Logo ROOT   6.07/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  xx[0] = fXaxis.GetBinLowEdge(binx);
815  cu = c1*f1->EvalPar(xx);
816  cu += c1*f1->Integral(fXaxis.GetBinLowEdge(binx), fXaxis.GetBinUpEdge(binx)) * fXaxis.GetBinWidth(binx);
817  } else {
818  cu = c1*f1->EvalPar(xx);
819  }
820  if (TF1::RejectedPoint()) continue;
821  AddBinContent(bin,cu);
822  }
823  }
824  }
825 
826  return kTRUE;
827 }
828 
829 ////////////////////////////////////////////////////////////////////////////////
830 /// Performs the operation: `this = this + c1*h1`
831 /// If errors are defined (see TH1::Sumw2), errors are also recalculated.
832 ///
833 /// Note that if h1 has Sumw2 set, Sumw2 is automatically called for this
834 /// if not already set.
835 ///
836 /// Note also that adding histogram with labels is not supported, histogram will be
837 /// added merging them by bin number independently of the labels.
838 /// For adding histogram with labels one should use TH1::Merge
839 ///
840 /// SPECIAL CASE (Average/Efficiency histograms)
841 /// For histograms representing averages or efficiencies, one should compute the average
842 /// of the two histograms and not the sum. One can mark a histogram to be an average
843 /// histogram by setting its bit kIsAverage with
844 /// myhist.SetBit(TH1::kIsAverage);
845 /// Note that the two histograms must have their kIsAverage bit set
846 ///
847 /// IMPORTANT NOTE1: If you intend to use the errors of this histogram later
848 /// you should call Sumw2 before making this operation.
849 /// This is particularly important if you fit the histogram after TH1::Add
850 ///
851 /// IMPORTANT NOTE2: if h1 has a normalisation factor, the normalisation factor
852 /// is used , ie this = this + c1*factor*h1
853 /// Use the other TH1::Add function if you do not want this feature
854 ///
855 /// The function return kFALSE if the Add operation failed
856 
858 {
859  if (!h1) {
860  Error("Add","Attempt to add a non-existing histogram");
861  return kFALSE;
862  }
863 
864  // delete buffer if it is there since it will become invalid
865  if (fBuffer) BufferEmpty(1);
866 
867  bool useMerge = (c1 == 1. && !this->TestBit(kIsAverage) && !h1->TestBit(kIsAverage) );
868  try {
869  CheckConsistency(this,h1);
870  useMerge = kFALSE;
871  } catch(DifferentNumberOfBins&) {
872  if (useMerge)
873  Info("Add","Attempt to add histograms with different number of bins - trying to use TH1::Merge");
874  else {
875  Error("Add","Attempt to add histograms with different number of bins : nbins h1 = %d , nbins h2 = %d",GetNbinsX(), h1->GetNbinsX());
876  return kFALSE;
877  }
878  } catch(DifferentAxisLimits&) {
879  if (useMerge)
880  Info("Add","Attempt to add histograms with different axis limits - trying to use TH1::Merge");
881  else
882  Warning("Add","Attempt to add histograms with different axis limits");
883  } catch(DifferentBinLimits&) {
884  if (useMerge)
885  Info("Add","Attempt to add histograms with different bin limits - trying to use TH1::Merge");
886  else
887  Warning("Add","Attempt to add histograms with different bin limits");
888  } catch(DifferentLabels&) {
889  // in case of different labels -
890  if (useMerge)
891  Info("Add","Attempt to add histograms with different labels - trying to use TH1::Merge");
892  else
893  Info("Warning","Attempt to add histograms with different labels");
894  }
895 
896  if (useMerge) {
897  TList l;
898  l.Add(const_cast<TH1*>(h1));
899  auto iret = Merge(&l);
900  return (iret >= 0);
901  }
902 
903  // Create Sumw2 if h1 has Sumw2 set
904  if (fSumw2.fN == 0 && h1->GetSumw2N() != 0) Sumw2();
905 
906  // - Add statistics
907  Double_t entries = TMath::Abs( GetEntries() + c1 * h1->GetEntries() );
908 
909  // statistics can be preserved only in case of positive coefficients
910  // otherwise with negative c1 (histogram subtraction) one risks to get negative variances
911  Bool_t resetStats = (c1 < 0);
912  Double_t s1[kNstat] = {0};
913  Double_t s2[kNstat] = {0};
914  if (!resetStats) {
915  // need to initialize to zero s1 and s2 since
916  // GetStats fills only used elements depending on dimension and type
917  GetStats(s1);
918  h1->GetStats(s2);
919  }
920 
921  SetMinimum();
922  SetMaximum();
923 
924  // - Loop on bins (including underflows/overflows)
925  Double_t factor = 1;
926  if (h1->GetNormFactor() != 0) factor = h1->GetNormFactor()/h1->GetSumOfWeights();;
927  Double_t c1sq = c1 * c1;
928  Double_t factsq = factor * factor;
929 
930  for (Int_t bin = 0; bin < fNcells; ++bin) {
931  //special case where histograms have the kIsAverage bit set
932  if (this->TestBit(kIsAverage) && h1->TestBit(kIsAverage)) {
933  Double_t y1 = h1->RetrieveBinContent(bin);
934  Double_t y2 = this->RetrieveBinContent(bin);
935  Double_t e1sq = h1->GetBinErrorSqUnchecked(bin);
936  Double_t e2sq = this->GetBinErrorSqUnchecked(bin);
937  Double_t w1 = 1., w2 = 1.;
938 
939  // consider all special cases when bin errors are zero
940  // see http://root.cern.ch/phpBB3//viewtopic.php?f=3&t=13299
941  if (e1sq) w1 = 1. / e1sq;
942  else if (h1->fSumw2.fN) {
943  w1 = 1.E200; // use an arbitrary huge value
944  if (y1 == 0) {
945  // use an estimated error from the global histogram scale
946  double sf = (s2[0] != 0) ? s2[1]/s2[0] : 1;
947  w1 = 1./(sf*sf);
948  }
949  }
950  if (e2sq) w2 = 1. / e2sq;
951  else if (fSumw2.fN) {
952  w2 = 1.E200; // use an arbitrary huge value
953  if (y2 == 0) {
954  // use an estimated error from the global histogram scale
955  double sf = (s1[0] != 0) ? s1[1]/s1[0] : 1;
956  w2 = 1./(sf*sf);
957  }
958  }
959 
960  double y = (w1*y1 + w2*y2)/(w1 + w2);
961  UpdateBinContent(bin, y);
962  if (fSumw2.fN) {
963  double err2 = 1./(w1 + w2);
964  if (err2 < 1.E-200) err2 = 0; // to remove arbitrary value when e1=0 AND e2=0
965  fSumw2.fArray[bin] = err2;
966  }
967  } else { // normal case of addition between histograms
968  AddBinContent(bin, c1 * factor * h1->RetrieveBinContent(bin));
969  if (fSumw2.fN) fSumw2.fArray[bin] += c1sq * factsq * h1->GetBinErrorSqUnchecked(bin);
970  }
971  }
972 
973  // update statistics (do here to avoid changes by SetBinContent)
974  if (resetStats) {
975  // statistics need to be reset in case coefficient are negative
976  ResetStats();
977  }
978  else {
979  for (Int_t i=0;i<kNstat;i++) {
980  if (i == 1) s1[i] += c1*c1*s2[i];
981  else s1[i] += c1*s2[i];
982  }
983  PutStats(s1);
984  SetEntries(entries);
985  }
986  return kTRUE;
987 }
988 
989 ////////////////////////////////////////////////////////////////////////////////
990 /// Replace contents of this histogram by the addition of h1 and h2.
991 ///
992 /// `this = c1*h1 + c2*h2`
993 /// if errors are defined (see TH1::Sumw2), errors are also recalculated
994 ///
995 /// Note that if h1 or h2 have Sumw2 set, Sumw2 is automatically called for this
996 /// if not already set.
997 ///
998 /// Note also that adding histogram with labels is not supported, histogram will be
999 /// added merging them by bin number independently of the labels.
1000 /// For adding histogram ith labels one should use TH1::Merge
1001 ///
1002 /// SPECIAL CASE (Average/Efficiency histograms)
1003 /// For histograms representing averages or efficiencies, one should compute the average
1004 /// of the two histograms and not the sum. One can mark a histogram to be an average
1005 /// histogram by setting its bit kIsAverage with
1006 /// myhist.SetBit(TH1::kIsAverage);
1007 /// Note that the two histograms must have their kIsAverage bit set
1008 ///
1009 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
1010 /// you should call Sumw2 before making this operation.
1011 /// This is particularly important if you fit the histogram after TH1::Add
1012 ///
1013 /// ANOTHER SPECIAL CASE : h1 = h2 and c2 < 0
1014 /// do a scaling this = c1 * h1 / (bin Volume)
1015 ///
1016 /// The function returns kFALSE if the Add operation failed
1017 
1019 {
1020 
1021  if (!h1 || !h2) {
1022  Error("Add","Attempt to add a non-existing histogram");
1023  return kFALSE;
1024  }
1025 
1026  // delete buffer if it is there since it will become invalid
1027  if (fBuffer) BufferEmpty(1);
1028 
1029  Bool_t normWidth = kFALSE;
1030  if (h1 == h2 && c2 < 0) {c2 = 0; normWidth = kTRUE;}
1031 
1032  if (h1 != h2) {
1033  bool useMerge = (c1 == 1. && c2 == 1. && !this->TestBit(kIsAverage) && !h1->TestBit(kIsAverage) );
1034 
1035  try {
1036  CheckConsistency(h1,h2);
1037  CheckConsistency(this,h1);
1038  useMerge = kFALSE;
1039  } catch(DifferentNumberOfBins&) {
1040  if (useMerge)
1041  Info("Add","Attempt to add histograms with different number of bins - trying to use TH1::Merge");
1042  else {
1043  Error("Add","Attempt to add histograms with different number of bins : nbins h1 = %d , nbins h2 = %d",GetNbinsX(), h1->GetNbinsX());
1044  return kFALSE;
1045  }
1046  } catch(DifferentAxisLimits&) {
1047  if (useMerge)
1048  Info("Add","Attempt to add histograms with different axis limits - trying to use TH1::Merge");
1049  else
1050  Warning("Add","Attempt to add histograms with different axis limits");
1051  } catch(DifferentBinLimits&) {
1052  if (useMerge)
1053  Info("Add","Attempt to add histograms with different bin limits - trying to use TH1::Merge");
1054  else
1055  Warning("Add","Attempt to add histograms with different bin limits");
1056  } catch(DifferentLabels&) {
1057  // in case of different labels -
1058  if (useMerge)
1059  Info("Add","Attempt to add histograms with different labels - trying to use TH1::Merge");
1060  else
1061  Info("Warning","Attempt to add histograms with different labels");
1062  }
1063 
1064  if (useMerge) {
1065  TList l;
1066  // why TList takes non-const pointers ????
1067  l.Add(const_cast<TH1*>(h1));
1068  l.Add(const_cast<TH1*>(h2));
1069  Reset("ICE");
1070  auto iret = Merge(&l);
1071  return (iret >= 0);
1072  }
1073  }
1074 
1075  // Create Sumw2 if h1 or h2 have Sumw2 set
1076  if (fSumw2.fN == 0 && (h1->GetSumw2N() != 0 || h2->GetSumw2N() != 0)) Sumw2();
1077 
1078  // - Add statistics
1079  Double_t nEntries = TMath::Abs( c1*h1->GetEntries() + c2*h2->GetEntries() );
1080 
1081  // TODO remove
1082  // statistics can be preserved only in case of positive coefficients
1083  // otherwise with negative c1 (histogram subtraction) one risks to get negative variances
1084  // also in case of scaling with the width we cannot preserve the statistics
1085  Double_t s1[kNstat] = {0};
1086  Double_t s2[kNstat] = {0};
1087  Double_t s3[kNstat];
1088 
1089 
1090  Bool_t resetStats = (c1*c2 < 0) || normWidth;
1091  if (!resetStats) {
1092  // need to initialize to zero s1 and s2 since
1093  // GetStats fills only used elements depending on dimension and type
1094  h1->GetStats(s1);
1095  h2->GetStats(s2);
1096  for (Int_t i=0;i<kNstat;i++) {
1097  if (i == 1) s3[i] = c1*c1*s1[i] + c2*c2*s2[i];
1098  //else s3[i] = TMath::Abs(c1)*s1[i] + TMath::Abs(c2)*s2[i];
1099  else s3[i] = c1*s1[i] + c2*s2[i];
1100  }
1101  }
1102 
1103  SetMinimum();
1104  SetMaximum();
1105 
1106  if (normWidth) { // DEPRECATED CASE: belongs to fitting / drawing modules
1107 
1108  Int_t nbinsx = GetNbinsX() + 2; // normal bins + underflow, overflow
1109  Int_t nbinsy = GetNbinsY() + 2;
1110  Int_t nbinsz = GetNbinsZ() + 2;
1111 
1112  if (fDimension < 2) nbinsy = 1;
1113  if (fDimension < 3) nbinsz = 1;
1114 
1115  Int_t bin, binx, biny, binz;
1116  for (binz = 0; binz < nbinsz; ++binz) {
1117  Double_t wz = h1->GetZaxis()->GetBinWidth(binz);
1118  for (biny = 0; biny < nbinsy; ++biny) {
1119  Double_t wy = h1->GetYaxis()->GetBinWidth(biny);
1120  for (binx = 0; binx < nbinsx; ++binx) {
1121  Double_t wx = h1->GetXaxis()->GetBinWidth(binx);
1122  bin = GetBin(binx, biny, binz);
1123  Double_t w = wx*wy*wz;
1124  UpdateBinContent(bin, c1 * h1->RetrieveBinContent(bin) / w);
1125  if (fSumw2.fN) {
1126  Double_t e1 = h1->GetBinError(bin)/w;
1127  fSumw2.fArray[bin] = c1*c1*e1*e1;
1128  }
1129  }
1130  }
1131  }
1132  } else if (h1->TestBit(kIsAverage) && h2->TestBit(kIsAverage)) {
1133  for (Int_t i = 0; i < fNcells; ++i) { // loop on cells (bins including underflow / overflow)
1134  // special case where histograms have the kIsAverage bit set
1135  Double_t y1 = h1->RetrieveBinContent(i);
1136  Double_t y2 = h2->RetrieveBinContent(i);
1137  Double_t e1sq = h1->GetBinErrorSqUnchecked(i);
1138  Double_t e2sq = h2->GetBinErrorSqUnchecked(i);
1139  Double_t w1 = 1., w2 = 1.;
1140 
1141  // consider all special cases when bin errors are zero
1142  // see http://root.cern.ch/phpBB3//viewtopic.php?f=3&t=13299
1143  if (e1sq) w1 = 1./ e1sq;
1144  else if (h1->fSumw2.fN) {
1145  w1 = 1.E200; // use an arbitrary huge value
1146  if (y1 == 0 ) { // use an estimated error from the global histogram scale
1147  double sf = (s1[0] != 0) ? s1[1]/s1[0] : 1;
1148  w1 = 1./(sf*sf);
1149  }
1150  }
1151  if (e2sq) w2 = 1./ e2sq;
1152  else if (h2->fSumw2.fN) {
1153  w2 = 1.E200; // use an arbitrary huge value
1154  if (y2 == 0) { // use an estimated error from the global histogram scale
1155  double sf = (s2[0] != 0) ? s2[1]/s2[0] : 1;
1156  w2 = 1./(sf*sf);
1157  }
1158  }
1159 
1160  double y = (w1*y1 + w2*y2)/(w1 + w2);
1161  UpdateBinContent(i, y);
1162  if (fSumw2.fN) {
1163  double err2 = 1./(w1 + w2);
1164  if (err2 < 1.E-200) err2 = 0; // to remove arbitrary value when e1=0 AND e2=0
1165  fSumw2.fArray[i] = err2;
1166  }
1167  }
1168  } else { // case of simple histogram addition
1169  Double_t c1sq = c1 * c1;
1170  Double_t c2sq = c2 * c2;
1171  for (Int_t i = 0; i < fNcells; ++i) { // Loop on cells (bins including underflows/overflows)
1172  UpdateBinContent(i, c1 * h1->RetrieveBinContent(i) + c2 * h2->RetrieveBinContent(i));
1173  if (fSumw2.fN) {
1174  fSumw2.fArray[i] = c1sq * h1->GetBinErrorSqUnchecked(i) + c2sq * h2->GetBinErrorSqUnchecked(i);
1175  }
1176  }
1177  }
1178 
1179  if (resetStats) {
1180  // statistics need to be reset in case coefficient are negative
1181  ResetStats();
1182  }
1183  else {
1184  // update statistics (do here to avoid changes by SetBinContent) FIXME remove???
1185  PutStats(s3);
1186  SetEntries(nEntries);
1187  }
1188 
1189  return kTRUE;
1190 }
1191 
1192 ////////////////////////////////////////////////////////////////////////////////
1193 /// Increment bin content by 1.
1194 
1196 {
1197  AbstractMethod("AddBinContent");
1198 }
1199 
1200 ////////////////////////////////////////////////////////////////////////////////
1201 /// Increment bin content by a weight w.
1202 
1204 {
1205  AbstractMethod("AddBinContent");
1206 }
1207 
1208 ////////////////////////////////////////////////////////////////////////////////
1209 /// Sets the flag controlling the automatic add of histograms in memory
1210 ///
1211 /// By default (fAddDirectory = kTRUE), histograms are automatically added
1212 /// to the list of objects in memory.
1213 /// Note that one histogram can be removed from its support directory
1214 /// by calling h->SetDirectory(0) or h->SetDirectory(dir) to add it
1215 /// to the list of objects in the directory dir.
1216 ///
1217 /// NOTE that this is a static function. To call it, use;
1218 /// TH1::AddDirectory
1219 
1221 {
1222  fgAddDirectory = add;
1223 }
1224 
1225 ////////////////////////////////////////////////////////////////////////////////
1226 /// Fill histogram with all entries in the buffer.
1227 ///
1228 /// - action = -1 histogram is reset and refilled from the buffer (called by THistPainter::Paint)
1229 /// - action = 0 histogram is reset and filled from the buffer. When the histogram is filled from the
1230 /// buffer the value fBuffer[0] is set to a negative number (= - number of entries)
1231 /// When calling with action == 0 the histogram is NOT refilled when fBuffer[0] is < 0
1232 /// While when calling with action = -1 the histogram is reset and ALWAYS refilled independently if
1233 /// the histogram was filled before. This is needed when drawing the histogram
1234 /// - action = 1 histogram is filled and buffer is deleted
1235 /// The buffer is automatically deleted when filling the histogram and the entries is
1236 /// larger than the buffer size
1237 
1239 {
1240  // do we need to compute the bin size?
1241  if (!fBuffer) return 0;
1242  Int_t nbentries = (Int_t)fBuffer[0];
1243 
1244  // nbentries correspond to the number of entries of histogram
1245 
1246  if (nbentries == 0) {
1247  // if action is 1 we delete the buffer
1248  // this will avoid infinite recursion
1249  if (action > 0) {
1250  delete [] fBuffer;
1251  fBuffer = 0;
1252  fBufferSize = 0;
1253  }
1254  return 0;
1255  }
1256  if (nbentries < 0 && action == 0) return 0; // case histogram has been already filled from the buffer
1257 
1258  Double_t *buffer = fBuffer;
1259  if (nbentries < 0) {
1260  nbentries = -nbentries;
1261  // a reset might call BufferEmpty() giving an infinite recursion
1262  // Protect it by setting fBuffer = 0
1263  fBuffer=0;
1264  //do not reset the list of functions
1265  Reset("ICES");
1266  fBuffer = buffer;
1267  }
1268  if (CanExtendAllAxes() || (fXaxis.GetXmax() <= fXaxis.GetXmin())) {
1269  //find min, max of entries in buffer
1270  Double_t xmin = fBuffer[2];
1271  Double_t xmax = xmin;
1272  for (Int_t i=1;i<nbentries;i++) {
1273  Double_t x = fBuffer[2*i+2];
1274  if (x < xmin) xmin = x;
1275  if (x > xmax) xmax = x;
1276  }
1277  if (fXaxis.GetXmax() <= fXaxis.GetXmin()) {
1279  } else {
1280  fBuffer = 0;
1281  Int_t keep = fBufferSize; fBufferSize = 0;
1282  if (xmin < fXaxis.GetXmin()) ExtendAxis(xmin,&fXaxis);
1283  if (xmax >= fXaxis.GetXmax()) ExtendAxis(xmax,&fXaxis);
1284  fBuffer = buffer;
1285  fBufferSize = keep;
1286  }
1287  }
1288 
1289  // call DoFillN which will not put entries in the buffer as FillN does
1290  // set fBuffer to zero to avoid re-emptying the buffer from functions called
1291  // by DoFillN (e.g Sumw2)
1292  buffer = fBuffer; fBuffer = 0;
1293  DoFillN(nbentries,&buffer[2],&buffer[1],2);
1294  fBuffer = buffer;
1295 
1296  // if action == 1 - delete the buffer
1297  if (action > 0) {
1298  delete [] fBuffer;
1299  fBuffer = 0;
1300  fBufferSize = 0;}
1301  else {
1302  // if number of entries is consistent with buffer - set it negative to avoid
1303  // refilling the histogram every time BufferEmpty(0) is called
1304  // In case it is not consistent, by setting fBuffer[0]=0 is like resetting the buffer
1305  // (it will not be used anymore the next time BufferEmpty is called)
1306  if (nbentries == (Int_t)fEntries)
1307  fBuffer[0] = -nbentries;
1308  else
1309  fBuffer[0] = 0;
1310  }
1311  return nbentries;
1312 }
1313 
1314 ////////////////////////////////////////////////////////////////////////////////
1315 /// accumulate arguments in buffer. When buffer is full, empty the buffer
1316 ///
1317 /// - `fBuffer[0]` = number of entries in buffer
1318 /// - `fBuffer[1]` = w of first entry
1319 /// - `fBuffer[2]` = x of first entry
1320 
1322 {
1323  if (!fBuffer) return -2;
1324  Int_t nbentries = (Int_t)fBuffer[0];
1325 
1326 
1327  if (nbentries < 0) {
1328  // reset nbentries to a positive value so next time BufferEmpty() is called
1329  // the histogram will be refilled
1330  nbentries = -nbentries;
1331  fBuffer[0] = nbentries;
1332  if (fEntries > 0) {
1333  // set fBuffer to zero to avoid calling BufferEmpty in Reset
1334  Double_t *buffer = fBuffer; fBuffer=0;
1335  Reset("ICES"); // do not reset list of functions
1336  fBuffer = buffer;
1337  }
1338  }
1339  if (2*nbentries+2 >= fBufferSize) {
1340  BufferEmpty(1);
1341  if (!fBuffer)
1342  // to avoid infinite recursion Fill->BufferFill->Fill
1343  return Fill(x,w);
1344  // this cannot happen
1345  R__ASSERT(0);
1346  }
1347  fBuffer[2*nbentries+1] = w;
1348  fBuffer[2*nbentries+2] = x;
1349  fBuffer[0] += 1;
1350  return -2;
1351 }
1352 
1353 ////////////////////////////////////////////////////////////////////////////////
1354 /// Check bin limits.
1355 
1356 bool TH1::CheckBinLimits(const TAxis* a1, const TAxis * a2)
1357 {
1358  const TArrayD * h1Array = a1->GetXbins();
1359  const TArrayD * h2Array = a2->GetXbins();
1360  Int_t fN = h1Array->fN;
1361  if ( fN != 0 ) {
1362  if ( h2Array->fN != fN ) {
1363  throw DifferentBinLimits();
1364  return false;
1365  }
1366  else {
1367  for ( int i = 0; i < fN; ++i ) {
1368  if ( ! TMath::AreEqualRel( h1Array->GetAt(i), h2Array->GetAt(i), 1E-10 ) ) {
1369  throw DifferentBinLimits();
1370  return false;
1371  }
1372  }
1373  }
1374  }
1375 
1376  return true;
1377 }
1378 
1379 ////////////////////////////////////////////////////////////////////////////////
1380 /// Check that axis have same labels.
1381 
1382 bool TH1::CheckBinLabels(const TAxis* a1, const TAxis * a2)
1383 {
1384  THashList *l1 = a1->GetLabels();
1385  THashList *l2 = a2->GetLabels();
1386 
1387  if (!l1 && !l2 )
1388  return true;
1389  if (!l1 || !l2 ) {
1390  throw DifferentLabels();
1391  return false;
1392  }
1393  // check now labels sizes are the same
1394  if (l1->GetSize() != l2->GetSize() ) {
1395  throw DifferentLabels();
1396  return false;
1397  }
1398  for (int i = 1; i <= a1->GetNbins(); ++i) {
1399  TString label1 = a1->GetBinLabel(i);
1400  TString label2 = a2->GetBinLabel(i);
1401  if (label1 != label2) {
1402  throw DifferentLabels();
1403  return false;
1404  }
1405  }
1406 
1407  return true;
1408 }
1409 
1410 ////////////////////////////////////////////////////////////////////////////////
1411 /// Check that the axis limits of the histograms are the same.
1412 /// If a first and last bin is passed the axis is compared between the given range
1413 
1414 bool TH1::CheckAxisLimits(const TAxis *a1, const TAxis *a2 )
1415 {
1416  if ( ! TMath::AreEqualRel(a1->GetXmin(), a2->GetXmin(),1.E-12) ||
1417  ! TMath::AreEqualRel(a1->GetXmax(), a2->GetXmax(),1.E-12) ) {
1418  throw DifferentAxisLimits();
1419  return false;
1420  }
1421  return true;
1422 }
1423 
1424 ////////////////////////////////////////////////////////////////////////////////
1425 /// Check that the axis are the same
1426 
1427 bool TH1::CheckEqualAxes(const TAxis *a1, const TAxis *a2 )
1428 {
1429  if (a1->GetNbins() != a2->GetNbins() ) {
1430  //throw DifferentNumberOfBins();
1431  ::Info("CheckEqualAxes","Axes have different number of bins : nbin1 = %d nbin2 = %d",a1->GetNbins(),a2->GetNbins() );
1432  return false;
1433  }
1434  try {
1435  CheckAxisLimits(a1,a2);
1436  } catch (DifferentAxisLimits&) {
1437  ::Info("CheckEqualAxes","Axes have different limits");
1438  return false;
1439  }
1440  try {
1441  CheckBinLimits(a1,a2);
1442  } catch (DifferentBinLimits&) {
1443  ::Info("CheckEqualAxes","Axes have different bin limits");
1444  return false;
1445  }
1446 
1447  // check labels
1448  try {
1449  CheckBinLabels(a1,a2);
1450  } catch (DifferentLabels&) {
1451  ::Info("CheckEqualAxes","Axes have different labels");
1452  return false;
1453  }
1454 
1455  return true;
1456 }
1457 
1458 ////////////////////////////////////////////////////////////////////////////////
1459 /// Check that two sub axis are the same.
1460 /// The limits are defined by first bin and last bin
1461 /// N.B. no check is done in this case for variable bins
1462 
1463 bool TH1::CheckConsistentSubAxes(const TAxis *a1, Int_t firstBin1, Int_t lastBin1, const TAxis * a2, Int_t firstBin2, Int_t lastBin2 )
1464 {
1465  // By default is assumed that no bins are given for the second axis
1466  Int_t nbins1 = lastBin1-firstBin1 + 1;
1467  Double_t xmin1 = a1->GetBinLowEdge(firstBin1);
1468  Double_t xmax1 = a1->GetBinUpEdge(lastBin1);
1469 
1470  Int_t nbins2 = a2->GetNbins();
1471  Double_t xmin2 = a2->GetXmin();
1472  Double_t xmax2 = a2->GetXmax();
1473 
1474  if (firstBin2 < lastBin2) {
1475  // in this case assume no bins are given for the second axis
1476  nbins2 = lastBin1-firstBin1 + 1;
1477  xmin2 = a1->GetBinLowEdge(firstBin1);
1478  xmax2 = a1->GetBinUpEdge(lastBin1);
1479  }
1480 
1481  if (nbins1 != nbins2 ) {
1482  ::Info("CheckConsistentSubAxes","Axes have different number of bins");
1483  return false;
1484  }
1485 
1486  if ( ! TMath::AreEqualRel(xmin1,xmin2,1.E-12) ||
1487  ! TMath::AreEqualRel(xmax1,xmax2,1.E-12) ) {
1488  ::Info("CheckConsistentSubAxes","Axes have different limits");
1489  return false;
1490  }
1491 
1492  return true;
1493 }
1494 
1495 ////////////////////////////////////////////////////////////////////////////////
1496 /// Check histogram compatibility.
1497 
1498 bool TH1::CheckConsistency(const TH1* h1, const TH1* h2)
1499 {
1500  if (h1 == h2) return true;
1501 
1502  if (h1->GetDimension() != h2->GetDimension() ) {
1503  throw DifferentDimension();
1504  return false;
1505  }
1506  Int_t dim = h1->GetDimension();
1507 
1508  // returns kTRUE if number of bins and bin limits are identical
1509  Int_t nbinsx = h1->GetNbinsX();
1510  Int_t nbinsy = h1->GetNbinsY();
1511  Int_t nbinsz = h1->GetNbinsZ();
1512 
1513  // Check whether the histograms have the same number of bins.
1514  if (nbinsx != h2->GetNbinsX() ||
1515  (dim > 1 && nbinsy != h2->GetNbinsY()) ||
1516  (dim > 2 && nbinsz != h2->GetNbinsZ()) ) {
1517  throw DifferentNumberOfBins();
1518  return false;
1519  }
1520 
1521  bool ret = true;
1522 
1523  // check axis limits
1524  ret &= CheckAxisLimits(h1->GetXaxis(), h2->GetXaxis());
1525  if (dim > 1) ret &= CheckAxisLimits(h1->GetYaxis(), h2->GetYaxis());
1526  if (dim > 2) ret &= CheckAxisLimits(h1->GetZaxis(), h2->GetZaxis());
1527 
1528  // check bin limits
1529  ret &= CheckBinLimits(h1->GetXaxis(), h2->GetXaxis());
1530  if (dim > 1) ret &= CheckBinLimits(h1->GetYaxis(), h2->GetYaxis());
1531  if (dim > 2) ret &= CheckBinLimits(h1->GetZaxis(), h2->GetZaxis());
1532 
1533  // check labels if histograms are both not empty
1534  if ( (h1->fTsumw != 0 || h1->GetEntries() != 0) &&
1535  (h2->fTsumw != 0 || h2->GetEntries() != 0) ) {
1536  ret &= CheckBinLabels(h1->GetXaxis(), h2->GetXaxis());
1537  if (dim > 1) ret &= CheckBinLabels(h1->GetYaxis(), h2->GetYaxis());
1538  if (dim > 2) ret &= CheckBinLabels(h1->GetZaxis(), h2->GetZaxis());
1539  }
1540 
1541  return ret;
1542 }
1543 
1544 ////////////////////////////////////////////////////////////////////////////////
1545 /// \f$ \chi^{2} \f$ test for comparing weighted and unweighted histograms
1546 ///
1547 /// Function: Returns p-value. Other return values are specified by the 3rd parameter
1548 ///
1549 /// \param[in] h2 the second histogram
1550 /// \param[in] option
1551 /// - "UU" = experiment experiment comparison (unweighted-unweighted)
1552 /// - "UW" = experiment MC comparison (unweighted-weighted). Note that
1553 /// the first histogram should be unweighted
1554 /// - "WW" = MC MC comparison (weighted-weighted)
1555 /// - "NORM" = to be used when one or both of the histograms is scaled
1556 /// but the histogram originally was unweighted
1557 /// - by default underflows and overflows are not included:
1558 /// * "OF" = overflows included
1559 /// * "UF" = underflows included
1560 /// - "P" = print chi2, ndf, p_value, igood
1561 /// - "CHI2" = returns chi2 instead of p-value
1562 /// - "CHI2/NDF" = returns \f$ \chi^{2} \f$/ndf
1563 /// \param[in] res not empty - computes normalized residuals and returns them in this array
1564 ///
1565 /// The current implementation is based on the papers \f$ \chi^{2} \f$ test for comparison
1566 /// of weighted and unweighted histograms" in Proceedings of PHYSTAT05 and
1567 /// "Comparison weighted and unweighted histograms", arXiv:physics/0605123
1568 /// by N.Gagunashvili. This function has been implemented by Daniel Haertl in August 2006.
1569 ///
1570 /// #### Introduction:
1571 ///
1572 /// A frequently used technique in data analysis is the comparison of
1573 /// histograms. First suggested by Pearson [1] the \f$ \chi^{2} \f$ test of
1574 /// homogeneity is used widely for comparing usual (unweighted) histograms.
1575 /// This paper describes the implementation modified \f$ \chi^{2} \f$ tests
1576 /// for comparison of weighted and unweighted histograms and two weighted
1577 /// histograms [2] as well as usual Pearson's \f$ \chi^{2} \f$ test for
1578 /// comparison two usual (unweighted) histograms.
1579 ///
1580 /// #### Overview:
1581 ///
1582 /// Comparison of two histograms expect hypotheses that two histograms
1583 /// represent identical distributions. To make a decision p-value should
1584 /// be calculated. The hypotheses of identity is rejected if the p-value is
1585 /// lower then some significance level. Traditionally significance levels
1586 /// 0.1, 0.05 and 0.01 are used. The comparison procedure should include an
1587 /// analysis of the residuals which is often helpful in identifying the
1588 /// bins of histograms responsible for a significant overall \f$ \chi^{2} \f$ value.
1589 /// Residuals are the difference between bin contents and expected bin
1590 /// contents. Most convenient for analysis are the normalized residuals. If
1591 /// hypotheses of identity are valid then normalized residuals are
1592 /// approximately independent and identically distributed random variables
1593 /// having N(0,1) distribution. Analysis of residuals expect test of above
1594 /// mentioned properties of residuals. Notice that indirectly the analysis
1595 /// of residuals increase the power of \f$ \chi^{2} \f$ test.
1596 ///
1597 /// #### Methods of comparison:
1598 ///
1599 /// \f$ \chi^{2} \f$ test for comparison two (unweighted) histograms:
1600 /// Let us consider two histograms with the same binning and the number
1601 /// of bins equal to r. Let us denote the number of events in the ith bin
1602 /// in the first histogram as ni and as mi in the second one. The total
1603 /// number of events in the first histogram is equal to:
1604 /// \f[
1605 /// N = \sum_{i=1}^{r} n_{i}
1606 /// \f]
1607 /// and
1608 /// \f[
1609 /// M = \sum_{i=1}^{r} m_{i}
1610 /// \f]
1611 /// in the second histogram. The hypothesis of identity (homogeneity) [3]
1612 /// is that the two histograms represent random values with identical
1613 /// distributions. It is equivalent that there exist r constants p1,...,pr,
1614 /// such that
1615 /// \f[
1616 ///\sum_{i=1}^{r} p_{i}=1
1617 /// \f]
1618 /// and the probability of belonging to the ith bin for some measured value
1619 /// in both experiments is equal to pi. The number of events in the ith
1620 /// bin is a random variable with a distribution approximated by a Poisson
1621 /// probability distribution
1622 /// \f[
1623 ///\frac{e^{-Np_{i}}(Np_{i})^{n_{i}}}{n_{i}!}
1624 /// \f]
1625 ///for the first histogram and with distribution
1626 /// \f[
1627 ///\frac{e^{-Mp_{i}}(Mp_{i})^{m_{i}}}{m_{i}!}
1628 /// \f]
1629 /// for the second histogram. If the hypothesis of homogeneity is valid,
1630 /// then the maximum likelihood estimator of pi, i=1,...,r, is
1631 /// \f[
1632 ///\hat{p}_{i}= \frac{n_{i}+m_{i}}{N+M}
1633 /// \f]
1634 /// and then
1635 /// \f[
1636 /// 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}}
1637 /// \f]
1638 /// has approximately a \f$ \chi^{2}_{(r-1)} \f$ distribution [3].
1639 /// The comparison procedure can include an analysis of the residuals which
1640 /// is often helpful in identifying the bins of histograms responsible for
1641 /// a significant overall \f$ \chi^{2} \f$ value. Most convenient for
1642 /// analysis are the adjusted (normalized) residuals [4]
1643 /// \f[
1644 /// 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))}}
1645 /// \f]
1646 /// If hypotheses of homogeneity are valid then residuals ri are
1647 /// approximately independent and identically distributed random variables
1648 /// having N(0,1) distribution. The application of the \f$ \chi^{2} \f$ test has
1649 /// restrictions related to the value of the expected frequencies Npi,
1650 /// Mpi, i=1,...,r. A conservative rule formulated in [5] is that all the
1651 /// expectations must be 1 or greater for both histograms. In practical
1652 /// cases when expected frequencies are not known the estimated expected
1653 /// frequencies \f$ M\hat{p}_{i}, N\hat{p}_{i}, i=1,...,r \f$ can be used.
1654 ///
1655 /// #### Unweighted and weighted histograms comparison:
1656 ///
1657 /// A simple modification of the ideas described above can be used for the
1658 /// comparison of the usual (unweighted) and weighted histograms. Let us
1659 /// denote the number of events in the ith bin in the unweighted
1660 /// histogram as ni and the common weight of events in the ith bin of the
1661 /// weighted histogram as wi. The total number of events in the
1662 /// unweighted histogram is equal to
1663 ///\f[
1664 /// N = \sum_{i=1}^{r} n_{i}
1665 ///\f]
1666 /// and the total weight of events in the weighted histogram is equal to
1667 ///\f[
1668 /// W = \sum_{i=1}^{r} w_{i}
1669 ///\f]
1670 /// Let us formulate the hypothesis of identity of an unweighted histogram
1671 /// to a weighted histogram so that there exist r constants p1,...,pr, such
1672 /// that
1673 ///\f[
1674 /// \sum_{i=1}^{r} p_{i} = 1
1675 ///\f]
1676 /// for the unweighted histogram. The weight wi is a random variable with a
1677 /// distribution approximated by the normal probability distribution
1678 /// \f$ N(Wp_{i},\sigma_{i}^{2}) \f$ where \f$ \sigma_{i}^{2} \f$ is the variance of the weight wi.
1679 /// If we replace the variance \f$ \sigma_{i}^{2} \f$
1680 /// with estimate \f$ s_{i}^{2} \f$ (sum of squares of weights of
1681 /// events in the ith bin) and the hypothesis of identity is valid, then the
1682 /// maximum likelihood estimator of pi,i=1,...,r, is
1683 ///\f[
1684 /// \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}}
1685 ///\f]
1686 /// We may then use the test statistic
1687 ///\f[
1688 /// 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}}
1689 ///\f]
1690 /// and it has approximately a \f$ \sigma^{2}_{(r-1)} \f$ distribution [2]. This test, as well
1691 /// as the original one [3], has a restriction on the expected frequencies. The
1692 /// expected frequencies recommended for the weighted histogram is more than 25.
1693 /// The value of the minimal expected frequency can be decreased down to 10 for
1694 /// the case when the weights of the events are close to constant. In the case
1695 /// of a weighted histogram if the number of events is unknown, then we can
1696 /// apply this recommendation for the equivalent number of events as
1697 ///\f[
1698 /// n_{i}^{equiv} = \frac{ w_{i}^{2} }{ s_{i}^{2} }
1699 ///\f]
1700 /// The minimal expected frequency for an unweighted histogram must be 1. Notice
1701 /// that any usual (unweighted) histogram can be considered as a weighted
1702 /// histogram with events that have constant weights equal to 1.
1703 /// The variance \f$ z_{i}^{2} \f$ of the difference between the weight wi
1704 /// and the estimated expectation value of the weight is approximately equal to:
1705 ///\f[
1706 /// 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}
1707 ///\f]
1708 /// The residuals
1709 ///\f[
1710 /// r_{i} = \frac{w_{i}-W\hat{p}_{i}}{z_{i}}
1711 ///\f]
1712 /// have approximately a normal distribution with mean equal to 0 and standard
1713 /// deviation equal to 1.
1714 ///
1715 /// #### Two weighted histograms comparison:
1716 ///
1717 /// Let us denote the common weight of events of the ith bin in the first
1718 /// histogram as w1i and as w2i in the second one. The total weight of events
1719 /// in the first histogram is equal to
1720 ///\f[
1721 /// W_{1} = \sum_{i=1}^{r} w_{1i}
1722 ///\f]
1723 /// and
1724 ///\f[
1725 /// W_{2} = \sum_{i=1}^{r} w_{2i}
1726 ///\f]
1727 /// in the second histogram. Let us formulate the hypothesis of identity of
1728 /// weighted histograms so that there exist r constants p1,...,pr, such that
1729 ///\f[
1730 /// \sum_{i=1}^{r} p_{i} = 1
1731 ///\f]
1732 /// and also expectation value of weight w1i equal to W1pi and expectation value
1733 /// of weight w2i equal to W2pi. Weights in both the histograms are random
1734 /// variables with distributions which can be approximated by a normal
1735 /// probability distribution \f$ N(W_{1}p_{i},\sigma_{1i}^{2}) \f$ for the first histogram
1736 /// and by a distribution \f$ N(W_{2}p_{i},\sigma_{2i}^{2}) \f$ for the second.
1737 /// Here \f$ \sigma_{1i}^{2} \f$ and \f$ \sigma_{2i}^{2} \f$ are the variances
1738 /// of w1i and w2i with estimators \f$ s_{1i}^{2} \f$ and \f$ s_{2i}^{2} \f$ respectively.
1739 /// If the hypothesis of identity is valid, then the maximum likelihood and
1740 /// Least Square Method estimator of pi,i=1,...,r, is
1741 ///\f[
1742 /// \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}}
1743 ///\f]
1744 /// We may then use the test statistic
1745 ///\f[
1746 /// 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}}
1747 ///\f]
1748 /// and it has approximately a \f$ \chi^{2}_{(r-1)} \f$ distribution [2].
1749 /// The normalized or studentised residuals [6]
1750 ///\f[
1751 /// 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})}}}
1752 ///\f]
1753 /// have approximately a normal distribution with mean equal to 0 and standard
1754 /// deviation 1. A recommended minimal expected frequency is equal to 10 for
1755 /// the proposed test.
1756 ///
1757 /// #### Numerical examples:
1758 ///
1759 /// The method described herein is now illustrated with an example.
1760 /// We take a distribution
1761 ///\f[
1762 /// \phi(x) = \frac{2}{(x-10)^{2}+1} + \frac{1}{(x-14)^{2}+1} (1)
1763 ///\f]
1764 /// defined on the interval [4,16]. Events distributed according to the formula
1765 /// (1) are simulated to create the unweighted histogram. Uniformly distributed
1766 /// events are simulated for the weighted histogram with weights calculated by
1767 /// formula (1). Each histogram has the same number of bins: 20. Fig.1 shows
1768 /// the result of comparison of the unweighted histogram with 200 events
1769 /// (minimal expected frequency equal to one) and the weighted histogram with
1770 /// 500 events (minimal expected frequency equal to 25)
1771 /// Begin_Macro
1772 /// ../../../tutorials/math/chi2test.C
1773 /// End_Macro
1774 /// Fig 1. An example of comparison of the unweighted histogram with 200 events
1775 /// and the weighted histogram with 500 events:
1776 /// 1. unweighted histogram;
1777 /// 2. weighted histogram;
1778 /// 3. normalized residuals plot;
1779 /// 4. normal Q-Q plot of residuals.
1780 ///
1781 /// The value of the test statistic \f$ \chi^{2} \f$ is equal to
1782 /// 21.09 with p-value equal to 0.33, therefore the hypothesis of identity of
1783 /// the two histograms can be accepted for 0.05 significant level. The behavior
1784 /// of the normalized residuals plot (see Fig. 1c) and the normal Q-Q plot
1785 /// (see Fig. 1d) of residuals are regular and we cannot identify the outliers
1786 /// or bins with a big influence on \f$ \chi^{2} \f$.
1787 ///
1788 /// The second example presents the same two histograms but 17 events was added
1789 /// to content of bin number 15 in unweighted histogram. Fig.2 shows the result
1790 /// of comparison of the unweighted histogram with 217 events (minimal expected
1791 /// frequency equal to one) and the weighted histogram with 500 events (minimal
1792 /// expected frequency equal to 25)
1793 /// Begin_Macro
1794 /// ../../../tutorials/math/chi2test.C(17)
1795 /// End_Macro
1796 /// Fig 2. An example of comparison of the unweighted histogram with 217 events
1797 /// and the weighted histogram with 500 events:
1798 /// 1. unweighted histogram;
1799 /// 2. weighted histogram;
1800 /// 3. normalized residuals plot;
1801 /// 4. normal Q-Q plot of residuals.
1802 ///
1803 /// The value of the test statistic \f$ \chi^{2} \f$ is equal to
1804 /// 32.33 with p-value equal to 0.029, therefore the hypothesis of identity of
1805 /// the two histograms is rejected for 0.05 significant level. The behavior of
1806 /// the normalized residuals plot (see Fig. 2c) and the normal Q-Q plot (see
1807 /// Fig. 2d) of residuals are not regular and we can identify the outlier or
1808 /// bin with a big influence on \f$ \chi^{2} \f$.
1809 ///
1810 /// #### References:
1811 ///
1812 /// - [1] Pearson, K., 1904. On the Theory of Contingency and Its Relation to
1813 /// Association and Normal Correlation. Drapers' Co. Memoirs, Biometric
1814 /// Series No. 1, London.
1815 /// - [2] Gagunashvili, N., 2006. \f$ \sigma^{2} \f$ test for comparison
1816 /// of weighted and unweighted histograms. Statistical Problems in Particle
1817 /// Physics, Astrophysics and Cosmology, Proceedings of PHYSTAT05,
1818 /// Oxford, UK, 12-15 September 2005, Imperial College Press, London, 43-44.
1819 /// Gagunashvili,N., Comparison of weighted and unweighted histograms,
1820 /// arXiv:physics/0605123, 2006.
1821 /// - [3] Cramer, H., 1946. Mathematical methods of statistics.
1822 /// Princeton University Press, Princeton.
1823 /// - [4] Haberman, S.J., 1973. The analysis of residuals in cross-classified tables.
1824 /// Biometrics 29, 205-220.
1825 /// - [5] Lewontin, R.C. and Felsenstein, J., 1965. The robustness of homogeneity
1826 /// test in 2xN tables. Biometrics 21, 19-33.
1827 /// - [6] Seber, G.A.F., Lee, A.J., 2003, Linear Regression Analysis.
1828 /// John Wiley & Sons Inc., New York.
1829 
1830 Double_t TH1::Chi2Test(const TH1* h2, Option_t *option, Double_t *res) const
1831 {
1832  Double_t chi2 = 0;
1833  Int_t ndf = 0, igood = 0;
1834 
1835  TString opt = option;
1836  opt.ToUpper();
1837 
1838  Double_t prob = Chi2TestX(h2,chi2,ndf,igood,option,res);
1839 
1840  if(opt.Contains("P")) {
1841  printf("Chi2 = %f, Prob = %g, NDF = %d, igood = %d\n", chi2,prob,ndf,igood);
1842  }
1843  if(opt.Contains("CHI2/NDF")) {
1844  if (ndf == 0) return 0;
1845  return chi2/ndf;
1846  }
1847  if(opt.Contains("CHI2")) {
1848  return chi2;
1849  }
1850 
1851  return prob;
1852 }
1853 
1854 ////////////////////////////////////////////////////////////////////////////////
1855 /// The computation routine of the Chisquare test. For the method description,
1856 /// see Chi2Test() function.
1857 ///
1858 /// \return p-value
1859 /// \param[in] h2 the second histogram
1860 /// \param[in] option
1861 /// - "UU" = experiment experiment comparison (unweighted-unweighted)
1862 /// - "UW" = experiment MC comparison (unweighted-weighted). Note that the first
1863 /// histogram should be unweighted
1864 /// - "WW" = MC MC comparison (weighted-weighted)
1865 /// - "NORM" = if one or both histograms is scaled
1866 /// - "OF" = overflows included
1867 /// - "UF" = underflows included
1868 /// by default underflows and overflows are not included
1869 /// \param[out] igood test output
1870 /// - igood=0 - no problems
1871 /// - For unweighted unweighted comparison
1872 /// - igood=1'There is a bin in the 1st histogram with less than 1 event'
1873 /// - igood=2'There is a bin in the 2nd histogram with less than 1 event'
1874 /// - igood=3'when the conditions for igood=1 and igood=2 are satisfied'
1875 /// - For unweighted weighted comparison
1876 /// - igood=1'There is a bin in the 1st histogram with less then 1 event'
1877 /// - igood=2'There is a bin in the 2nd histogram with less then 10 effective number of events'
1878 /// - igood=3'when the conditions for igood=1 and igood=2 are satisfied'
1879 /// - For weighted weighted comparison
1880 /// - igood=1'There is a bin in the 1st histogram with less then 10 effective
1881 /// number of events'
1882 /// - igood=2'There is a bin in the 2nd histogram with less then 10 effective
1883 /// number of events'
1884 /// - igood=3'when the conditions for igood=1 and igood=2 are satisfied'
1885 /// \param[out] chi2 chisquare of the test
1886 /// \param[out] ndf number of degrees of freedom (important, when both histograms have the same empty bins)
1887 /// \param[out] res normalized residuals for further analysis
1888 
1889 Double_t TH1::Chi2TestX(const TH1* h2, Double_t &chi2, Int_t &ndf, Int_t &igood, Option_t *option, Double_t *res) const
1890 {
1892  Int_t i_start, i_end;
1893  Int_t j_start, j_end;
1894  Int_t k_start, k_end;
1895 
1896  Double_t sum1 = 0.0, sumw1 = 0.0;
1897  Double_t sum2 = 0.0, sumw2 = 0.0;
1898 
1899  chi2 = 0.0;
1900  ndf = 0;
1901 
1902  TString opt = option;
1903  opt.ToUpper();
1904 
1905  if (fBuffer) const_cast<TH1*>(this)->BufferEmpty();
1906 
1907  const TAxis *xaxis1 = GetXaxis();
1908  const TAxis *xaxis2 = h2->GetXaxis();
1909  const TAxis *yaxis1 = GetYaxis();
1910  const TAxis *yaxis2 = h2->GetYaxis();
1911  const TAxis *zaxis1 = GetZaxis();
1912  const TAxis *zaxis2 = h2->GetZaxis();
1913 
1914  Int_t nbinx1 = xaxis1->GetNbins();
1915  Int_t nbinx2 = xaxis2->GetNbins();
1916  Int_t nbiny1 = yaxis1->GetNbins();
1917  Int_t nbiny2 = yaxis2->GetNbins();
1918  Int_t nbinz1 = zaxis1->GetNbins();
1919  Int_t nbinz2 = zaxis2->GetNbins();
1920 
1921  //check dimensions
1922  if (this->GetDimension() != h2->GetDimension() ){
1923  Error("Chi2TestX","Histograms have different dimensions.");
1924  return 0.0;
1925  }
1926 
1927  //check number of channels
1928  if (nbinx1 != nbinx2) {
1929  Error("Chi2TestX","different number of x channels");
1930  }
1931  if (nbiny1 != nbiny2) {
1932  Error("Chi2TestX","different number of y channels");
1933  }
1934  if (nbinz1 != nbinz2) {
1935  Error("Chi2TestX","different number of z channels");
1936  }
1937 
1938  //check for ranges
1939  i_start = j_start = k_start = 1;
1940  i_end = nbinx1;
1941  j_end = nbiny1;
1942  k_end = nbinz1;
1943 
1944  if (xaxis1->TestBit(TAxis::kAxisRange)) {
1945  i_start = xaxis1->GetFirst();
1946  i_end = xaxis1->GetLast();
1947  }
1948  if (yaxis1->TestBit(TAxis::kAxisRange)) {
1949  j_start = yaxis1->GetFirst();
1950  j_end = yaxis1->GetLast();
1951  }
1952  if (zaxis1->TestBit(TAxis::kAxisRange)) {
1953  k_start = zaxis1->GetFirst();
1954  k_end = zaxis1->GetLast();
1955  }
1956 
1957 
1958  if (opt.Contains("OF")) {
1959  if (GetDimension() == 3) k_end = ++nbinz1;
1960  if (GetDimension() >= 2) j_end = ++nbiny1;
1961  if (GetDimension() >= 1) i_end = ++nbinx1;
1962  }
1963 
1964  if (opt.Contains("UF")) {
1965  if (GetDimension() == 3) k_start = 0;
1966  if (GetDimension() >= 2) j_start = 0;
1967  if (GetDimension() >= 1) i_start = 0;
1968  }
1969 
1970  ndf = (i_end - i_start + 1) * (j_end - j_start + 1) * (k_end - k_start + 1) - 1;
1971 
1972  Bool_t comparisonUU = opt.Contains("UU");
1973  Bool_t comparisonUW = opt.Contains("UW");
1974  Bool_t comparisonWW = opt.Contains("WW");
1975  Bool_t scaledHistogram = opt.Contains("NORM");
1976 
1977  if (scaledHistogram && !comparisonUU) {
1978  Info("Chi2TestX", "NORM option should be used together with UU option. It is ignored");
1979  }
1980 
1981  // look at histo global bin content and effective entries
1982  Stat_t s[kNstat];
1983  GetStats(s);// s[1] sum of squares of weights, s[0] sum of weights
1984  Double_t sumBinContent1 = s[0];
1985  Double_t effEntries1 = (s[1] ? s[0] * s[0] / s[1] : 0.0);
1986 
1987  h2->GetStats(s);// s[1] sum of squares of weights, s[0] sum of weights
1988  Double_t sumBinContent2 = s[0];
1989  Double_t effEntries2 = (s[1] ? s[0] * s[0] / s[1] : 0.0);
1990 
1991  if (!comparisonUU && !comparisonUW && !comparisonWW ) {
1992  // deduce automatically from type of histogram
1993  if (TMath::Abs(sumBinContent1 - effEntries1) < 1) {
1994  if ( TMath::Abs(sumBinContent2 - effEntries2) < 1) comparisonUU = true;
1995  else comparisonUW = true;
1996  }
1997  else comparisonWW = true;
1998  }
1999  // check unweighted histogram
2000  if (comparisonUW) {
2001  if (TMath::Abs(sumBinContent1 - effEntries1) >= 1) {
2002  Warning("Chi2TestX","First histogram is not unweighted and option UW has been requested");
2003  }
2004  }
2005  if ( (!scaledHistogram && comparisonUU) ) {
2006  if ( ( TMath::Abs(sumBinContent1 - effEntries1) >= 1) || (TMath::Abs(sumBinContent2 - effEntries2) >= 1) ) {
2007  Warning("Chi2TestX","Both histograms are not unweighted and option UU has been requested");
2008  }
2009  }
2010 
2011 
2012  //get number of events in histogram
2013  if (comparisonUU && scaledHistogram) {
2014  for (Int_t i = i_start; i <= i_end; ++i) {
2015  for (Int_t j = j_start; j <= j_end; ++j) {
2016  for (Int_t k = k_start; k <= k_end; ++k) {
2017 
2018  Int_t bin = GetBin(i, j, k);
2019 
2020  Double_t cnt1 = RetrieveBinContent(bin);
2021  Double_t cnt2 = h2->RetrieveBinContent(bin);
2022  Double_t e1sq = GetBinErrorSqUnchecked(bin);
2023  Double_t e2sq = h2->GetBinErrorSqUnchecked(bin);
2024 
2025  if (e1sq > 0.0) cnt1 = TMath::Floor(cnt1 * cnt1 / e1sq + 0.5); // avoid rounding errors
2026  else cnt1 = 0.0;
2027 
2028  if (e2sq > 0.0) cnt2 = TMath::Floor(cnt2 * cnt2 / e2sq + 0.5); // avoid rounding errors
2029  else cnt2 = 0.0;
2030 
2031  // sum contents
2032  sum1 += cnt1;
2033  sum2 += cnt2;
2034  sumw1 += e1sq;
2035  sumw2 += e2sq;
2036  }
2037  }
2038  }
2039  if (sumw1 <= 0.0 || sumw2 <= 0.0) {
2040  Error("Chi2TestX", "Cannot use option NORM when one histogram has all zero errors");
2041  return 0.0;
2042  }
2043 
2044  } else {
2045  for (Int_t i = i_start; i <= i_end; ++i) {
2046  for (Int_t j = j_start; j <= j_end; ++j) {
2047  for (Int_t k = k_start; k <= k_end; ++k) {
2048 
2049  Int_t bin = GetBin(i, j, k);
2050 
2051  sum1 += RetrieveBinContent(bin);
2052  sum2 += h2->RetrieveBinContent(bin);
2053 
2054  if ( comparisonWW ) sumw1 += GetBinErrorSqUnchecked(bin);
2055  if ( comparisonUW || comparisonWW ) sumw2 += h2->GetBinErrorSqUnchecked(bin);
2056  }
2057  }
2058  }
2059  }
2060  //checks that the histograms are not empty
2061  if (sum1 == 0.0 || sum2 == 0.0) {
2062  Error("Chi2TestX","one histogram is empty");
2063  return 0.0;
2064  }
2065 
2066  if ( comparisonWW && ( sumw1 <= 0.0 && sumw2 <= 0.0 ) ){
2067  Error("Chi2TestX","Hist1 and Hist2 have both all zero errors\n");
2068  return 0.0;
2069  }
2070 
2071  //THE TEST
2072  Int_t m = 0, n = 0;
2073 
2074  //Experiment - experiment comparison
2075  if (comparisonUU) {
2076  Double_t sum = sum1 + sum2;
2077  for (Int_t i = i_start; i <= i_end; ++i) {
2078  for (Int_t j = j_start; j <= j_end; ++j) {
2079  for (Int_t k = k_start; k <= k_end; ++k) {
2080 
2081  Int_t bin = GetBin(i, j, k);
2082 
2083  Double_t cnt1 = RetrieveBinContent(bin);
2084  Double_t cnt2 = h2->RetrieveBinContent(bin);
2085 
2086  if (scaledHistogram) {
2087  // scale bin value to effective bin entries
2088  Double_t e1sq = GetBinErrorSqUnchecked(bin);
2089  Double_t e2sq = h2->GetBinErrorSqUnchecked(bin);
2090 
2091  if (e1sq > 0) cnt1 = TMath::Floor(cnt1 * cnt1 / e1sq + 0.5); // avoid rounding errors
2092  else cnt1 = 0;
2093 
2094  if (e2sq > 0) cnt2 = TMath::Floor(cnt2 * cnt2 / e2sq + 0.5); // avoid rounding errors
2095  else cnt2 = 0;
2096  }
2097 
2098  if (Int_t(cnt1) == 0 && Int_t(cnt2) == 0) --ndf; // no data means one degree of freedom less
2099  else {
2100 
2101  Double_t cntsum = cnt1 + cnt2;
2102  Double_t nexp1 = cntsum * sum1 / sum;
2103  //Double_t nexp2 = binsum*sum2/sum;
2104 
2105  if (res) res[i - i_start] = (cnt1 - nexp1) / TMath::Sqrt(nexp1);
2106 
2107  if (cnt1 < 1) ++m;
2108  if (cnt2 < 1) ++n;
2109 
2110  //Habermann correction for residuals
2111  Double_t correc = (1. - sum1 / sum) * (1. - cntsum / sum);
2112  if (res) res[i - i_start] /= TMath::Sqrt(correc);
2113 
2114  Double_t delta = sum2 * cnt1 - sum1 * cnt2;
2115  chi2 += delta * delta / cntsum;
2116  }
2117  }
2118  }
2119  }
2120  chi2 /= sum1 * sum2;
2121 
2122  // flag error only when of the two histogram is zero
2123  if (m) {
2124  igood += 1;
2125  Info("Chi2TestX","There is a bin in h1 with less than 1 event.\n");
2126  }
2127  if (n) {
2128  igood += 2;
2129  Info("Chi2TestX","There is a bin in h2 with less than 1 event.\n");
2130  }
2131 
2132  Double_t prob = TMath::Prob(chi2,ndf);
2133  return prob;
2134 
2135  }
2136 
2137  // unweighted - weighted comparison
2138  // case of error = 0 and content not zero is treated without problems by excluding second chi2 sum
2139  // and can be considered as a data-theory comparison
2140  if ( comparisonUW ) {
2141  for (Int_t i = i_start; i <= i_end; ++i) {
2142  for (Int_t j = j_start; j <= j_end; ++j) {
2143  for (Int_t k = k_start; k <= k_end; ++k) {
2144 
2145  Int_t bin = GetBin(i, j, k);
2146 
2147  Double_t cnt1 = RetrieveBinContent(bin);
2148  Double_t cnt2 = h2->RetrieveBinContent(bin);
2149  Double_t e2sq = h2->GetBinErrorSqUnchecked(bin);
2150 
2151  // case both histogram have zero bin contents
2152  if (cnt1 * cnt1 == 0 && cnt2 * cnt2 == 0) {
2153  --ndf; //no data means one degree of freedom less
2154  continue;
2155  }
2156 
2157  // case weighted histogram has zero bin content and error
2158  if (cnt2 * cnt2 == 0 && e2sq == 0) {
2159  if (sumw2 > 0) {
2160  // use as approximated error as 1 scaled by a scaling ratio
2161  // estimated from the total sum weight and sum weight squared
2162  e2sq = sumw2 / sum2;
2163  }
2164  else {
2165  // return error because infinite discrepancy here:
2166  // bin1 != 0 and bin2 =0 in a histogram with all errors zero
2167  Error("Chi2TestX","Hist2 has in bin (%d,%d,%d) zero content and zero errors\n", i, j, k);
2168  chi2 = 0; return 0;
2169  }
2170  }
2171 
2172  if (cnt1 < 1) m++;
2173  if (e2sq > 0 && cnt2 * cnt2 / e2sq < 10) n++;
2174 
2175  Double_t var1 = sum2 * cnt2 - sum1 * e2sq;
2176  Double_t var2 = var1 * var1 + 4. * sum2 * sum2 * cnt1 * e2sq;
2177 
2178  // if cnt1 is zero and cnt2 = 1 and sum1 = sum2 var1 = 0 && var2 == 0
2179  // approximate by incrementing cnt1
2180  // LM (this need to be fixed for numerical errors)
2181  while (var1 * var1 + cnt1 == 0 || var1 + var2 == 0) {
2182  sum1++;
2183  cnt1++;
2184  var1 = sum2 * cnt2 - sum1 * e2sq;
2185  var2 = var1 * var1 + 4. * sum2 * sum2 * cnt1 * e2sq;
2186  }
2187  var2 = TMath::Sqrt(var2);
2188 
2189  while (var1 + var2 == 0) {
2190  sum1++;
2191  cnt1++;
2192  var1 = sum2 * cnt2 - sum1 * e2sq;
2193  var2 = var1 * var1 + 4. * sum2 * sum2 * cnt1 * e2sq;
2194  while (var1 * var1 + cnt1 == 0 || var1 + var2 == 0) {
2195  sum1++;
2196  cnt1++;
2197  var1 = sum2 * cnt2 - sum1 * e2sq;
2198  var2 = var1 * var1 + 4. * sum2 * sum2 * cnt1 * e2sq;
2199  }
2200  var2 = TMath::Sqrt(var2);
2201  }
2202 
2203  Double_t probb = (var1 + var2) / (2. * sum2 * sum2);
2204 
2205  Double_t nexp1 = probb * sum1;
2206  Double_t nexp2 = probb * sum2;
2207 
2208  Double_t delta1 = cnt1 - nexp1;
2209  Double_t delta2 = cnt2 - nexp2;
2210 
2211  chi2 += delta1 * delta1 / nexp1;
2212 
2213  if (e2sq > 0) {
2214  chi2 += delta2 * delta2 / e2sq;
2215  }
2216 
2217  if (res) {
2218  if (e2sq > 0) {
2219  Double_t temp1 = sum2 * e2sq / var2;
2220  Double_t temp2 = 1.0 + (sum1 * e2sq - sum2 * cnt2) / var2;
2221  temp2 = temp1 * temp1 * sum1 * probb * (1.0 - probb) + temp2 * temp2 * e2sq / 4.0;
2222  // invert sign here
2223  res[i - i_start] = - delta2 / TMath::Sqrt(temp2);
2224  }
2225  else
2226  res[i - i_start] = delta1 / TMath::Sqrt(nexp1);
2227  }
2228  }
2229  }
2230  }
2231 
2232  if (m) {
2233  igood += 1;
2234  Info("Chi2TestX","There is a bin in h1 with less than 1 event.\n");
2235  }
2236  if (n) {
2237  igood += 2;
2238  Info("Chi2TestX","There is a bin in h2 with less than 10 effective events.\n");
2239  }
2240 
2241  Double_t prob = TMath::Prob(chi2, ndf);
2242 
2243  return prob;
2244  }
2245 
2246  // weighted - weighted comparison
2247  if (comparisonWW) {
2248  for (Int_t i = i_start; i <= i_end; ++i) {
2249  for (Int_t j = j_start; j <= j_end; ++j) {
2250  for (Int_t k = k_start; k <= k_end; ++k) {
2251 
2252  Int_t bin = GetBin(i, j, k);
2253  Double_t cnt1 = RetrieveBinContent(bin);
2254  Double_t cnt2 = h2->RetrieveBinContent(bin);
2255  Double_t e1sq = GetBinErrorSqUnchecked(bin);
2256  Double_t e2sq = h2->GetBinErrorSqUnchecked(bin);
2257 
2258  // case both histogram have zero bin contents
2259  // (use square of content to avoid numerical errors)
2260  if (cnt1 * cnt1 == 0 && cnt2 * cnt2 == 0) {
2261  --ndf; //no data means one degree of freedom less
2262  continue;
2263  }
2264 
2265  if (e1sq == 0 && e2sq == 0) {
2266  // cannot treat case of booth histogram have zero zero errors
2267  Error("Chi2TestX","h1 and h2 both have bin %d,%d,%d with all zero errors\n", i,j,k);
2268  chi2 = 0; return 0;
2269  }
2270 
2271  Double_t sigma = sum1 * sum1 * e2sq + sum2 * sum2 * e1sq;
2272  Double_t delta = sum2 * cnt1 - sum1 * cnt2;
2273  chi2 += delta * delta / sigma;
2274 
2275  if (res) {
2276  Double_t temp = cnt1 * sum1 * e2sq + cnt2 * sum2 * e1sq;
2277  Double_t probb = temp / sigma;
2278  Double_t z = 0;
2279  if (e1sq > e2sq) {
2280  Double_t d1 = cnt1 - sum1 * probb;
2281  Double_t s1 = e1sq * ( 1. - e2sq * sum1 * sum1 / sigma );
2282  z = d1 / TMath::Sqrt(s1);
2283  }
2284  else {
2285  Double_t d2 = cnt2 - sum2 * probb;
2286  Double_t s2 = e2sq * ( 1. - e1sq * sum2 * sum2 / sigma );
2287  z = -d2 / TMath::Sqrt(s2);
2288  }
2289  res[i - i_start] = z;
2290  }
2291 
2292  if (e1sq > 0 && cnt1 * cnt1 / e1sq < 10) m++;
2293  if (e2sq > 0 && cnt2 * cnt2 / e2sq < 10) n++;
2294  }
2295  }
2296  }
2297  if (m) {
2298  igood += 1;
2299  Info("Chi2TestX","There is a bin in h1 with less than 10 effective events.\n");
2300  }
2301  if (n) {
2302  igood += 2;
2303  Info("Chi2TestX","There is a bin in h2 with less than 10 effective events.\n");
2304  }
2305  Double_t prob = TMath::Prob(chi2, ndf);
2306  return prob;
2307  }
2308  return 0;
2309 }
2310 ////////////////////////////////////////////////////////////////////////////////
2311 /// Compute and return the chisquare of this histogram with respect to a function
2312 /// The chisquare is computed by weighting each histogram point by the bin error
2313 /// By default the full range of the histogram is used.
2314 /// Use option "R" for restricting the chisquare calculation to the given range of the function
2315 /// Use option "L" for using the chisquare based on the poisson likelihood (Baker-Cousins Chisquare)
2316 
2317 Double_t TH1::Chisquare(TF1 * func, Option_t *option) const
2318 {
2319  if (!func) {
2320  Error("Chisquare","Function pointer is Null - return -1");
2321  return -1;
2322  }
2323 
2324  TString opt(option); opt.ToUpper();
2325  bool useRange = opt.Contains("R");
2326  bool usePL = opt.Contains("L");
2327 
2328  return ROOT::Fit::Chisquare(*this, *func, useRange, usePL);
2329 }
2330 
2331 ////////////////////////////////////////////////////////////////////////////////
2332 /// Remove all the content from the underflow and overflow bins, without changing the number of entries
2333 /// After calling this method, every undeflow and overflow bins will have content 0.0
2334 /// The Sumw2 is also cleared, since there is no more content in the bins
2335 
2337 {
2338  for (Int_t bin = 0; bin < fNcells; ++bin)
2339  if (IsBinUnderflow(bin) || IsBinOverflow(bin)) {
2340  UpdateBinContent(bin, 0.0);
2341  if (fSumw2.fN) fSumw2.fArray[bin] = 0.0;
2342  }
2343 }
2344 
2345 ////////////////////////////////////////////////////////////////////////////////
2346 /// Compute integral (cumulative sum of bins)
2347 /// The result stored in fIntegral is used by the GetRandom functions.
2348 /// This function is automatically called by GetRandom when the fIntegral
2349 /// array does not exist or when the number of entries in the histogram
2350 /// has changed since the previous call to GetRandom.
2351 /// The resulting integral is normalized to 1
2352 /// If the routine is called with the onlyPositive flag set an error will
2353 /// be produced in case of negative bin content and a NaN value returned
2354 
2355 Double_t TH1::ComputeIntegral(Bool_t onlyPositive)
2356 {
2358 
2359  // delete previously computed integral (if any)
2360  if (fIntegral) delete [] fIntegral;
2361 
2362  // - Allocate space to store the integral and compute integral
2363  Int_t nbinsx = GetNbinsX();
2364  Int_t nbinsy = GetNbinsY();
2365  Int_t nbinsz = GetNbinsZ();
2366  Int_t nbins = nbinsx * nbinsy * nbinsz;
2367 
2368  fIntegral = new Double_t[nbins + 2];
2369  Int_t ibin = 0; fIntegral[ibin] = 0;
2370 
2371  for (Int_t binz=1; binz <= nbinsz; ++binz) {
2372  for (Int_t biny=1; biny <= nbinsy; ++biny) {
2373  for (Int_t binx=1; binx <= nbinsx; ++binx) {
2374  ++ibin;
2375  Double_t y = RetrieveBinContent(GetBin(binx, biny, binz));
2376  if (onlyPositive && y < 0) {
2377  Error("ComputeIntegral","Bin content is negative - return a NaN value");
2379  break;
2380  }
2381  fIntegral[ibin] = fIntegral[ibin - 1] + y;
2382  }
2383  }
2384  }
2385 
2386  // - Normalize integral to 1
2387  if (fIntegral[nbins] == 0 ) {
2388  Error("ComputeIntegral", "Integral = zero"); return 0;
2389  }
2390  for (Int_t bin=1; bin <= nbins; ++bin) fIntegral[bin] /= fIntegral[nbins];
2391  fIntegral[nbins+1] = fEntries;
2392  return fIntegral[nbins];
2393 }
2394 
2395 ////////////////////////////////////////////////////////////////////////////////
2396 /// Return a pointer to the array of bins integral.
2397 /// if the pointer fIntegral is null, TH1::ComputeIntegral is called
2398 /// The array dimension is the number of bins in the histograms
2399 /// including underflow and overflow (fNCells)
2400 /// the last value integral[fNCells] is set to the number of entries of
2401 /// the histogram
2402 
2404 {
2406  return fIntegral;
2407 }
2408 
2409 ////////////////////////////////////////////////////////////////////////////////
2410 /// Return a pointer to an histogram containing the cumulative The
2411 /// cumulative can be computed both in the forward (default) or backward
2412 /// direction; the name of the new histogram is constructed from
2413 /// the name of this histogram with the suffix suffix appended.
2414 ///
2415 /// The cumulative distribution is formed by filling each bin of the
2416 /// resulting histogram with the sum of that bin and all previous
2417 /// (forward == kTRUE) or following (forward = kFALSE) bins.
2418 ///
2419 /// note: while cumulative distributions make sense in one dimension, you
2420 /// may not be getting what you expect in more than 1D because the concept
2421 /// of a cumulative distribution is much trickier to define; make sure you
2422 /// understand the order of summation before you use this method with
2423 /// histograms of dimension >= 2.
2424 
2425 TH1 *TH1::GetCumulative(Bool_t forward, const char* suffix) const
2426 {
2427  const Int_t nbinsx = GetNbinsX();
2428  const Int_t nbinsy = GetNbinsY();
2429  const Int_t nbinsz = GetNbinsZ();
2430  TH1* hintegrated = (TH1*) Clone(fName + suffix);
2431  hintegrated->Reset();
2432  if (forward) { // Forward computation
2433  Double_t sum = 0.;
2434  for (Int_t binz = 1; binz <= nbinsz; ++binz) {
2435  for (Int_t biny = 1; biny <= nbinsy; ++biny) {
2436  for (Int_t binx = 1; binx <= nbinsx; ++binx) {
2437  const Int_t bin = hintegrated->GetBin(binx, biny, binz);
2438  sum += GetBinContent(bin);
2439  hintegrated->SetBinContent(bin, sum);
2440  }
2441  }
2442  }
2443  } else { // Backward computation
2444  Double_t sum = 0.;
2445  for (Int_t binz = nbinsz; binz >= 1; --binz) {
2446  for (Int_t biny = nbinsy; biny >= 1; --biny) {
2447  for (Int_t binx = nbinsx; binx >= 1; --binx) {
2448  const Int_t bin = hintegrated->GetBin(binx, biny, binz);
2449  sum += GetBinContent(bin);
2450  hintegrated->SetBinContent(bin, sum);
2451  }
2452  }
2453  }
2454  }
2455  return hintegrated;
2456 }
2457 
2458 ////////////////////////////////////////////////////////////////////////////////
2459 /// Copy this histogram structure to newth1.
2460 ///
2461 /// Note that this function does not copy the list of associated functions.
2462 /// Use TObject::Clone to make a full copy of an histogram.
2463 ///
2464 /// Note also that the histogram it will be created in gDirectory (if AddDirectoryStatus()=true)
2465 /// or will not be added to any directory if AddDirectoryStatus()=false
2466 /// independently of the current directory stored in the original histogram
2467 
2468 void TH1::Copy(TObject &obj) const
2469 {
2470  if (((TH1&)obj).fDirectory) {
2471  // We are likely to change the hash value of this object
2472  // with TNamed::Copy, to keep things correct, we need to
2473  // clean up its existing entries.
2474  ((TH1&)obj).fDirectory->Remove(&obj);
2475  ((TH1&)obj).fDirectory = 0;
2476  }
2477  TNamed::Copy(obj);
2478  ((TH1&)obj).fDimension = fDimension;
2479  ((TH1&)obj).fNormFactor= fNormFactor;
2480  ((TH1&)obj).fNcells = fNcells;
2481  ((TH1&)obj).fBarOffset = fBarOffset;
2482  ((TH1&)obj).fBarWidth = fBarWidth;
2483  ((TH1&)obj).fOption = fOption;
2484  ((TH1&)obj).fBinStatErrOpt = fBinStatErrOpt;
2485  ((TH1&)obj).fBufferSize= fBufferSize;
2486  // copy the Buffer
2487  // delete first a previously existing buffer
2488  if (((TH1&)obj).fBuffer != 0) {
2489  delete [] ((TH1&)obj).fBuffer;
2490  ((TH1&)obj).fBuffer = 0;
2491  }
2492  if (fBuffer) {
2493  Double_t *buf = new Double_t[fBufferSize];
2494  for (Int_t i=0;i<fBufferSize;i++) buf[i] = fBuffer[i];
2495  // obj.fBuffer has been deleted before
2496  ((TH1&)obj).fBuffer = buf;
2497  }
2498 
2499 
2500  TArray* a = dynamic_cast<TArray*>(&obj);
2501  if (a) a->Set(fNcells);
2502  for (Int_t i = 0; i < fNcells; i++) ((TH1&)obj).UpdateBinContent(i, RetrieveBinContent(i));
2503 
2504  ((TH1&)obj).fEntries = fEntries;
2505 
2506  // which will call BufferEmpty(0) and set fBuffer[0] to a Maybe one should call
2507  // assignment operator on the TArrayD
2508 
2509  ((TH1&)obj).fTsumw = fTsumw;
2510  ((TH1&)obj).fTsumw2 = fTsumw2;
2511  ((TH1&)obj).fTsumwx = fTsumwx;
2512  ((TH1&)obj).fTsumwx2 = fTsumwx2;
2513  ((TH1&)obj).fMaximum = fMaximum;
2514  ((TH1&)obj).fMinimum = fMinimum;
2515 
2516  TAttLine::Copy(((TH1&)obj));
2517  TAttFill::Copy(((TH1&)obj));
2518  TAttMarker::Copy(((TH1&)obj));
2519  fXaxis.Copy(((TH1&)obj).fXaxis);
2520  fYaxis.Copy(((TH1&)obj).fYaxis);
2521  fZaxis.Copy(((TH1&)obj).fZaxis);
2522  ((TH1&)obj).fXaxis.SetParent(&obj);
2523  ((TH1&)obj).fYaxis.SetParent(&obj);
2524  ((TH1&)obj).fZaxis.SetParent(&obj);
2525  fContour.Copy(((TH1&)obj).fContour);
2526  fSumw2.Copy(((TH1&)obj).fSumw2);
2527  // fFunctions->Copy(((TH1&)obj).fFunctions);
2528  // when copying an histogram if the AddDirectoryStatus() is true it
2529  // will be added to gDirectory independently of the fDirectory stored.
2530  // and if the AddDirectoryStatus() is false it will not be added to
2531  // any directory (fDirectory = 0)
2532  if (fgAddDirectory && gDirectory) {
2533  gDirectory->Append(&obj);
2534  ((TH1&)obj).fDirectory = gDirectory;
2535  } else
2536  ((TH1&)obj).fDirectory = 0;
2537 
2538 }
2539 
2540 ////////////////////////////////////////////////////////////////////////////////
2541 /// Make a complete copy of the underlying object. If 'newname' is set,
2542 /// the copy's name will be set to that name.
2543 
2544 TObject* TH1::Clone(const char* newname) const
2545 {
2546  TH1* obj = (TH1*)IsA()->GetNew()(0);
2547  Copy(*obj);
2548 
2549  //Now handle the parts that Copy doesn't do
2550  if(fFunctions) {
2551  if (obj->fFunctions) delete obj->fFunctions;
2552  obj->fFunctions = (TList*)fFunctions->Clone();
2553  }
2554  if(newname && strlen(newname) ) {
2555  obj->SetName(newname);
2556  }
2557  return obj;
2558 }
2559 
2560 ////////////////////////////////////////////////////////////////////////////////
2561 /// Perform the automatic addition of the histogram to the given directory
2562 ///
2563 /// Note this function is called in place when the semantic requires
2564 /// this object to be added to a directory (I.e. when being read from
2565 /// a TKey or being Cloned)
2566 
2568 {
2570  if (addStatus) {
2571  SetDirectory(dir);
2572  if (dir) {
2574  }
2575  }
2576 }
2577 
2578 ////////////////////////////////////////////////////////////////////////////////
2579 /// Compute distance from point px,py to a line.
2580 ///
2581 /// Compute the closest distance of approach from point px,py to elements
2582 /// of an histogram.
2583 /// The distance is computed in pixels units.
2584 ///
2585 /// #### Algorithm:
2586 /// Currently, this simple model computes the distance from the mouse
2587 /// to the histogram contour only.
2588 
2590 {
2591  if (!fPainter) return 9999;
2592  return fPainter->DistancetoPrimitive(px,py);
2593 }
2594 
2595 ////////////////////////////////////////////////////////////////////////////////
2596 /// Performs the operation: `this = this/(c1*f1)`
2597 /// if errors are defined (see TH1::Sumw2), errors are also recalculated.
2598 ///
2599 /// Only bins inside the function range are recomputed.
2600 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
2601 /// you should call Sumw2 before making this operation.
2602 /// This is particularly important if you fit the histogram after TH1::Divide
2603 ///
2604 /// The function return kFALSE if the divide operation failed
2605 
2607 {
2608  if (!f1) {
2609  Error("Add","Attempt to divide by a non-existing function");
2610  return kFALSE;
2611  }
2612 
2613  // delete buffer if it is there since it will become invalid
2614  if (fBuffer) BufferEmpty(1);
2615 
2616  Int_t nx = GetNbinsX() + 2; // normal bins + uf / of
2617  Int_t ny = GetNbinsY() + 2;
2618  Int_t nz = GetNbinsZ() + 2;
2619  if (fDimension < 2) ny = 1;
2620  if (fDimension < 3) nz = 1;
2621 
2622 
2623  SetMinimum();
2624  SetMaximum();
2625 
2626  // - Loop on bins (including underflows/overflows)
2627  Int_t bin, binx, biny, binz;
2628  Double_t cu, w;
2629  Double_t xx[3];
2630  Double_t *params = 0;
2631  f1->InitArgs(xx,params);
2632  for (binz = 0; binz < nz; ++binz) {
2633  xx[2] = fZaxis.GetBinCenter(binz);
2634  for (biny = 0; biny < ny; ++biny) {
2635  xx[1] = fYaxis.GetBinCenter(biny);
2636  for (binx = 0; binx < nx; ++binx) {
2637  xx[0] = fXaxis.GetBinCenter(binx);
2638  if (!f1->IsInside(xx)) continue;
2640  bin = binx + nx * (biny + ny * binz);
2641  cu = c1 * f1->EvalPar(xx);
2642  if (TF1::RejectedPoint()) continue;
2643  if (cu) w = RetrieveBinContent(bin) / cu;
2644  else w = 0;
2645  UpdateBinContent(bin, w);
2646  if (fSumw2.fN) {
2647  if (cu != 0) fSumw2.fArray[bin] = GetBinErrorSqUnchecked(bin) / (cu * cu);
2648  else fSumw2.fArray[bin] = 0;
2649  }
2650  }
2651  }
2652  }
2653  ResetStats();
2654  return kTRUE;
2655 }
2656 
2657 ////////////////////////////////////////////////////////////////////////////////
2658 /// Divide this histogram by h1.
2659 ///
2660 /// `this = this/h1`
2661 /// if errors are defined (see TH1::Sumw2), errors are also recalculated.
2662 /// Note that if h1 has Sumw2 set, Sumw2 is automatically called for this
2663 /// if not already set.
2664 /// The resulting errors are calculated assuming uncorrelated histograms.
2665 /// See the other TH1::Divide that gives the possibility to optionally
2666 /// compute binomial errors.
2667 ///
2668 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
2669 /// you should call Sumw2 before making this operation.
2670 /// This is particularly important if you fit the histogram after TH1::Scale
2671 ///
2672 /// The function return kFALSE if the divide operation failed
2673 
2674 Bool_t TH1::Divide(const TH1 *h1)
2675 {
2676  if (!h1) {
2677  Error("Divide", "Input histogram passed does not exist (NULL).");
2678  return kFALSE;
2679  }
2680 
2681  // delete buffer if it is there since it will become invalid
2682  if (fBuffer) BufferEmpty(1);
2683 
2684  try {
2685  CheckConsistency(this,h1);
2686  } catch(DifferentNumberOfBins&) {
2687  Error("Divide","Cannot divide histograms with different number of bins");
2688  return kFALSE;
2689  } catch(DifferentAxisLimits&) {
2690  Warning("Divide","Dividing histograms with different axis limits");
2691  } catch(DifferentBinLimits&) {
2692  Warning("Divide","Dividing histograms with different bin limits");
2693  } catch(DifferentLabels&) {
2694  Warning("Divide","Dividing histograms with different labels");
2695  }
2696 
2697  // Create Sumw2 if h1 has Sumw2 set
2698  if (fSumw2.fN == 0 && h1->GetSumw2N() != 0) Sumw2();
2699 
2700  // - Loop on bins (including underflows/overflows)
2701  for (Int_t i = 0; i < fNcells; ++i) {
2702  Double_t c0 = RetrieveBinContent(i);
2703  Double_t c1 = h1->RetrieveBinContent(i);
2704  if (c1) UpdateBinContent(i, c0 / c1);
2705  else UpdateBinContent(i, 0);
2706 
2707  if(fSumw2.fN) {
2708  if (c1 == 0) { fSumw2.fArray[i] = 0; continue; }
2709  Double_t c1sq = c1 * c1;
2710  fSumw2.fArray[i] = (GetBinErrorSqUnchecked(i) * c1sq + h1->GetBinErrorSqUnchecked(i) * c0 * c0) / (c1sq * c1sq);
2711  }
2712  }
2713  ResetStats();
2714  return kTRUE;
2715 }
2716 
2717 ////////////////////////////////////////////////////////////////////////////////
2718 /// Replace contents of this histogram by the division of h1 by h2.
2719 ///
2720 /// `this = c1*h1/(c2*h2)`
2721 ///
2722 /// If errors are defined (see TH1::Sumw2), errors are also recalculated
2723 /// Note that if h1 or h2 have Sumw2 set, Sumw2 is automatically called for this
2724 /// if not already set.
2725 /// The resulting errors are calculated assuming uncorrelated histograms.
2726 /// However, if option ="B" is specified, Binomial errors are computed.
2727 /// In this case c1 and c2 do not make real sense and they are ignored.
2728 ///
2729 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
2730 /// you should call Sumw2 before making this operation.
2731 /// This is particularly important if you fit the histogram after TH1::Divide
2732 ///
2733 /// Please note also that in the binomial case errors are calculated using standard
2734 /// binomial statistics, which means when b1 = b2, the error is zero.
2735 /// If you prefer to have efficiency errors not going to zero when the efficiency is 1, you must
2736 /// use the function TGraphAsymmErrors::BayesDivide, which will return an asymmetric and non-zero lower
2737 /// error for the case b1=b2.
2738 ///
2739 /// The function return kFALSE if the divide operation failed
2740 
2741 Bool_t TH1::Divide(const TH1 *h1, const TH1 *h2, Double_t c1, Double_t c2, Option_t *option)
2742 {
2744  TString opt = option;
2745  opt.ToLower();
2746  Bool_t binomial = kFALSE;
2747  if (opt.Contains("b")) binomial = kTRUE;
2748  if (!h1 || !h2) {
2749  Error("Divide", "At least one of the input histograms passed does not exist (NULL).");
2750  return kFALSE;
2751  }
2752 
2753  // delete buffer if it is there since it will become invalid
2754  if (fBuffer) BufferEmpty(1);
2755 
2756  try {
2757  CheckConsistency(h1,h2);
2758  CheckConsistency(this,h1);
2759  } catch(DifferentNumberOfBins&) {
2760  Error("Divide","Cannot divide histograms with different number of bins");
2761  return kFALSE;
2762  } catch(DifferentAxisLimits&) {
2763  Warning("Divide","Dividing histograms with different axis limits");
2764  } catch(DifferentBinLimits&) {
2765  Warning("Divide","Dividing histograms with different bin limits");
2766  } catch(DifferentLabels&) {
2767  Warning("Divide","Dividing histograms with different labels");
2768  }
2769 
2770 
2771  if (!c2) {
2772  Error("Divide","Coefficient of dividing histogram cannot be zero");
2773  return kFALSE;
2774  }
2775 
2776  // Create Sumw2 if h1 or h2 have Sumw2 set
2777  if (fSumw2.fN == 0 && (h1->GetSumw2N() != 0 || h2->GetSumw2N() != 0)) Sumw2();
2778 
2779  SetMinimum();
2780  SetMaximum();
2781 
2782  // - Loop on bins (including underflows/overflows)
2783  for (Int_t i = 0; i < fNcells; ++i) {
2784  Double_t b1 = h1->RetrieveBinContent(i);
2785  Double_t b2 = h2->RetrieveBinContent(i);
2786  if (b2) UpdateBinContent(i, c1 * b1 / (c2 * b2));
2787  else UpdateBinContent(i, 0);
2788 
2789  if (fSumw2.fN) {
2790  if (b2 == 0) { fSumw2.fArray[i] = 0; continue; }
2791  Double_t b1sq = b1 * b1; Double_t b2sq = b2 * b2;
2792  Double_t c1sq = c1 * c1; Double_t c2sq = c2 * c2;
2793  Double_t e1sq = h1->GetBinErrorSqUnchecked(i);
2794  Double_t e2sq = h2->GetBinErrorSqUnchecked(i);
2795  if (binomial) {
2796  if (b1 != b2) {
2797  // in the case of binomial statistics c1 and c2 must be 1 otherwise it does not make sense
2798  // c1 and c2 are ignored
2799  //fSumw2.fArray[bin] = TMath::Abs(w*(1-w)/(c2*b2));//this is the formula in Hbook/Hoper1
2800  //fSumw2.fArray[bin] = TMath::Abs(w*(1-w)/b2); // old formula from G. Flucke
2801  // formula which works also for weighted histogram (see http://root.cern.ch/phpBB2/viewtopic.php?t=3753 )
2802  fSumw2.fArray[i] = TMath::Abs( ( (1. - 2.* b1 / b2) * e1sq + b1sq * e2sq / b2sq ) / b2sq );
2803  } else {
2804  //in case b1=b2 error is zero
2805  //use TGraphAsymmErrors::BayesDivide for getting the asymmetric error not equal to zero
2806  fSumw2.fArray[i] = 0;
2807  }
2808  } else {
2809  fSumw2.fArray[i] = c1sq * c2sq * (e1sq * b2sq + e2sq * b1sq) / (c2sq * c2sq * b2sq * b2sq);
2810  }
2811  }
2812  }
2813  ResetStats();
2814  if (binomial)
2815  // in case of binomial division use denominator for number of entries
2816  SetEntries ( h2->GetEntries() );
2817 
2818  return kTRUE;
2819 }
2820 
2821 ////////////////////////////////////////////////////////////////////////////////
2822 /// Draw this histogram with options.
2823 ///
2824 /// Histograms are drawn via the THistPainter class. Each histogram has
2825 /// a pointer to its own painter (to be usable in a multithreaded program).
2826 /// The same histogram can be drawn with different options in different pads.
2827 /// When an histogram drawn in a pad is deleted, the histogram is
2828 /// automatically removed from the pad or pads where it was drawn.
2829 /// If an histogram is drawn in a pad, then filled again, the new status
2830 /// of the histogram will be automatically shown in the pad next time
2831 /// the pad is updated. One does not need to redraw the histogram.
2832 /// To draw the current version of an histogram in a pad, one can use
2833 /// `h->DrawCopy();`
2834 /// This makes a clone of the histogram. Once the clone is drawn, the original
2835 /// histogram may be modified or deleted without affecting the aspect of the
2836 /// clone.
2837 /// By default, TH1::Draw clears the current pad.
2838 ///
2839 /// One can use TH1::SetMaximum and TH1::SetMinimum to force a particular
2840 /// value for the maximum or the minimum scale on the plot.
2841 ///
2842 /// TH1::UseCurrentStyle can be used to change all histogram graphics
2843 /// attributes to correspond to the current selected style.
2844 /// This function must be called for each histogram.
2845 /// In case one reads and draws many histograms from a file, one can force
2846 /// the histograms to inherit automatically the current graphics style
2847 /// by calling before gROOT->ForceStyle();
2848 ///
2849 /// See the THistPainter class for a description of all the drawing options.
2850 
2851 void TH1::Draw(Option_t *option)
2852 {
2853  TString opt1 = option; opt1.ToLower();
2854  TString opt2 = option;
2855  Int_t index = opt1.Index("same");
2856 
2857  // Check if the string "same" is part of a TCutg name.
2858  if (index>=0) {
2859  Int_t indb = opt1.Index("[");
2860  if (indb>=0) {
2861  Int_t indk = opt1.Index("]");
2862  if (index>indb && index<indk) index = -1;
2863  }
2864  }
2865 
2866  // If there is no pad or an empty pad the the "same" is ignored.
2867  if (gPad) {
2868  if (!gPad->IsEditable()) gROOT->MakeDefCanvas();
2869  if (index>=0) {
2870  if (gPad->GetX1() == 0 && gPad->GetX2() == 1 &&
2871  gPad->GetY1() == 0 && gPad->GetY2() == 1 &&
2872  gPad->GetListOfPrimitives()->GetSize()==0) opt2.Remove(index,4);
2873  } else {
2874  //the following statement is necessary in case one attempts to draw
2875  //a temporary histogram already in the current pad
2876  if (TestBit(kCanDelete)) gPad->GetListOfPrimitives()->Remove(this);
2877  gPad->Clear();
2878  }
2879  } else {
2880  if (index>=0) opt2.Remove(index,4);
2881  }
2882 
2883  AppendPad(opt2.Data());
2884 }
2885 
2886 ////////////////////////////////////////////////////////////////////////////////
2887 /// Copy this histogram and Draw in the current pad.
2888 ///
2889 /// Once the histogram is drawn into the pad, any further modification
2890 /// using graphics input will be made on the copy of the histogram,
2891 /// and not to the original object.
2892 /// By default a postfix "_copy" is added to the histogram name. Pass an empty postfix in case
2893 /// you want to draw an histogram with the same name
2894 ///
2895 /// See Draw for the list of options
2896 
2897 TH1 *TH1::DrawCopy(Option_t *option, const char * name_postfix) const
2898 {
2899  TString opt = option;
2900  opt.ToLower();
2901  if (gPad && !opt.Contains("same")) gPad->Clear();
2902  TString newName = (name_postfix) ? TString::Format("%s%s",GetName(),name_postfix) : "";
2903  TH1 *newth1 = (TH1 *)Clone(newName);
2904  newth1->SetDirectory(0);
2905  newth1->SetBit(kCanDelete);
2906  newth1->AppendPad(option);
2907  return newth1;
2908 }
2909 
2910 ////////////////////////////////////////////////////////////////////////////////
2911 /// Draw a normalized copy of this histogram.
2912 ///
2913 /// A clone of this histogram is normalized to norm and drawn with option.
2914 /// A pointer to the normalized histogram is returned.
2915 /// The contents of the histogram copy are scaled such that the new
2916 /// sum of weights (excluding under and overflow) is equal to norm.
2917 /// Note that the returned normalized histogram is not added to the list
2918 /// of histograms in the current directory in memory.
2919 /// It is the user's responsibility to delete this histogram.
2920 /// The kCanDelete bit is set for the returned object. If a pad containing
2921 /// this copy is cleared, the histogram will be automatically deleted.
2922 ///
2923 /// See Draw for the list of options
2924 
2925 TH1 *TH1::DrawNormalized(Option_t *option, Double_t norm) const
2926 {
2928  if (sum == 0) {
2929  Error("DrawNormalized","Sum of weights is null. Cannot normalize histogram: %s",GetName());
2930  return 0;
2931  }
2932  Bool_t addStatus = TH1::AddDirectoryStatus();
2934  TH1 *h = (TH1*)Clone();
2935  h->SetBit(kCanDelete);
2936  // in case of drawing with error options - scale correctly the error
2937  TString opt(option); opt.ToUpper();
2938  if (fSumw2.fN == 0) {
2939  h->Sumw2();
2940  // do not use in this case the "Error option " for drawing which is enabled by default since the normalized histogram has now errors
2941  if (opt.IsNull() || opt == "SAME") opt += "HIST";
2942  }
2943  h->Scale(norm/sum);
2944  if (TMath::Abs(fMaximum+1111) > 1e-3) h->SetMaximum(fMaximum*norm/sum);
2945  if (TMath::Abs(fMinimum+1111) > 1e-3) h->SetMinimum(fMinimum*norm/sum);
2946  h->Draw(opt);
2947  TH1::AddDirectory(addStatus);
2948  return h;
2949 }
2950 
2951 ////////////////////////////////////////////////////////////////////////////////
2952 /// Display a panel with all histogram drawing options.
2953 ///
2954 /// See class TDrawPanelHist for example
2955 
2956 void TH1::DrawPanel()
2957 {
2958  if (!fPainter) {Draw(); if (gPad) gPad->Update();}
2959  if (fPainter) fPainter->DrawPanel();
2960 }
2961 
2962 ////////////////////////////////////////////////////////////////////////////////
2963 /// Evaluate function f1 at the center of bins of this histogram.
2964 ///
2965 /// - If option "R" is specified, the function is evaluated only
2966 /// for the bins included in the function range.
2967 /// - If option "A" is specified, the value of the function is added to the
2968 /// existing bin contents
2969 /// - If option "S" is specified, the value of the function is used to
2970 /// generate a value, distributed according to the Poisson
2971 /// distribution, with f1 as the mean.
2972 
2973 void TH1::Eval(TF1 *f1, Option_t *option)
2974 {
2976  Int_t range, stat, add;
2977  if (!f1) return;
2978 
2979  TString opt = option;
2980  opt.ToLower();
2981  if (opt.Contains("a")) add = 1;
2982  else add = 0;
2983  if (opt.Contains("s")) stat = 1;
2984  else stat = 0;
2985  if (opt.Contains("r")) range = 1;
2986  else range = 0;
2987 
2988  // delete buffer if it is there since it will become invalid
2989  if (fBuffer) BufferEmpty(1);
2990 
2991  Int_t nbinsx = fXaxis.GetNbins();
2992  Int_t nbinsy = fYaxis.GetNbins();
2993  Int_t nbinsz = fZaxis.GetNbins();
2994  if (!add) Reset();
2995 
2996  for (Int_t binz = 1; binz <= nbinsz; ++binz) {
2997  x[2] = fZaxis.GetBinCenter(binz);
2998  for (Int_t biny = 1; biny <= nbinsy; ++biny) {
2999  x[1] = fYaxis.GetBinCenter(biny);
3000  for (Int_t binx = 1; binx <= nbinsx; ++binx) {
3001  Int_t bin = GetBin(binx,biny,binz);
3002  x[0] = fXaxis.GetBinCenter(binx);
3003  if (range && !f1->IsInside(x)) continue;
3004  Double_t fu = f1->Eval(x[0], x[1], x[2]);
3005  if (stat) fu = gRandom->PoissonD(fu);
3006  AddBinContent(bin, fu);
3007  if (fSumw2.fN) fSumw2.fArray[bin] += TMath::Abs(fu);
3008  }
3009  }
3010  }
3011 }
3012 
3013 ////////////////////////////////////////////////////////////////////////////////
3014 /// Execute action corresponding to one event.
3015 ///
3016 /// This member function is called when a histogram is clicked with the locator
3017 ///
3018 /// If Left button clicked on the bin top value, then the content of this bin
3019 /// is modified according to the new position of the mouse when it is released.
3020 
3021 void TH1::ExecuteEvent(Int_t event, Int_t px, Int_t py)
3022 {
3023  if (fPainter) fPainter->ExecuteEvent(event, px, py);
3024 }
3025 
3026 ////////////////////////////////////////////////////////////////////////////////
3027 /// This function allows to do discrete Fourier transforms of TH1 and TH2.
3028 /// Available transform types and flags are described below.
3029 ///
3030 /// To extract more information about the transform, use the function
3031 /// TVirtualFFT::GetCurrentTransform() to get a pointer to the current
3032 /// transform object.
3033 ///
3034 /// \param[out] h_output histogram for the output. If a null pointer is passed, a new histogram is created
3035 /// and returned, otherwise, the provided histogram is used and should be big enough
3036 /// \param[in] option option parameters consists of 3 parts:
3037 /// - option on what to return
3038 /// - "RE" - returns a histogram of the real part of the output
3039 /// - "IM" - returns a histogram of the imaginary part of the output
3040 /// - "MAG"- returns a histogram of the magnitude of the output
3041 /// - "PH" - returns a histogram of the phase of the output
3042 /// - option of transform type
3043 /// - "R2C" - real to complex transforms - default
3044 /// - "R2HC" - real to halfcomplex (special format of storing output data,
3045 /// results the same as for R2C)
3046 /// - "DHT" - discrete Hartley transform
3047 /// real to real transforms (sine and cosine):
3048 /// - "R2R_0", "R2R_1", "R2R_2", "R2R_3" - discrete cosine transforms of types I-IV
3049 /// - "R2R_4", "R2R_5", "R2R_6", "R2R_7" - discrete sine transforms of types I-IV
3050 /// To specify the type of each dimension of a 2-dimensional real to real
3051 /// transform, use options of form "R2R_XX", for example, "R2R_02" for a transform,
3052 /// which is of type "R2R_0" in 1st dimension and "R2R_2" in the 2nd.
3053 /// - option of transform flag
3054 /// - "ES" (from "estimate") - no time in preparing the transform, but probably sub-optimal
3055 /// performance
3056 /// - "M" (from "measure") - some time spend in finding the optimal way to do the transform
3057 /// - "P" (from "patient") - more time spend in finding the optimal way to do the transform
3058 /// - "EX" (from "exhaustive") - the most optimal way is found
3059 /// This option should be chosen depending on how many transforms of the same size and
3060 /// type are going to be done. Planning is only done once, for the first transform of this
3061 /// size and type. Default is "ES".
3062 ///
3063 /// Examples of valid options: "Mag R2C M" "Re R2R_11" "Im R2C ES" "PH R2HC EX"
3064 
3065 TH1* TH1::FFT(TH1* h_output, Option_t *option)
3066 {
3068  Int_t ndim[3];
3069  ndim[0] = this->GetNbinsX();
3070  ndim[1] = this->GetNbinsY();
3071  ndim[2] = this->GetNbinsZ();
3072 
3073  TVirtualFFT *fft;
3074  TString opt = option;
3075  opt.ToUpper();
3076  if (!opt.Contains("2R")){
3077  if (!opt.Contains("2C") && !opt.Contains("2HC") && !opt.Contains("DHT")) {
3078  //no type specified, "R2C" by default
3079  opt.Append("R2C");
3080  }
3081  fft = TVirtualFFT::FFT(this->GetDimension(), ndim, opt.Data());
3082  }
3083  else {
3084  //find the kind of transform
3085  Int_t ind = opt.Index("R2R", 3);
3086  Int_t *kind = new Int_t[2];
3087  char t;
3088  t = opt[ind+4];
3089  kind[0] = atoi(&t);
3090  if (h_output->GetDimension()>1) {
3091  t = opt[ind+5];
3092  kind[1] = atoi(&t);
3093  }
3094  fft = TVirtualFFT::SineCosine(this->GetDimension(), ndim, kind, option);
3095  delete [] kind;
3096  }
3097 
3098  if (!fft) return 0;
3099  Int_t in=0;
3100  for (Int_t binx = 1; binx<=ndim[0]; binx++) {
3101  for (Int_t biny=1; biny<=ndim[1]; biny++) {
3102  for (Int_t binz=1; binz<=ndim[2]; binz++) {
3103  fft->SetPoint(in, this->GetBinContent(binx, biny, binz));
3104  in++;
3105  }
3106  }
3107  }
3108  fft->Transform();
3109  h_output = TransformHisto(fft, h_output, option);
3110  return h_output;
3111 }
3112 
3113 ////////////////////////////////////////////////////////////////////////////////
3114 /// Increment bin with abscissa X by 1.
3115 ///
3116 /// if x is less than the low-edge of the first bin, the Underflow bin is incremented
3117 /// if x is greater than the upper edge of last bin, the Overflow bin is incremented
3118 ///
3119 /// If the storage of the sum of squares of weights has been triggered,
3120 /// via the function Sumw2, then the sum of the squares of weights is incremented
3121 /// by 1 in the bin corresponding to x.
3122 ///
3123 /// The function returns the corresponding bin number which has its content incremented by 1
3124 
3126 {
3127  if (fBuffer) return BufferFill(x,1);
3128 
3129  Int_t bin;
3130  fEntries++;
3131  bin =fXaxis.FindBin(x);
3132  if (bin <0) return -1;
3133  AddBinContent(bin);
3134  if (fSumw2.fN) ++fSumw2.fArray[bin];
3135  if (bin == 0 || bin > fXaxis.GetNbins()) {
3136  if (!fgStatOverflows) return -1;
3137  }
3138  ++fTsumw;
3139  ++fTsumw2;
3140  fTsumwx += x;
3141  fTsumwx2 += x*x;
3142  return bin;
3143 }
3144 
3145 ////////////////////////////////////////////////////////////////////////////////
3146 /// Increment bin with abscissa X with a weight w.
3147 ///
3148 /// if x is less than the low-edge of the first bin, the Underflow bin is incremented
3149 /// if x is greater than the upper edge of last bin, the Overflow bin is incremented
3150 ///
3151 /// If the weight is not equal to 1, the storage of the sum of squares of
3152 /// weights is automatically triggered and the sum of the squares of weights is incremented
3153 /// by \f$ w^2 \f$ in the bin corresponding to x.
3154 ///
3155 /// The function returns the corresponding bin number which has its content incremented by w
3156 
3158 {
3160  if (fBuffer) return BufferFill(x,w);
3161 
3162  Int_t bin;
3163  fEntries++;
3164  bin =fXaxis.FindBin(x);
3165  if (bin <0) return -1;
3166  if (!fSumw2.fN && w != 1.0 && !TestBit(TH1::kIsNotW) ) Sumw2(); // must be called before AddBinContent
3167  if (fSumw2.fN) fSumw2.fArray[bin] += w*w;
3168  AddBinContent(bin, w);
3169  if (bin == 0 || bin > fXaxis.GetNbins()) {
3170  if (!fgStatOverflows) return -1;
3171  }
3172  Double_t z= w;
3173  fTsumw += z;
3174  fTsumw2 += z*z;
3175  fTsumwx += z*x;
3176  fTsumwx2 += z*x*x;
3177  return bin;
3178 }
3179 
3180 ////////////////////////////////////////////////////////////////////////////////
3181 /// Increment bin with namex with a weight w
3182 ///
3183 /// if x is less than the low-edge of the first bin, the Underflow bin is incremented
3184 /// if x is greater than the upper edge of last bin, the Overflow bin is incremented
3185 ///
3186 /// If the weight is not equal to 1, the storage of the sum of squares of
3187 /// weights is automatically triggered and the sum of the squares of weights is incremented
3188 /// by \f$ w^2 \f$ in the bin corresponding to x.
3189 ///
3190 /// The function returns the corresponding bin number which has its content
3191 /// incremented by w.
3192 
3193 Int_t TH1::Fill(const char *namex, Double_t w)
3194 {
3195  Int_t bin;
3196  fEntries++;
3197  bin =fXaxis.FindBin(namex);
3198  if (bin <0) return -1;
3199  if (!fSumw2.fN && w != 1.0 && !TestBit(TH1::kIsNotW)) Sumw2();
3200  if (fSumw2.fN) fSumw2.fArray[bin] += w*w;
3201  AddBinContent(bin, w);
3202  if (bin == 0 || bin > fXaxis.GetNbins()) return -1;
3203  Double_t z= w;
3204  fTsumw += z;
3205  fTsumw2 += z*z;
3206  // this make sense if the histogram is not expanding (no axis can be extended)
3207  if (!CanExtendAllAxes()) {
3208  Double_t x = fXaxis.GetBinCenter(bin);
3209  fTsumwx += z*x;
3210  fTsumwx2 += z*x*x;
3211  }
3212  return bin;
3213 }
3214 
3215 ////////////////////////////////////////////////////////////////////////////////
3216 /// Fill this histogram with an array x and weights w.
3217 ///
3218 /// \param[in] ntimes number of entries in arrays x and w (array size must be ntimes*stride)
3219 /// \param[in] x array of values to be histogrammed
3220 /// \param[in] w array of weighs
3221 /// \param[in] stride step size through arrays x and w
3222 ///
3223 /// If the weight is not equal to 1, the storage of the sum of squares of
3224 /// weights is automatically triggered and the sum of the squares of weights is incremented
3225 /// by \f$ w^2 \f$ in the bin corresponding to x.
3226 /// if w is NULL each entry is assumed a weight=1
3227 
3228 void TH1::FillN(Int_t ntimes, const Double_t *x, const Double_t *w, Int_t stride)
3229 {
3230  //If a buffer is activated, fill buffer
3231  if (fBuffer) {
3232  ntimes *= stride;
3233  Int_t i = 0;
3234  for (i=0;i<ntimes;i+=stride) {
3235  if (!fBuffer) break; // buffer can be deleted in BufferFill when is empty
3236  if (w) BufferFill(x[i],w[i]);
3237  else BufferFill(x[i], 1.);
3238  }
3239  // fill the remaining entries if the buffer has been deleted
3240  if (i < ntimes && fBuffer==0)
3241  DoFillN((ntimes-i)/stride,&x[i],&w[i],stride);
3242  return;
3243  }
3244  // call internal method
3245  DoFillN(ntimes, x, w, stride);
3246 }
3247 
3248 ////////////////////////////////////////////////////////////////////////////////
3249 /// Internal method to fill histogram content from a vector
3250 /// called directly by TH1::BufferEmpty
3251 
3252 void TH1::DoFillN(Int_t ntimes, const Double_t *x, const Double_t *w, Int_t stride)
3253 {
3254  Int_t bin,i;
3255 
3256  fEntries += ntimes;
3257  Double_t ww = 1;
3258  Int_t nbins = fXaxis.GetNbins();
3259  ntimes *= stride;
3260  for (i=0;i<ntimes;i+=stride) {
3261  bin =fXaxis.FindBin(x[i]);
3262  if (bin <0) continue;
3263  if (w) ww = w[i];
3264  if (!fSumw2.fN && ww != 1.0 && !TestBit(TH1::kIsNotW)) Sumw2();
3265  if (fSumw2.fN) fSumw2.fArray[bin] += ww*ww;
3266  AddBinContent(bin, ww);
3267  if (bin == 0 || bin > nbins) {
3268  if (!fgStatOverflows) continue;
3269  }
3270  Double_t z= ww;
3271  fTsumw += z;
3272  fTsumw2 += z*z;
3273  fTsumwx += z*x[i];
3274  fTsumwx2 += z*x[i]*x[i];
3275  }
3276 }
3277 
3278 ////////////////////////////////////////////////////////////////////////////////
3279 /// Fill histogram following distribution in function fname.
3280 ///
3281 /// The distribution contained in the function fname (TF1) is integrated
3282 /// over the channel contents for the bin range of this histogram.
3283 /// It is normalized to 1.
3284 ///
3285 /// Getting one random number implies:
3286 /// - Generating a random number between 0 and 1 (say r1)
3287 /// - Look in which bin in the normalized integral r1 corresponds to
3288 /// - Fill histogram channel
3289 /// ntimes random numbers are generated
3290 ///
3291 /// One can also call TF1::GetRandom to get a random variate from a function.
3292 
3293 void TH1::FillRandom(const char *fname, Int_t ntimes)
3294 {
3295  Int_t bin, binx, ibin, loop;
3296  Double_t r1, x;
3297  // - Search for fname in the list of ROOT defined functions
3298  TF1 *f1 = (TF1*)gROOT->GetFunction(fname);
3299  if (!f1) { Error("FillRandom", "Unknown function: %s",fname); return; }
3300 
3301  // - Allocate temporary space to store the integral and compute integral
3302 
3303  TAxis * xAxis = &fXaxis;
3304 
3305  // in case axis of histogram is not defined use the function axis
3306  if (fXaxis.GetXmax() <= fXaxis.GetXmin()) {
3307  Double_t xmin,xmax;
3308  f1->GetRange(xmin,xmax);
3309  Info("FillRandom","Using function axis and range [%g,%g]",xmin, xmax);
3310  xAxis = f1->GetHistogram()->GetXaxis();
3311  }
3312 
3313  Int_t first = xAxis->GetFirst();
3314  Int_t last = xAxis->GetLast();
3315  Int_t nbinsx = last-first+1;
3316 
3317  Double_t *integral = new Double_t[nbinsx+1];
3318  integral[0] = 0;
3319  for (binx=1;binx<=nbinsx;binx++) {
3320  Double_t fint = f1->Integral(xAxis->GetBinLowEdge(binx+first-1),xAxis->GetBinUpEdge(binx+first-1));
3321  integral[binx] = integral[binx-1] + fint;
3322  }
3323 
3324  // - Normalize integral to 1
3325  if (integral[nbinsx] == 0 ) {
3326  delete [] integral;
3327  Error("FillRandom", "Integral = zero"); return;
3328  }
3329  for (bin=1;bin<=nbinsx;bin++) integral[bin] /= integral[nbinsx];
3330 
3331  // --------------Start main loop ntimes
3332  for (loop=0;loop<ntimes;loop++) {
3333  r1 = gRandom->Rndm();
3334  ibin = TMath::BinarySearch(nbinsx,&integral[0],r1);
3335  //binx = 1 + ibin;
3336  //x = xAxis->GetBinCenter(binx); //this is not OK when SetBuffer is used
3337  x = xAxis->GetBinLowEdge(ibin+first)
3338  +xAxis->GetBinWidth(ibin+first)*(r1-integral[ibin])/(integral[ibin+1] - integral[ibin]);
3339  Fill(x);
3340  }
3341  delete [] integral;
3342 }
3343 
3344 ////////////////////////////////////////////////////////////////////////////////
3345 /// Fill histogram following distribution in histogram h.
3346 ///
3347 /// The distribution contained in the histogram h (TH1) is integrated
3348 /// over the channel contents for the bin range of this histogram.
3349 /// It is normalized to 1.
3350 ///
3351 /// Getting one random number implies:
3352 /// - Generating a random number between 0 and 1 (say r1)
3353 /// - Look in which bin in the normalized integral r1 corresponds to
3354 /// - Fill histogram channel ntimes random numbers are generated
3355 ///
3356 /// SPECIAL CASE when the target histogram has the same binning as the source.
3357 /// in this case we simply use a poisson distribution where
3358 /// the mean value per bin = bincontent/integral.
3359 
3360 void TH1::FillRandom(TH1 *h, Int_t ntimes)
3361 {
3362  if (!h) { Error("FillRandom", "Null histogram"); return; }
3363  if (fDimension != h->GetDimension()) {
3364  Error("FillRandom", "Histograms with different dimensions"); return;
3365  }
3366 
3367  //in case the target histogram has the same binning and ntimes much greater
3368  //than the number of bins we can use a fast method
3369  Int_t first = fXaxis.GetFirst();
3370  Int_t last = fXaxis.GetLast();
3371  Int_t nbins = last-first+1;
3372  if (ntimes > 10*nbins) {
3373  try {
3374  CheckConsistency(this,h);
3375  Double_t sumw = h->Integral(first,last);
3376  if (sumw == 0) return;
3377  Double_t sumgen = 0;
3378  for (Int_t bin=first;bin<=last;bin++) {
3379  Double_t mean = h->RetrieveBinContent(bin)*ntimes/sumw;
3380  Double_t cont = (Double_t)gRandom->Poisson(mean);
3381  sumgen += cont;
3382  AddBinContent(bin,cont);
3383  if (fSumw2.fN) fSumw2.fArray[bin] += cont;
3384  }
3385 
3386  // fix for the fluctuations in the total number n
3387  // since we use Poisson instead of multinomial
3388  // add a correction to have ntimes as generated entries
3389  Int_t i;
3390  if (sumgen < ntimes) {
3391  // add missing entries
3392  for (i = Int_t(sumgen+0.5); i < ntimes; ++i)
3393  {
3394  Double_t x = h->GetRandom();
3395  Fill(x);
3396  }
3397  }
3398  else if (sumgen > ntimes) {
3399  // remove extra entries
3400  i = Int_t(sumgen+0.5);
3401  while( i > ntimes) {
3402  Double_t x = h->GetRandom();
3403  Int_t ibin = fXaxis.FindBin(x);
3404  Double_t y = RetrieveBinContent(ibin);
3405  // skip in case bin is empty
3406  if (y > 0) {
3407  SetBinContent(ibin, y-1.);
3408  i--;
3409  }
3410  }
3411  }
3412 
3413  ResetStats();
3414  return;
3415  }
3416  catch(std::exception&) {} // do nothing
3417  }
3418  // case of different axis and not too large ntimes
3419 
3420  if (h->ComputeIntegral() ==0) return;
3421  Int_t loop;
3422  Double_t x;
3423  for (loop=0;loop<ntimes;loop++) {
3424  x = h->GetRandom();
3425  Fill(x);
3426  }
3427 }
3428 
3429 ////////////////////////////////////////////////////////////////////////////////
3430 /// Return Global bin number corresponding to x,y,z
3431 ///
3432 /// 2-D and 3-D histograms are represented with a one dimensional
3433 /// structure. This has the advantage that all existing functions, such as
3434 /// GetBinContent, GetBinError, GetBinFunction work for all dimensions.
3435 /// This function tries to extend the axis if the given point belongs to an
3436 /// under-/overflow bin AND if CanExtendAllAxes() is true.
3437 ///
3438 /// See also TH1::GetBin, TAxis::FindBin and TAxis::FindFixBin
3439 
3441 {
3442  if (GetDimension() < 2) {
3443  return fXaxis.FindBin(x);
3444  }
3445  if (GetDimension() < 3) {
3446  Int_t nx = fXaxis.GetNbins()+2;
3447  Int_t binx = fXaxis.FindBin(x);
3448  Int_t biny = fYaxis.FindBin(y);
3449  return binx + nx*biny;
3450  }
3451  if (GetDimension() < 4) {
3452  Int_t nx = fXaxis.GetNbins()+2;
3453  Int_t ny = fYaxis.GetNbins()+2;
3454  Int_t binx = fXaxis.FindBin(x);
3455  Int_t biny = fYaxis.FindBin(y);
3456  Int_t binz = fZaxis.FindBin(z);
3457  return binx + nx*(biny +ny*binz);
3458  }
3459  return -1;
3460 }
3461 
3462 ////////////////////////////////////////////////////////////////////////////////
3463 /// Return Global bin number corresponding to x,y,z.
3464 ///
3465 /// 2-D and 3-D histograms are represented with a one dimensional
3466 /// structure. This has the advantage that all existing functions, such as
3467 /// GetBinContent, GetBinError, GetBinFunction work for all dimensions.
3468 /// This function DOES NOT try to extend the axis if the given point belongs
3469 /// to an under-/overflow bin.
3470 ///
3471 /// See also TH1::GetBin, TAxis::FindBin and TAxis::FindFixBin
3472 
3474 {
3475  if (GetDimension() < 2) {
3476  return fXaxis.FindFixBin(x);
3477  }
3478  if (GetDimension() < 3) {
3479  Int_t nx = fXaxis.GetNbins()+2;
3480  Int_t binx = fXaxis.FindFixBin(x);
3481  Int_t biny = fYaxis.FindFixBin(y);
3482  return binx + nx*biny;
3483  }
3484  if (GetDimension() < 4) {
3485  Int_t nx = fXaxis.GetNbins()+2;
3486  Int_t ny = fYaxis.GetNbins()+2;
3487  Int_t binx = fXaxis.FindFixBin(x);
3488  Int_t biny = fYaxis.FindFixBin(y);
3489  Int_t binz = fZaxis.FindFixBin(z);
3490  return binx + nx*(biny +ny*binz);
3491  }
3492  return -1;
3493 }
3494 
3495 ////////////////////////////////////////////////////////////////////////////////
3496 /// Find first bin with content > threshold for axis (1=x, 2=y, 3=z)
3497 /// if no bins with content > threshold is found the function returns -1.
3498 
3499 Int_t TH1::FindFirstBinAbove(Double_t threshold, Int_t axis) const
3500 {
3501  if (fBuffer) ((TH1*)this)->BufferEmpty();
3502 
3503  if (axis != 1) {
3504  Warning("FindFirstBinAbove","Invalid axis number : %d, axis x assumed\n",axis);
3505  axis = 1;
3506  }
3507  Int_t nbins = fXaxis.GetNbins();
3508  for (Int_t bin=1;bin<=nbins;bin++) {
3509  if (RetrieveBinContent(bin) > threshold) return bin;
3510  }
3511  return -1;
3512 }
3513 
3514 ////////////////////////////////////////////////////////////////////////////////
3515 /// Find last bin with content > threshold for axis (1=x, 2=y, 3=z)
3516 /// if no bins with content > threshold is found the function returns -1.
3517 
3518 Int_t TH1::FindLastBinAbove(Double_t threshold, Int_t axis) const
3519 {
3520  if (fBuffer) ((TH1*)this)->BufferEmpty();
3521 
3522  if (axis != 1) {
3523  Warning("FindLastBinAbove","Invalid axis number : %d, axis x assumed\n",axis);
3524  axis = 1;
3525  }
3526  Int_t nbins = fXaxis.GetNbins();
3527  for (Int_t bin=nbins;bin>=1;bin--) {
3528  if (RetrieveBinContent(bin) > threshold) return bin;
3529  }
3530  return -1;
3531 }
3532 
3533 ////////////////////////////////////////////////////////////////////////////////
3534 /// Search object named name in the list of functions.
3535 
3536 TObject *TH1::FindObject(const char *name) const
3537 {
3538  if (fFunctions) return fFunctions->FindObject(name);
3539  return 0;
3540 }
3541 
3542 ////////////////////////////////////////////////////////////////////////////////
3543 /// Search object obj in the list of functions.
3544 
3545 TObject *TH1::FindObject(const TObject *obj) const
3546 {
3547  if (fFunctions) return fFunctions->FindObject(obj);
3548  return 0;
3549 }
3550 
3551 ////////////////////////////////////////////////////////////////////////////////
3552 /// Fit histogram with function fname.
3553 ///
3554 /// fname is the name of an already predefined function created by TF1 or TF2
3555 /// Predefined functions such as gaus, expo and poln are automatically
3556 /// created by ROOT.
3557 /// fname can also be a formula, accepted by the linear fitter (linear parts divided
3558 /// by "++" sign), for example "x++sin(x)" for fitting "[0]*x+[1]*sin(x)"
3559 ///
3560 /// This function finds a pointer to the TF1 object with name fname
3561 /// and calls TH1::Fit(TF1 *f1,...)
3562 
3563 TFitResultPtr TH1::Fit(const char *fname ,Option_t *option ,Option_t *goption, Double_t xxmin, Double_t xxmax)
3564 {
3565  char *linear;
3566  linear= (char*)strstr(fname, "++");
3567  TF1 *f1=0;
3568  TF2 *f2=0;
3569  TF3 *f3=0;
3570  Int_t ndim=GetDimension();
3571  if (linear){
3572  if (ndim<2){
3573  f1=new TF1(fname, fname, xxmin, xxmax);
3574  return Fit(f1,option,goption,xxmin,xxmax);
3575  }
3576  else if (ndim<3){
3577  f2=new TF2(fname, fname);
3578  return Fit(f2,option,goption,xxmin,xxmax);
3579  }
3580  else{
3581  f3=new TF3(fname, fname);
3582  return Fit(f3,option,goption,xxmin,xxmax);
3583  }
3584  }
3585 
3586  else{
3587  f1 = (TF1*)gROOT->GetFunction(fname);
3588  if (!f1) { Printf("Unknown function: %s",fname); return -1; }
3589  return Fit(f1,option,goption,xxmin,xxmax);
3590  }
3591 }
3592 
3593 ////////////////////////////////////////////////////////////////////////////////
3594 /// Fit histogram with function f1.
3595 ///
3596 /// \param[in] option fit options is given in parameter option.
3597 /// - "W" Set all weights to 1 for non empty bins; ignore error bars
3598 /// - "WW" Set all weights to 1 including empty bins; ignore error bars
3599 /// - "I" Use integral of function in bin, normalized by the bin volume,
3600 /// instead of value at bin center
3601 /// - "L" Use Loglikelihood method (default is chisquare method)
3602 /// - "WL" Use Loglikelihood method and bin contents are not integer,
3603 /// i.e. histogram is weighted (must have Sumw2() set)
3604 /// - "P" Use Pearson chi2 (using expected errors instead of observed errors)
3605 /// - "U" Use a User specified fitting algorithm (via SetFCN)
3606 /// - "Q" Quiet mode (minimum printing)
3607 /// - "V" Verbose mode (default is between Q and V)
3608 /// - "E" Perform better Errors estimation using Minos technique
3609 /// - "B" User defined parameter settings are used for predefined functions
3610 /// like "gaus", "expo", "poln", "landau".
3611 /// Use this option when you want to fix one or more parameters for these functions.
3612 /// - "M" More. Improve fit results.
3613 /// It uses the IMPROVE command of TMinuit (see TMinuit::mnimpr).
3614 /// This algorithm attempts to improve the found local minimum by searching for a
3615 /// better one.
3616 /// - "R" Use the Range specified in the function range
3617 /// - "N" Do not store the graphics function, do not draw
3618 /// - "0" Do not plot the result of the fit. By default the fitted function
3619 /// is drawn unless the option"N" above is specified.
3620 /// - "+" Add this new fitted function to the list of fitted functions
3621 /// (by default, any previous function is deleted)
3622 /// - "C" In case of linear fitting, don't calculate the chisquare
3623 /// (saves time)
3624 /// - "F" If fitting a polN, switch to minuit fitter
3625 /// - "S" The result of the fit is returned in the TFitResultPtr
3626 /// (see below Access to the Fit Result)
3627 /// \param[in] goption specify a list of graphics options. See TH1::Draw for a complete list of these options.
3628 /// \param[in] xxmin range
3629 /// \param[in] xxmax range
3630 ///
3631 /// In order to use the Range option, one must first create a function
3632 /// with the expression to be fitted. For example, if your histogram
3633 /// has a defined range between -4 and 4 and you want to fit a gaussian
3634 /// only in the interval 1 to 3, you can do:
3635 ///
3636 /// ~~~ {.cpp}
3637 /// TF1 *f1 = new TF1("f1", "gaus", 1, 3);
3638 /// histo->Fit("f1", "R");
3639 /// ~~~
3640 ///
3641 /// ## Setting initial conditions
3642 /// Parameters must be initialized before invoking the Fit function.
3643 /// The setting of the parameter initial values is automatic for the
3644 /// predefined functions : poln, expo, gaus, landau. One can however disable
3645 /// this automatic computation by specifying the option "B".
3646 /// Note that if a predefined function is defined with an argument,
3647 /// eg, gaus(0), expo(1), you must specify the initial values for
3648 /// the parameters.
3649 /// You can specify boundary limits for some or all parameters via
3650 ///
3651 /// ~~~ {.cpp}
3652 /// f1->SetParLimits(p_number, parmin, parmax);
3653 /// ~~~
3654 ///
3655 /// if parmin>=parmax, the parameter is fixed
3656 /// Note that you are not forced to fix the limits for all parameters.
3657 /// For example, if you fit a function with 6 parameters, you can do:
3658 ///
3659 /// ~~~ {.cpp}
3660 /// func->SetParameters(0, 3.1, 1.e-6, -8, 0, 100);
3661 /// func->SetParLimits(3, -10, -4);
3662 /// func->FixParameter(4, 0);
3663 /// func->SetParLimits(5, 1, 1);
3664 /// ~~~
3665 ///
3666 /// With this setup, parameters 0->2 can vary freely
3667 /// Parameter 3 has boundaries [-10,-4] with initial value -8
3668 /// Parameter 4 is fixed to 0
3669 /// Parameter 5 is fixed to 100.
3670 /// When the lower limit and upper limit are equal, the parameter is fixed.
3671 /// However to fix a parameter to 0, one must call the FixParameter function.
3672 ///
3673 /// Note that option "I" gives better results but is slower.
3674 ///
3675 /// #### Changing the fitting objective function
3676 ///
3677 /// By default a chi square function is used for fitting. When option "L" (or "LL") is used
3678 /// a Poisson likelihood function (see note below) is used.
3679 /// The functions are defined in the header Fit/Chi2Func.h or Fit/PoissonLikelihoodFCN and they
3680 /// are implemented using the routines FitUtil::EvaluateChi2 or FitUtil::EvaluatePoissonLogL in
3681 /// the file math/mathcore/src/FitUtil.cxx.
3682 /// To specify a User defined fitting function, specify option "U" and
3683 /// call the following functions:
3684 ///
3685 /// ~~~ {.cpp}
3686 /// TVirtualFitter::Fitter(myhist)->SetFCN(MyFittingFunction)
3687 /// ~~~
3688 ///
3689 /// where MyFittingFunction is of type:
3690 ///
3691 /// ~~~ {.cpp}
3692 /// extern void MyFittingFunction(Int_t &npar, Double_t *gin, Double_t &f, Double_t *u, Int_t flag);
3693 /// ~~~
3694 ///
3695 /// #### Chi2 Fits
3696 ///
3697 /// By default a chi2 (least-square) fit is performed on the histogram. The so-called modified least-square method
3698 /// is used where the residual for each bin is computed using as error the observed value (the bin error)
3699 ///
3700 /// \f[
3701 /// Chi2 = \sum{ \left(y(i) - \frac{f(x(i) | p )}{e(i)} \right)^2 }
3702 /// \f]
3703 ///
3704 /// 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
3705 /// an un-weighted histogram. Bins with zero errors are excluded from the fit. See also later the note on the treatment of empty bins.
3706 /// When using option "I" the residual is computed not using the function value at the bin center, f (x(i) | p), but the integral
3707 /// of the function in the bin, Integral{ f(x|p)dx } divided by the bin volume
3708 ///
3709 /// #### Likelihood Fits
3710 ///
3711 /// When using option "L" a likelihood fit is used instead of the default chi2 square fit.
3712 /// The likelihood is built assuming a Poisson probability density function for each bin.
3713 /// The negative log-likelihood to be minimized is
3714 ///
3715 /// \f[
3716 /// NLL = \sum{ log Poisson ( y(i) | f(x(i) | p ) ) }
3717 /// \f]
3718 ///
3719 /// The exact likelihood used is the Poisson likelihood described in this paper:
3720 /// S. Baker and R. D. Cousins, “Clarification of the use of chi-square and likelihood functions in fits to histograms,”
3721 /// Nucl. Instrum. Meth. 221 (1984) 437.
3722 ///
3723 /// This method can then be used only when the bin content represents counts (i.e. errors are sqrt(N) ).
3724 /// The likelihood method has the advantage of treating correctly bins with low statistics. In case of high
3725 /// statistics/bin the distribution of the bin content becomes a normal distribution and the likelihood and chi2 fit
3726 /// give the same result.
3727 ///
3728 /// The likelihood method, although a bit slower, it is therefore the recommended method in case of low
3729 /// bin statistics, where the chi2 method may give incorrect results, in particular when there are
3730 /// several empty bins (see also below).
3731 /// In case of a weighted histogram, it is possible to perform a likelihood fit by using the
3732 /// option "WL". Note a weighted histogram is an histogram which has been filled with weights and it
3733 /// contains the sum of the weight square ( TH1::Sumw2() has been called). The bin error for a weighted
3734 /// histogram is the square root of the sum of the weight square.
3735 ///
3736 /// #### Treatment of Empty Bins
3737 ///
3738 /// Empty bins, which have the content equal to zero AND error equal to zero,
3739 /// are excluded by default from the chisquare fit, but they are considered in the likelihood fit.
3740 /// since they affect the likelihood if the function value in these bins is not negligible.
3741 /// When using option "WW" these bins will be considered in the chi2 fit with an error of 1.
3742 /// Note that if the histogram is having bins with zero content and non zero-errors they are considered as
3743 /// any other bins in the fit. Instead bins with zero error and non-zero content are excluded in the chi2 fit.
3744 /// A likelihood fit should also not be performed on such an histogram, since we are assuming a wrong pdf for each bin.
3745 /// In general, one should not fit an histogram with non-empty bins and zero errors, apart if all the bins have zero errors.
3746 /// In this case one could use the option "w", which gives a weight=1 for each bin (unweighted least-square fit).
3747 ///
3748 /// #### Fitting a histogram of dimension N with a function of dimension N-1
3749 ///
3750 /// It is possible to fit a TH2 with a TF1 or a TH3 with a TF2.
3751 /// In this case the option "Integral" is not allowed and each cell has
3752 /// equal weight.
3753 ///
3754 /// #### Associated functions
3755 ///
3756 /// One or more object (typically a TF1*) can be added to the list
3757 /// of functions (fFunctions) associated to each histogram.
3758 /// When TH1::Fit is invoked, the fitted function is added to this list.
3759 /// Given an histogram h, one can retrieve an associated function
3760 /// with:
3761 ///
3762 /// ~~~ {.cpp}
3763 /// TF1 *myfunc = h->GetFunction("myfunc");
3764 /// ~~~
3765 ///
3766 /// #### Access to the fit result
3767 ///
3768 /// The function returns a TFitResultPtr which can hold a pointer to a TFitResult object.
3769 /// By default the TFitResultPtr contains only the status of the fit which is return by an
3770 /// automatic conversion of the TFitResultPtr to an integer. One can write in this case directly:
3771 ///
3772 /// ~~~ {.cpp}
3773 /// Int_t fitStatus = h->Fit(myFunc)
3774 /// ~~~
3775 ///
3776 /// If the option "S" is instead used, TFitResultPtr contains the TFitResult and behaves as a smart
3777 /// pointer to it. For example one can do:
3778 ///
3779 /// ~~~ {.cpp}
3780 /// TFitResultPtr r = h->Fit(myFunc,"S");
3781 /// TMatrixDSym cov = r->GetCovarianceMatrix(); // to access the covariance matrix
3782 /// Double_t chi2 = r->Chi2(); // to retrieve the fit chi2
3783 /// Double_t par0 = r->Parameter(0); // retrieve the value for the parameter 0
3784 /// Double_t err0 = r->ParError(0); // retrieve the error for the parameter 0
3785 /// r->Print("V"); // print full information of fit including covariance matrix
3786 /// r->Write(); // store the result in a file
3787 /// ~~~
3788 ///
3789 /// The fit parameters, error and chi2 (but not covariance matrix) can be retrieved also
3790 /// from the fitted function.
3791 /// If the histogram is made persistent, the list of
3792 /// associated functions is also persistent. Given a pointer (see above)
3793 /// to an associated function myfunc, one can retrieve the function/fit
3794 /// parameters with calls such as:
3795 ///
3796 /// ~~~ {.cpp}
3797 /// Double_t chi2 = myfunc->GetChisquare();
3798 /// Double_t par0 = myfunc->GetParameter(0); //value of 1st parameter
3799 /// Double_t err0 = myfunc->GetParError(0); //error on first parameter
3800 /// ~~~
3801 ///
3802 /// #### Access to the fit status
3803 ///
3804 /// The status of the fit can be obtained converting the TFitResultPtr to an integer
3805 /// independently if the fit option "S" is used or not:
3806 ///
3807 /// ~~~ {.cpp}
3808 /// TFitResultPtr r = h->Fit(myFunc,opt);
3809 /// Int_t fitStatus = r;
3810 /// ~~~
3811 ///
3812 /// The fitStatus is 0 if the fit is OK (i.e no error occurred).
3813 /// The value of the fit status code is negative in case of an error not connected with the
3814 /// minimization procedure, for example when a wrong function is used.
3815 /// Otherwise the return value is the one returned from the minimization procedure.
3816 /// When TMinuit (default case) or Minuit2 are used as minimizer the status returned is :
3817 /// `fitStatus = migradResult + 10*minosResult + 100*hesseResult + 1000*improveResult`.
3818 /// TMinuit will return 0 (for migrad, minos, hesse or improve) in case of success and 4 in
3819 /// case of error (see the documentation of TMinuit::mnexcm). So for example, for an error
3820 /// only in Minos but not in Migrad a fitStatus of 40 will be returned.
3821 /// Minuit2 will return also 0 in case of success and different values in migrad minos or
3822 /// hesse depending on the error. See in this case the documentation of
3823 /// Minuit2Minimizer::Minimize for the migradResult, Minuit2Minimizer::GetMinosError for the
3824 /// minosResult and Minuit2Minimizer::Hesse for the hesseResult.
3825 /// If other minimizers are used see their specific documentation for the status code returned.
3826 /// For example in the case of Fumili, for the status returned see TFumili::Minimize.
3827 ///
3828 /// #### Excluding points
3829 ///
3830 /// Use TF1::RejectPoint inside your fitting function to exclude points
3831 /// within a certain range from the fit. Example:
3832 ///
3833 /// ~~~ {.cpp}
3834 /// Double_t fline(Double_t *x, Double_t *par)
3835 /// {
3836 /// if (x[0] > 2.5 && x[0] < 3.5) {
3837 /// TF1::RejectPoint();
3838 /// return 0;
3839 /// }
3840 /// return par[0] + par[1]*x[0];
3841 /// }
3842 ///
3843 /// void exclude() {
3844 /// TF1 *f1 = new TF1("f1", "[0] +[1]*x +gaus(2)", 0, 5);
3845 /// f1->SetParameters(6, -1,5, 3, 0.2);
3846 /// TH1F *h = new TH1F("h", "background + signal", 100, 0, 5);
3847 /// h->FillRandom("f1", 2000);
3848 /// TF1 *fline = new TF1("fline", fline, 0, 5, 2);
3849 /// fline->SetParameters(2, -1);
3850 /// h->Fit("fline", "l");
3851 /// }
3852 /// ~~~
3853 ///
3854 /// #### Warning when using the option "0"
3855 ///
3856 /// When selecting the option "0", the fitted function is added to
3857 /// the list of functions of the histogram, but it is not drawn.
3858 /// You can undo what you disabled in the following way:
3859 ///
3860 /// ~~~ {.cpp}
3861 /// h.Fit("myFunction", "0"); // fit, store function but do not draw
3862 /// h.Draw(); function is not drawn
3863 /// const Int_t kNotDraw = 1<<9;
3864 /// h.GetFunction("myFunction")->ResetBit(kNotDraw);
3865 /// h.Draw(); // function is visible again
3866 /// ~~~
3867 ///
3868 /// #### Access to the Minimizer information during fitting
3869 ///
3870 /// This function calls, the ROOT::Fit::FitObject function implemented in HFitImpl.cxx
3871 /// which uses the ROOT::Fit::Fitter class. The Fitter class creates the objective function
3872 /// (e.g. chi2 or likelihood) and uses an implementation of the Minimizer interface for minimizing
3873 /// the function.
3874 /// The default minimizer is Minuit (class TMinuitMinimizer which calls TMinuit).
3875 /// The default can be set in the resource file in etc/system.rootrc. For example
3876 ///
3877 /// ~~~ {.cpp}
3878 /// Root.Fitter: Minuit2
3879 /// ~~~
3880 ///
3881 /// A different fitter can also be set via ROOT::Math::MinimizerOptions::SetDefaultMinimizer
3882 /// (or TVirtualFitter::SetDefaultFitter).
3883 /// For example ROOT::Math::MinimizerOptions::SetDefaultMinimizer("GSLMultiMin","BFGS");
3884 /// will set the usage of the BFGS algorithm of the GSL multi-dimensional minimization
3885 /// (implemented in libMathMore). ROOT::Math::MinimizerOptions can be used also to set other
3886 /// default options, like maximum number of function calls, minimization tolerance or print
3887 /// level. See the documentation of this class.
3888 ///
3889 /// For fitting linear functions (containing the "++" sign" and polN functions,
3890 /// the linear fitter is automatically initialized.
3891 
3892 TFitResultPtr TH1::Fit(TF1 *f1 ,Option_t *option ,Option_t *goption, Double_t xxmin, Double_t xxmax)
3893 {
3894  // implementation of Fit method is in file hist/src/HFitImpl.cxx
3895  Foption_t fitOption;
3897 
3898  // create range and minimizer options with default values
3899  ROOT::Fit::DataRange range(xxmin,xxmax);
3900  ROOT::Math::MinimizerOptions minOption;
3901 
3902  // need to empty the buffer before
3903  // (t.b.d. do a ML unbinned fit with buffer data)
3904  if (fBuffer) BufferEmpty();
3905 
3906  return ROOT::Fit::FitObject(this, f1 , fitOption , minOption, goption, range);
3907 }
3908 
3909 ////////////////////////////////////////////////////////////////////////////////
3910 /// Display a panel with all histogram fit options.
3911 ///
3912 /// See class TFitPanel for example
3913 
3914 void TH1::FitPanel()
3915 {
3916  if (!gPad)
3917  gROOT->MakeDefCanvas();
3918 
3919  if (!gPad) {
3920  Error("FitPanel", "Unable to create a default canvas");
3921  return;
3922  }
3923 
3924 
3925  // use plugin manager to create instance of TFitEditor
3926  TPluginHandler *handler = gROOT->GetPluginManager()->FindHandler("TFitEditor");
3927  if (handler && handler->LoadPlugin() != -1) {
3928  if (handler->ExecPlugin(2, gPad, this) == 0)
3929  Error("FitPanel", "Unable to create the FitPanel");
3930  }
3931  else
3932  Error("FitPanel", "Unable to find the FitPanel plug-in");
3933 }
3934 
3935 ////////////////////////////////////////////////////////////////////////////////
3936 /// Return an histogram containing the asymmetry of this histogram with h2,
3937 /// where the asymmetry is defined as:
3938 ///
3939 /// ~~~ {.cpp}
3940 /// Asymmetry = (h1 - h2)/(h1 + h2) where h1 = this
3941 /// ~~~
3942 ///
3943 /// works for 1D, 2D, etc. histograms
3944 /// c2 is an optional argument that gives a relative weight between the two
3945 /// histograms, and dc2 is the error on this weight. This is useful, for example,
3946 /// when forming an asymmetry between two histograms from 2 different data sets that
3947 /// need to be normalized to each other in some way. The function calculates
3948 /// the errors assuming Poisson statistics on h1 and h2 (that is, dh = sqrt(h)).
3949 ///
3950 /// example: assuming 'h1' and 'h2' are already filled
3951 ///
3952 /// ~~~ {.cpp}
3953 /// h3 = h1->GetAsymmetry(h2)
3954 /// ~~~
3955 ///
3956 /// then 'h3' is created and filled with the asymmetry between 'h1' and 'h2';
3957 /// h1 and h2 are left intact.
3958 ///
3959 /// Note that it is the user's responsibility to manage the created histogram.
3960 /// The name of the returned histogram will be `Asymmetry_nameOfh1-nameOfh2`
3961 ///
3962 /// code proposed by Jason Seely (seely@mit.edu) and adapted by R.Brun
3963 ///
3964 /// clone the histograms so top and bottom will have the
3965 /// correct dimensions:
3966 /// Sumw2 just makes sure the errors will be computed properly
3967 /// when we form sums and ratios below.
3968 
3969 TH1 *TH1::GetAsymmetry(TH1* h2, Double_t c2, Double_t dc2)
3970 {
3971  TH1 *h1 = this;
3972  TString name = TString::Format("Asymmetry_%s-%s",h1->GetName(),h2->GetName() );
3973  TH1 *asym = (TH1*)Clone(name);
3974 
3975  // set also the title
3976  TString title = TString::Format("(%s - %s)/(%s+%s)",h1->GetName(),h2->GetName(),h1->GetName(),h2->GetName() );
3977  asym->SetTitle(title);
3978 
3979  asym->Sumw2();
3980  Bool_t addStatus = TH1::AddDirectoryStatus();
3982  TH1 *top = (TH1*)asym->Clone();
3983  TH1 *bottom = (TH1*)asym->Clone();
3984  TH1::AddDirectory(addStatus);
3985 
3986  // form the top and bottom of the asymmetry, and then divide:
3987  top->Add(h1,h2,1,-c2);
3988  bottom->Add(h1,h2,1,c2);
3989  asym->Divide(top,bottom);
3990 
3991  Int_t xmax = asym->GetNbinsX();
3992  Int_t ymax = asym->GetNbinsY();
3993  Int_t zmax = asym->GetNbinsZ();
3994 
3995  if (h1->fBuffer) h1->BufferEmpty(1);
3996  if (h2->fBuffer) h2->BufferEmpty(1);
3997  if (bottom->fBuffer) bottom->BufferEmpty(1);
3998 
3999  // now loop over bins to calculate the correct errors
4000  // the reason this error calculation looks complex is because of c2
4001  for(Int_t i=1; i<= xmax; i++){
4002  for(Int_t j=1; j<= ymax; j++){
4003  for(Int_t k=1; k<= zmax; k++){
4004  Int_t bin = GetBin(i, j, k);
4005  // here some bin contents are written into variables to make the error
4006  // calculation a little more legible:
4007  Double_t a = h1->RetrieveBinContent(bin);
4008  Double_t b = h2->RetrieveBinContent(bin);
4009  Double_t bot = bottom->RetrieveBinContent(bin);
4010 
4011  // make sure there are some events, if not, then the errors are set = 0
4012  // automatically.
4013  //if(bot < 1){} was changed to the next line from recommendation of Jason Seely (28 Nov 2005)
4014  if(bot < 1e-6){}
4015  else{
4016  // computation of errors by Christos Leonidopoulos
4017  Double_t dasq = h1->GetBinErrorSqUnchecked(bin);
4018  Double_t dbsq = h2->GetBinErrorSqUnchecked(bin);
4019  Double_t error = 2*TMath::Sqrt(a*a*c2*c2*dbsq + c2*c2*b*b*dasq+a*a*b*b*dc2*dc2)/(bot*bot);
4020  asym->SetBinError(i,j,k,error);
4021  }
4022  }
4023  }
4024  }
4025  delete top;
4026  delete bottom;
4027 
4028  return asym;
4029 }
4030 
4031 ////////////////////////////////////////////////////////////////////////////////
4032 /// Static function
4033 /// return the default buffer size for automatic histograms
4034 /// the parameter fgBufferSize may be changed via SetDefaultBufferSize
4035 
4037 {
4039 }
4040 
4041 ////////////////////////////////////////////////////////////////////////////////
4042 /// Return kTRUE if TH1::Sumw2 must be called when creating new histograms.
4043 /// see TH1::SetDefaultSumw2.
4044 
4046 {
4048 }
4049 
4050 ////////////////////////////////////////////////////////////////////////////////
4051 /// Return the current number of entries.
4052 
4053 Double_t TH1::GetEntries() const
4054 {
4055  if (fBuffer) {
4056  Int_t nentries = (Int_t) fBuffer[0];
4057  if (nentries > 0) return nentries;
4058  }
4059 
4060  return fEntries;
4061 }
4062 
4063 ////////////////////////////////////////////////////////////////////////////////
4064 /// Number of effective entries of the histogram.
4065 ///
4066 /// \f[
4067 /// neff = \frac{(\sum Weights )^2}{(\sum Weight^2 )}
4068 /// \f]
4069 ///
4070 /// In case of an unweighted histogram this number is equivalent to the
4071 /// number of entries of the histogram.
4072 /// For a weighted histogram, this number corresponds to the hypothetical number of unweighted entries
4073 /// a histogram would need to have the same statistical power as this weighted histogram.
4074 /// Note: The underflow/overflow are included if one has set the TH1::StatOverFlows flag
4075 /// and if the statistics has been computed at filling time.
4076 /// If a range is set in the histogram the number is computed from the given range.
4077 
4079 {
4081  this->GetStats(s);// s[1] sum of squares of weights, s[0] sum of weights
4082  return (s[1] ? s[0]*s[0]/s[1] : TMath::Abs(s[0]) );
4083 }
4084 
4085 ////////////////////////////////////////////////////////////////////////////////
4086 /// Redefines TObject::GetObjectInfo.
4087 /// Displays the histogram info (bin number, contents, integral up to bin
4088 /// corresponding to cursor position px,py
4089 
4090 char *TH1::GetObjectInfo(Int_t px, Int_t py) const
4091 {
4092  return ((TH1*)this)->GetPainter()->GetObjectInfo(px,py);
4093 }
4094 
4095 ////////////////////////////////////////////////////////////////////////////////
4096 /// Return pointer to painter.
4097 /// If painter does not exist, it is created
4098 
4100 {
4101  if (!fPainter) {
4102  TString opt = option;
4103  opt.ToLower();
4104  if (opt.Contains("gl") || gStyle->GetCanvasPreferGL()) {
4105  //try to create TGLHistPainter
4106  TPluginHandler *handler = gROOT->GetPluginManager()->FindHandler("TGLHistPainter");
4107 
4108  if (handler && handler->LoadPlugin() != -1)
4109  fPainter = reinterpret_cast<TVirtualHistPainter *>(handler->ExecPlugin(1, this));
4110  }
4111  }
4112 
4114 
4115  return fPainter;
4116 }
4117 
4118 ////////////////////////////////////////////////////////////////////////////////
4119 /// Compute Quantiles for this histogram
4120 /// Quantile x_q of a probability distribution Function F is defined as
4121 ///
4122 /// ~~~ {.cpp}
4123 /// F(x_q) = q with 0 <= q <= 1.
4124 /// ~~~
4125 ///
4126 /// For instance the median x_0.5 of a distribution is defined as that value
4127 /// of the random variable for which the distribution function equals 0.5:
4128 ///
4129 /// ~~~ {.cpp}
4130 /// F(x_0.5) = Probability(x < x_0.5) = 0.5
4131 /// ~~~
4132 ///
4133 /// code from Eddy Offermann, Renaissance
4134 ///
4135 /// \param[in] nprobSum maximum size of array q and size of array probSum (if given)
4136 /// \param[in] probSum array of positions where quantiles will be computed.
4137 /// - if probSum is null, probSum will be computed internally and will
4138 /// have a size = number of bins + 1 in h. it will correspond to the
4139 /// quantiles calculated at the lowest edge of the histogram (quantile=0) and
4140 /// all the upper edges of the bins.
4141 /// - if probSum is not null, it is assumed to contain at least nprobSum values.
4142 /// \param[out] q array q filled with nq quantiles
4143 /// \return value nq (<=nprobSum) with the number of quantiles computed
4144 ///
4145 /// Note that the Integral of the histogram is automatically recomputed
4146 /// if the number of entries is different of the number of entries when
4147 /// the integral was computed last time. In case you do not use the Fill
4148 /// functions to fill your histogram, but SetBinContent, you must call
4149 /// TH1::ComputeIntegral before calling this function.
4150 ///
4151 /// Getting quantiles q from two histograms and storing results in a TGraph,
4152 /// a so-called QQ-plot
4153 ///
4154 /// ~~~ {.cpp}
4155 /// TGraph *gr = new TGraph(nprob);
4156 /// h1->GetQuantiles(nprob,gr->GetX());
4157 /// h2->GetQuantiles(nprob,gr->GetY());
4158 /// gr->Draw("alp");
4159 /// ~~~
4160 ///
4161 /// Example:
4162 ///
4163 /// ~~~ {.cpp}
4164 /// void quantiles() {
4165 /// // demo for quantiles
4166 /// const Int_t nq = 20;
4167 /// TH1F *h = new TH1F("h","demo quantiles",100,-3,3);
4168 /// h->FillRandom("gaus",5000);
4169 ///
4170 /// Double_t xq[nq]; // position where to compute the quantiles in [0,1]
4171 /// Double_t yq[nq]; // array to contain the quantiles
4172 /// for (Int_t i=0;i<nq;i++) xq[i] = Float_t(i+1)/nq;
4173 /// h->GetQuantiles(nq,yq,xq);
4174 ///
4175 /// //show the original histogram in the top pad
4176 /// TCanvas *c1 = new TCanvas("c1","demo quantiles",10,10,700,900);
4177 /// c1->Divide(1,2);
4178 /// c1->cd(1);
4179 /// h->Draw();
4180 ///
4181 /// // show the quantiles in the bottom pad
4182 /// c1->cd(2);
4183 /// gPad->SetGrid();
4184 /// TGraph *gr = new TGraph(nq,xq,yq);
4185 /// gr->SetMarkerStyle(21);
4186 /// gr->Draw("alp");
4187 /// }
4188 /// ~~~
4189 
4190 Int_t TH1::GetQuantiles(Int_t nprobSum, Double_t *q, const Double_t *probSum)
4191 {
4192  if (GetDimension() > 1) {
4193  Error("GetQuantiles","Only available for 1-d histograms");
4194  return 0;
4195  }
4196 
4197  const Int_t nbins = GetXaxis()->GetNbins();
4198  if (!fIntegral) ComputeIntegral();
4199  if (fIntegral[nbins+1] != fEntries) ComputeIntegral();
4200 
4201  Int_t i, ibin;
4202  Double_t *prob = (Double_t*)probSum;
4203  Int_t nq = nprobSum;
4204  if (probSum == 0) {
4205  nq = nbins+1;
4206  prob = new Double_t[nq];
4207  prob[0] = 0;
4208  for (i=1;i<nq;i++) {
4209  prob[i] = fIntegral[i]/fIntegral[nbins];
4210  }
4211  }
4212 
4213  for (i = 0; i < nq; i++) {
4214  ibin = TMath::BinarySearch(nbins,fIntegral,prob[i]);
4215  while (ibin < nbins-1 && fIntegral[ibin+1] == prob[i]) {
4216  if (fIntegral[ibin+2] == prob[i]) ibin++;
4217  else break;
4218  }
4219  q[i] = GetBinLowEdge(ibin+1);
4220  const Double_t dint = fIntegral[ibin+1]-fIntegral[ibin];
4221  if (dint > 0) q[i] += GetBinWidth(ibin+1)*(prob[i]-fIntegral[ibin])/dint;
4222  }
4223 
4224  if (!probSum) delete [] prob;
4225  return nq;
4226 }
4227 
4228 ////////////////////////////////////////////////////////////////////////////////
4229 /// Decode string choptin and fill fitOption structure.
4230 
4231 Int_t TH1::FitOptionsMake(Option_t *choptin, Foption_t &fitOption)
4232 {
4234  return 1;
4235 }
4236 
4237 ////////////////////////////////////////////////////////////////////////////////
4238 /// Compute Initial values of parameters for a gaussian.
4239 
4240 void H1InitGaus()
4241 {
4242  Double_t allcha, sumx, sumx2, x, val, stddev, mean;
4243  Int_t bin;
4244  const Double_t sqrtpi = 2.506628;
4245 
4246  // - Compute mean value and StdDev of the histogram in the given range
4248  TH1 *curHist = (TH1*)hFitter->GetObjectFit();
4249  Int_t hxfirst = hFitter->GetXfirst();
4250  Int_t hxlast = hFitter->GetXlast();
4251  Double_t valmax = curHist->GetBinContent(hxfirst);
4252  Double_t binwidx = curHist->GetBinWidth(hxfirst);
4253  allcha = sumx = sumx2 = 0;
4254  for (bin=hxfirst;bin<=hxlast;bin++) {
4255  x = curHist->GetBinCenter(bin);
4256  val = TMath::Abs(curHist->GetBinContent(bin));
4257  if (val > valmax) valmax = val;
4258  sumx += val*x;
4259  sumx2 += val*x*x;
4260  allcha += val;
4261  }
4262  if (allcha == 0) return;
4263  mean = sumx/allcha;
4264  stddev = sumx2/allcha - mean*mean;
4265  if (stddev > 0) stddev = TMath::Sqrt(stddev);
4266  else stddev = 0;
4267  if (stddev == 0) stddev = binwidx*(hxlast-hxfirst+1)/4;
4268  //if the distribution is really gaussian, the best approximation
4269  //is binwidx*allcha/(sqrtpi*stddev)
4270  //However, in case of non-gaussian tails, this underestimates
4271  //the normalisation constant. In this case the maximum value
4272  //is a better approximation.
4273  //We take the average of both quantities
4274  Double_t constant = 0.5*(valmax+binwidx*allcha/(sqrtpi*stddev));
4275 
4276  //In case the mean value is outside the histo limits and
4277  //the StdDev is bigger than the range, we take
4278  // mean = center of bins
4279  // stddev = half range
4280  Double_t xmin = curHist->GetXaxis()->GetXmin();
4281  Double_t xmax = curHist->GetXaxis()->GetXmax();
4282  if ((mean < xmin || mean > xmax) && stddev > (xmax-xmin)) {
4283  mean = 0.5*(xmax+xmin);
4284  stddev = 0.5*(xmax-xmin);
4285  }
4286  TF1 *f1 = (TF1*)hFitter->GetUserFunc();
4287  f1->SetParameter(0,constant);
4288  f1->SetParameter(1,mean);
4289  f1->SetParameter(2,stddev);
4290  f1->SetParLimits(2,0,10*stddev);
4291 }
4292 
4293 ////////////////////////////////////////////////////////////////////////////////
4294 /// Compute Initial values of parameters for an exponential.
4295 
4296 void H1InitExpo()
4297 {
4298  Double_t constant, slope;
4299  Int_t ifail;
4301  Int_t hxfirst = hFitter->GetXfirst();
4302  Int_t hxlast = hFitter->GetXlast();
4303  Int_t nchanx = hxlast - hxfirst + 1;
4304 
4305  H1LeastSquareLinearFit(-nchanx, constant, slope, ifail);
4306 
4307  TF1 *f1 = (TF1*)hFitter->GetUserFunc();
4308  f1->SetParameter(0,constant);
4309  f1->SetParameter(1,slope);
4310 
4311 }
4312 
4313 ////////////////////////////////////////////////////////////////////////////////
4314 /// Compute Initial values of parameters for a polynom.
4315 
4316 void H1InitPolynom()
4317 {
4318  Double_t fitpar[25];
4319 
4321  TF1 *f1 = (TF1*)hFitter->GetUserFunc();
4322  Int_t hxfirst = hFitter->GetXfirst();
4323  Int_t hxlast = hFitter->GetXlast();
4324  Int_t nchanx = hxlast - hxfirst + 1;
4325  Int_t npar = f1->GetNpar();
4326 
4327  if (nchanx <=1 || npar == 1) {
4328  TH1 *curHist = (TH1*)hFitter->GetObjectFit();
4329  fitpar[0] = curHist->GetSumOfWeights()/Double_t(nchanx);
4330  } else {
4331  H1LeastSquareFit( nchanx, npar, fitpar);
4332  }
4333  for (Int_t i=0;i<npar;i++) f1->SetParameter(i, fitpar[i]);
4334 }
4335 
4336 ////////////////////////////////////////////////////////////////////////////////
4337 /// Least squares lpolynomial fitting without weights.
4338 ///
4339 /// \param[in] n number of points to fit
4340 /// \param[in] m number of parameters
4341 /// \param[in] a array of parameters
4342 ///
4343 /// based on CERNLIB routine LSQ: Translated to C++ by Rene Brun
4344 /// (E.Keil. revised by B.Schorr, 23.10.1981.)
4345 
4346 void H1LeastSquareFit(Int_t n, Int_t m, Double_t *a)
4347 {
4348  const Double_t zero = 0.;
4349  const Double_t one = 1.;
4350  const Int_t idim = 20;
4351 
4352  Double_t b[400] /* was [20][20] */;
4353  Int_t i, k, l, ifail;
4354  Double_t power;
4355  Double_t da[20], xk, yk;
4356 
4357  if (m <= 2) {
4358  H1LeastSquareLinearFit(n, a[0], a[1], ifail);
4359  return;
4360  }
4361  if (m > idim || m > n) return;
4362  b[0] = Double_t(n);
4363  da[0] = zero;
4364  for (l = 2; l <= m; ++l) {
4365  b[l-1] = zero;
4366  b[m + l*20 - 21] = zero;
4367  da[l-1] = zero;
4368  }
4370  TH1 *curHist = (TH1*)hFitter->GetObjectFit();
4371  Int_t hxfirst = hFitter->GetXfirst();
4372  Int_t hxlast = hFitter->GetXlast();
4373  for (k = hxfirst; k <= hxlast; ++k) {
4374  xk = curHist->GetBinCenter(k);
4375  yk = curHist->GetBinContent(k);
4376  power = one;
4377  da[0] += yk;
4378  for (l = 2; l <= m; ++l) {
4379  power *= xk;
4380  b[l-1] += power;
4381  da[l-1] += power*yk;
4382  }
4383  for (l = 2; l <= m; ++l) {
4384  power *= xk;
4385  b[m + l*20 - 21] += power;
4386  }
4387  }
4388  for (i = 3; i <= m; ++i) {
4389  for (k = i; k <= m; ++k) {
4390  b[k - 1 + (i-1)*20 - 21] = b[k + (i-2)*20 - 21];
4391  }
4392  }
4393  H1LeastSquareSeqnd(m, b, idim, ifail, 1, da);
4394 
4395  for (i=0; i<m; ++i) a[i] = da[i];
4396 
4397 }
4398 
4399 ////////////////////////////////////////////////////////////////////////////////
4400 /// Least square linear fit without weights.
4401 ///
4402 /// extracted from CERNLIB LLSQ: Translated to C++ by Rene Brun
4403 /// (added to LSQ by B. Schorr, 15.02.1982.)
4404 
4405 void H1LeastSquareLinearFit(Int_t ndata, Double_t &a0, Double_t &a1, Int_t &ifail)
4406 {
4407  Double_t xbar, ybar, x2bar;
4408  Int_t i, n;
4409  Double_t xybar;
4410  Double_t fn, xk, yk;
4411  Double_t det;
4412 
4413  n = TMath::Abs(ndata);
4414  ifail = -2;
4415  xbar = ybar = x2bar = xybar = 0;
4417  TH1 *curHist = (TH1*)hFitter->GetObjectFit();
4418  Int_t hxfirst = hFitter->GetXfirst();
4419  Int_t hxlast = hFitter->GetXlast();
4420  for (i = hxfirst; i <= hxlast; ++i) {
4421  xk = curHist->GetBinCenter(i);
4422  yk = curHist->GetBinContent(i);
4423  if (ndata < 0) {
4424  if (yk <= 0) yk = 1e-9;
4425  yk = TMath::Log(yk);
4426  }
4427  xbar += xk;
4428  ybar += yk;
4429  x2bar += xk*xk;
4430  xybar += xk*yk;
4431  }
4432  fn = Double_t(n);
4433  det = fn*x2bar - xbar*xbar;
4434  ifail = -1;
4435  if (det <= 0) {
4436  a0 = ybar/fn;
4437  a1 = 0;
4438  return;
4439  }
4440  ifail = 0;
4441  a0 = (x2bar*ybar - xbar*xybar) / det;
4442  a1 = (fn*xybar - xbar*ybar) / det;
4443 
4444 }
4445 
4446 ////////////////////////////////////////////////////////////////////////////////
4447 /// Extracted from CERN Program library routine DSEQN.
4448 ///
4449 /// Translated to C++ by Rene Brun
4450 
4451 void H1LeastSquareSeqnd(Int_t n, Double_t *a, Int_t idim, Int_t &ifail, Int_t k, Double_t *b)
4452 {
4453  Int_t a_dim1, a_offset, b_dim1, b_offset;
4454  Int_t nmjp1, i, j, l;
4455  Int_t im1, jp1, nm1, nmi;
4456  Double_t s1, s21, s22;
4457  const Double_t one = 1.;
4458 
4459  /* Parameter adjustments */
4460  b_dim1 = idim;
4461  b_offset = b_dim1 + 1;
4462  b -= b_offset;
4463  a_dim1 = idim;
4464  a_offset = a_dim1 + 1;
4465  a -= a_offset;
4466 
4467  if (idim < n) return;
4468 
4469  ifail = 0;
4470  for (j = 1; j <= n; ++j) {
4471  if (a[j + j*a_dim1] <= 0) { ifail = -1; return; }
4472  a[j + j*a_dim1] = one / a[j + j*a_dim1];
4473  if (j == n) continue;
4474  jp1 = j + 1;
4475  for (l = jp1; l <= n; ++l) {
4476  a[j + l*a_dim1] = a[j + j*a_dim1] * a[l + j*a_dim1];
4477  s1 = -a[l + (j+1)*a_dim1];
4478  for (i = 1; i <= j; ++i) { s1 = a[l + i*a_dim1] * a[i + (j+1)*a_dim1] + s1; }
4479  a[l + (j+1)*a_dim1] = -s1;
4480  }
4481  }
4482  if (k <= 0) return;
4483 
4484  for (l = 1; l <= k; ++l) {
4485  b[l*b_dim1 + 1] = a[a_dim1 + 1]*b[l*b_dim1 + 1];
4486  }
4487  if (n == 1) return;
4488  for (l = 1; l <= k; ++l) {
4489  for (i = 2; i <= n; ++i) {
4490  im1 = i - 1;
4491  s21 = -b[i + l*b_dim1];
4492  for (j = 1; j <= im1; ++j) {
4493  s21 = a[i + j*a_dim1]*b[j + l*b_dim1] + s21;
4494  }
4495  b[i + l*b_dim1] = -a[i + i*a_dim1]*s21;
4496  }
4497  nm1 = n - 1;
4498  for (i = 1; i <= nm1; ++i) {
4499  nmi = n - i;
4500  s22 = -b[nmi + l*b_dim1];
4501  for (j = 1; j <= i; ++j) {
4502  nmjp1 = n - j + 1;
4503  s22 = a[nmi + nmjp1*a_dim1]*b[nmjp1 + l*b_dim1] + s22;
4504  }
4505  b[nmi + l*b_dim1] = -s22;
4506  }
4507  }
4508 }
4509 
4510 ////////////////////////////////////////////////////////////////////////////////
4511 /// Return Global bin number corresponding to binx,y,z.
4512 ///
4513 /// 2-D and 3-D histograms are represented with a one dimensional
4514 /// structure.
4515 /// This has the advantage that all existing functions, such as
4516 /// GetBinContent, GetBinError, GetBinFunction work for all dimensions.
4517 ///
4518 /// In case of a TH1x, returns binx directly.
4519 /// see TH1::GetBinXYZ for the inverse transformation.
4520 ///
4521 /// Convention for numbering bins
4522 ///
4523 /// For all histogram types: nbins, xlow, xup
4524 ///
4525 /// - bin = 0; underflow bin
4526 /// - bin = 1; first bin with low-edge xlow INCLUDED
4527 /// - bin = nbins; last bin with upper-edge xup EXCLUDED
4528 /// - bin = nbins+1; overflow bin
4529 ///
4530 /// In case of 2-D or 3-D histograms, a "global bin" number is defined.
4531 /// For example, assuming a 3-D histogram with binx,biny,binz, the function
4532 ///
4533 /// ~~~ {.cpp}
4534 /// Int_t bin = h->GetBin(binx,biny,binz);
4535 /// ~~~
4536 ///
4537 /// returns a global/linearized bin number. This global bin is useful
4538 /// to access the bin information independently of the dimension.
4539 
4540 Int_t TH1::GetBin(Int_t binx, Int_t, Int_t) const
4541 {
4542  Int_t ofx = fXaxis.GetNbins() + 1; // overflow bin
4543  if (binx < 0) binx = 0;
4544  if (binx > ofx) binx = ofx;
4545 
4546  return binx;
4547 }
4548 
4549 ////////////////////////////////////////////////////////////////////////////////
4550 /// Return binx, biny, binz corresponding to the global bin number globalbin
4551 /// see TH1::GetBin function above
4552 
4553 void TH1::GetBinXYZ(Int_t binglobal, Int_t &binx, Int_t &biny, Int_t &binz) const
4554 {
4556  Int_t ny = fYaxis.GetNbins()+2;
4557 
4558  if (GetDimension() == 1) {
4559  binx = binglobal%nx;
4560  biny = 0;
4561  binz = 0;
4562  return;
4563  }
4564  if (GetDimension() == 2) {
4565  binx = binglobal%nx;
4566  biny = ((binglobal-binx)/nx)%ny;
4567  binz = 0;
4568  return;
4569  }
4570  if (GetDimension() == 3) {
4571  binx = binglobal%nx;
4572  biny = ((binglobal-binx)/nx)%ny;
4573  binz = ((binglobal-binx)/nx -biny)/ny;
4574  }
4575 }
4576 
4577 ////////////////////////////////////////////////////////////////////////////////
4578 /// Return a random number distributed according the histogram bin contents.
4579 /// This function checks if the bins integral exists. If not, the integral
4580 /// is evaluated, normalized to one.
4581 ///
4582 /// The integral is automatically recomputed if the number of entries
4583 /// is not the same then when the integral was computed.
4584 /// NB Only valid for 1-d histograms. Use GetRandom2 or 3 otherwise.
4585 /// If the histogram has a bin with negative content a NaN is returned
4586 
4587 Double_t TH1::GetRandom() const
4588 {
4589  if (fDimension > 1) {
4590  Error("GetRandom","Function only valid for 1-d histograms");
4591  return 0;
4592  }
4593  Int_t nbinsx = GetNbinsX();
4594  Double_t integral = 0;
4595  // compute integral checking that all bins have positive content (see ROOT-5894)
4596  if (fIntegral) {
4597  if (fIntegral[nbinsx+1] != fEntries) integral = ((TH1*)this)->ComputeIntegral(true);
4598  else integral = fIntegral[nbinsx];
4599  } else {
4600  integral = ((TH1*)this)->ComputeIntegral(true);
4601  }
4602  if (integral == 0) return 0;
4603  // return a NaN in case some bins have negative content
4604  if (integral == TMath::QuietNaN() ) return TMath::QuietNaN();
4605 
4606  Double_t r1 = gRandom->Rndm();
4607  Int_t ibin = TMath::BinarySearch(nbinsx,fIntegral,r1);
4608  Double_t x = GetBinLowEdge(ibin+1);
4609  if (r1 > fIntegral[ibin]) x +=
4610  GetBinWidth(ibin+1)*(r1-fIntegral[ibin])/(fIntegral[ibin+1] - fIntegral[ibin]);
4611  return x;
4612 }
4613 
4614 ////////////////////////////////////////////////////////////////////////////////
4615 /// Return content of bin number bin.
4616 ///
4617 /// Implemented in TH1C,S,F,D
4618 ///
4619 /// Convention for numbering bins
4620 ///
4621 /// For all histogram types: nbins, xlow, xup
4622 ///
4623 /// - bin = 0; underflow bin
4624 /// - bin = 1; first bin with low-edge xlow INCLUDED
4625 /// - bin = nbins; last bin with upper-edge xup EXCLUDED
4626 /// - bin = nbins+1; overflow bin
4627 ///
4628 /// In case of 2-D or 3-D histograms, a "global bin" number is defined.
4629 /// For example, assuming a 3-D histogram with binx,biny,binz, the function
4630 ///
4631 /// ~~~ {.cpp}
4632 /// Int_t bin = h->GetBin(binx,biny,binz);
4633 /// ~~~
4634 ///
4635 /// returns a global/linearized bin number. This global bin is useful
4636 /// to access the bin information independently of the dimension.
4637 
4639 {
4640  if (fBuffer) const_cast<TH1*>(this)->BufferEmpty();
4641  if (bin < 0) bin = 0;
4642  if (bin >= fNcells) bin = fNcells-1;
4643 
4644  return RetrieveBinContent(bin);
4645 }
4646 
4647 ////////////////////////////////////////////////////////////////////////////////
4648 /// Compute first binx in the range [firstx,lastx] for which
4649 /// diff = abs(bin_content-c) <= maxdiff
4650 ///
4651 /// In case several bins in the specified range with diff=0 are found
4652 /// the first bin found is returned in binx.
4653 /// In case several bins in the specified range satisfy diff <=maxdiff
4654 /// the bin with the smallest difference is returned in binx.
4655 /// In all cases the function returns the smallest difference.
4656 ///
4657 /// NOTE1: if firstx <= 0, firstx is set to bin 1
4658 /// if (lastx < firstx then firstx is set to the number of bins
4659 /// ie if firstx=0 and lastx=0 (default) the search is on all bins.
4660 ///
4661 /// NOTE2: if maxdiff=0 (default), the first bin with content=c is returned.
4662 
4663 Double_t TH1::GetBinWithContent(Double_t c, Int_t &binx, Int_t firstx, Int_t lastx,Double_t maxdiff) const
4664 {
4665  if (fDimension > 1) {
4666  binx = 0;
4667  Error("GetBinWithContent","function is only valid for 1-D histograms");
4668  return 0;
4669  }
4670 
4671  if (fBuffer) ((TH1*)this)->BufferEmpty();
4672 
4673  if (firstx <= 0) firstx = 1;
4674  if (lastx < firstx) lastx = fXaxis.GetNbins();
4675  Int_t binminx = 0;
4676  Double_t diff, curmax = 1.e240;
4677  for (Int_t i=firstx;i<=lastx;i++) {
4678  diff = TMath::Abs(RetrieveBinContent(i)-c);
4679  if (diff <= 0) {binx = i; return diff;}
4680  if (diff < curmax && diff <= maxdiff) {curmax = diff, binminx=i;}
4681  }
4682  binx = binminx;
4683  return curmax;
4684 }
4685 
4686 ////////////////////////////////////////////////////////////////////////////////
4687 /// Given a point x, approximates the value via linear interpolation
4688 /// based on the two nearest bin centers
4689 ///
4690 /// Andy Mastbaum 10/21/08
4691 
4693 {
4694  if (fBuffer) ((TH1*)this)->BufferEmpty();
4695 
4696  Int_t xbin = FindBin(x);
4697  Double_t x0,x1,y0,y1;
4698 
4699  if(x<=GetBinCenter(1)) {
4700  return RetrieveBinContent(1);
4701  } else if(x>=GetBinCenter(GetNbinsX())) {
4702  return RetrieveBinContent(GetNbinsX());
4703  } else {
4704  if(x<=GetBinCenter(xbin)) {
4705  y0 = RetrieveBinContent(xbin-1);
4706  x0 = GetBinCenter(xbin-1);
4707  y1 = RetrieveBinContent(xbin);
4708  x1 = GetBinCenter(xbin);
4709  } else {
4710  y0 = RetrieveBinContent(xbin);
4711  x0 = GetBinCenter(xbin);
4712  y1 = RetrieveBinContent(xbin+1);
4713  x1 = GetBinCenter(xbin+1);
4714  }
4715  return y0 + (x-x0)*((y1-y0)/(x1-x0));
4716  }
4717 }
4718 
4719 ////////////////////////////////////////////////////////////////////////////////
4720 /// Interpolate. Not yet implemented.
4721 
4723 {
4724  Error("Interpolate","This function must be called with 1 argument for a TH1");
4725  return 0;
4726 }
4727 
4728 ////////////////////////////////////////////////////////////////////////////////
4729 /// Interpolate. Not yet implemented.
4730 
4732 {
4733  Error("Interpolate","This function must be called with 1 argument for a TH1");
4734  return 0;
4735 }
4736 
4737 ////////////////////////////////////////////////////////////////////////////////
4738 /// Return true if the bin is overflow.
4739 
4740 Bool_t TH1::IsBinOverflow(Int_t bin) const
4741 {
4742  Int_t binx, biny, binz;
4743  GetBinXYZ(bin, binx, biny, binz);
4744 
4745  if ( fDimension == 1 )
4746  return binx >= GetNbinsX() + 1;
4747  else if ( fDimension == 2 )
4748  return (binx >= GetNbinsX() + 1) ||
4749  (biny >= GetNbinsY() + 1);
4750  else if ( fDimension == 3 )
4751  return (binx >= GetNbinsX() + 1) ||
4752  (biny >= GetNbinsY() + 1) ||
4753  (binz >= GetNbinsZ() + 1);
4754  else
4755  return 0;
4756 }
4757 
4758 ////////////////////////////////////////////////////////////////////////////////
4759 /// Return true if the bin is underflow.
4760 
4761 Bool_t TH1::IsBinUnderflow(Int_t bin) const
4762 {
4763  Int_t binx, biny, binz;
4764  GetBinXYZ(bin, binx, biny, binz);
4765 
4766  if ( fDimension == 1 )
4767  return (binx <= 0);
4768  else if ( fDimension == 2 )
4769  return (binx <= 0 || biny <= 0);
4770  else if ( fDimension == 3 )
4771  return (binx <= 0 || biny <= 0 || binz <= 0);
4772  else
4773  return 0;
4774 }
4775 
4776 ////////////////////////////////////////////////////////////////////////////////
4777 /// Reduce the number of bins for the axis passed in the option to the number of bins having a label.
4778 /// The method will remove only the extra bins existing after the last "labeled" bin.
4779 /// Note that if there are "un-labeled" bins present between "labeled" bins they will not be removed
4780 
4781 void TH1::LabelsDeflate(Option_t *ax)
4782 {
4783  Int_t iaxis = AxisChoice(ax);
4784  TAxis *axis = 0;
4785  if (iaxis == 1) axis = GetXaxis();
4786  if (iaxis == 2) axis = GetYaxis();
4787  if (iaxis == 3) axis = GetZaxis();
4788  if (!axis) {
4789  Error("LabelsDeflate","Invalid axis option %s",ax);
4790  return;
4791  }
4792  if (!axis->GetLabels()) return;
4793 
4794  // find bin with last labels
4795  // bin number is object ID in list of labels
4796  // therefore max bin number is number of bins of the deflated histograms
4797  TIter next(axis->GetLabels());
4798  TObject *obj;
4799  Int_t nbins = 0;
4800  while ((obj = next())) {
4801  Int_t ibin = obj->GetUniqueID();
4802  if (ibin > nbins) nbins = ibin;
4803  }
4804  if (nbins < 1) nbins = 1;
4805  TH1 *hold = (TH1*)IsA()->New();
4806  R__ASSERT(hold);
4807  hold->SetDirectory(0);
4808  Copy(*hold);
4809 
4810  Bool_t timedisp = axis->GetTimeDisplay();
4811  Double_t xmin = axis->GetXmin();
4812  Double_t xmax = axis->GetBinUpEdge(nbins);
4813  if (xmax <= xmin) xmax = xmin +nbins;
4814  axis->SetRange(0,0);
4815  axis->Set(nbins,xmin,xmax);
4816  SetBinsLength(-1); // reset the number of cells
4817  Int_t errors = fSumw2.fN;
4818  if (errors) fSumw2.Set(fNcells);
4819  axis->SetTimeDisplay(timedisp);
4820  // reset histogram content
4821  Reset("ICE");
4822 
4823  //now loop on all bins and refill
4824  // NOTE that if the bins without labels have content
4825  // it will be put in the underflow/overflow.
4826  // For this reason we use AddBinContent method
4827  Double_t oldEntries = fEntries;
4828  Int_t bin,binx,biny,binz;
4829  for (bin=0; bin < hold->fNcells; ++bin) {
4830  hold->GetBinXYZ(bin,binx,biny,binz);
4831  Int_t ibin = GetBin(binx,biny,binz);
4832  Double_t cu = hold->RetrieveBinContent(bin);
4833  AddBinContent(ibin,cu);
4834  if (errors) {
4835  fSumw2.fArray[ibin] += hold->fSumw2.fArray[bin];
4836  }
4837  }
4838  fEntries = oldEntries;
4839  delete hold;
4840 }
4841 
4842 ////////////////////////////////////////////////////////////////////////////////
4843 /// Double the number of bins for axis.
4844 /// Refill histogram
4845 /// This function is called by TAxis::FindBin(const char *label)
4846 
4847 void TH1::LabelsInflate(Option_t *ax)
4848 {
4849  Int_t iaxis = AxisChoice(ax);
4850  TAxis *axis = 0;
4851  if (iaxis == 1) axis = GetXaxis();
4852  if (iaxis == 2) axis = GetYaxis();
4853  if (iaxis == 3) axis = GetZaxis();
4854  if (!axis) return;
4855 
4856  TH1 *hold = (TH1*)IsA()->New();;
4857  hold->SetDirectory(0);
4858  Copy(*hold);
4859 
4860  Bool_t timedisp = axis->GetTimeDisplay();
4861  Int_t nbins = axis->GetNbins();
4862  Double_t xmin = axis->GetXmin();
4863  Double_t xmax = axis->GetXmax();
4864  xmax = xmin + 2*(xmax-xmin);
4865  axis->SetRange(0,0);
4866  // double the bins and recompute ncells
4867  axis->Set(2*nbins,xmin,xmax);
4868  SetBinsLength(-1);
4869  Int_t errors = fSumw2.fN;
4870  if (errors) fSumw2.Set(fNcells);
4871  axis->SetTimeDisplay(timedisp);
4872 
4873  Reset("ICE"); // reset content and error
4874 
4875  //now loop on all bins and refill
4876  Double_t oldEntries = fEntries;
4877  Int_t bin,ibin,binx,biny,binz;
4878  for (ibin =0; ibin < hold->fNcells; ibin++) {
4879  // get the binx,y,z values . This will stay the same between new-old after the expanding
4880  hold->GetBinXYZ(ibin,binx,biny,binz);
4881  bin = GetBin(binx,biny,binz);
4882 
4883  // underflow and overflow will be cleaned up because their meaning has been altered
4884  if (hold->IsBinUnderflow(ibin) || hold->IsBinOverflow(ibin)) continue;
4885  else {
4886  AddBinContent(bin, hold->RetrieveBinContent(ibin));
4887  if (errors) fSumw2.fArray[bin] += hold->fSumw2.fArray[ibin];
4888  }
4889  }
4890  fEntries = oldEntries;
4891  delete hold;
4892 }
4893 
4894 ////////////////////////////////////////////////////////////////////////////////
4895 /// Set option(s) to draw axis with labels
4896 /// \param[in] option
4897 /// - "a" sort by alphabetic order
4898 /// - ">" sort by decreasing values
4899 /// - "<" sort by increasing values
4900 /// - "h" draw labels horizontal
4901 /// - "v" draw labels vertical
4902 /// - "u" draw labels up (end of label right adjusted)
4903 /// - "d" draw labels down (start of label left adjusted)
4904 /// \param[in] ax axis
4905 
4906 void TH1::LabelsOption(Option_t *option, Option_t *ax)
4907 {
4908  Int_t iaxis = AxisChoice(ax);
4909  TAxis *axis = 0;
4910  if (iaxis == 1) axis = GetXaxis();
4911  if (iaxis == 2) axis = GetYaxis();
4912  if (iaxis == 3) axis = GetZaxis();
4913  if (!axis) return;
4914  THashList *labels = axis->GetLabels();
4915  if (!labels) {
4916  Warning("LabelsOption","Cannot sort. No labels");
4917  return;
4918  }
4919  TString opt = option;
4920  opt.ToLower();
4921  if (opt.Contains("h")) {
4922  axis->SetBit(TAxis::kLabelsHori);
4925  axis->ResetBit(TAxis::kLabelsUp);
4926  }
4927  if (opt.Contains("v")) {
4928  axis->SetBit(TAxis::kLabelsVert);
4931  axis->ResetBit(TAxis::kLabelsUp);
4932  }
4933  if (opt.Contains("u")) {
4934  axis->SetBit(TAxis::kLabelsUp);
4938  }
4939  if (opt.Contains("d")) {
4940  axis->SetBit(TAxis::kLabelsDown);
4943  axis->ResetBit(TAxis::kLabelsUp);
4944  }
4945  Int_t sort = -1;
4946  if (opt.Contains("a")) sort = 0;
4947  if (opt.Contains(">")) sort = 1;
4948  if (opt.Contains("<")) sort = 2;
4949  if (sort < 0) return;
4950  if (sort > 0 && GetDimension() > 2) {
4951  Error("LabelsOption","Sorting by value not implemented for 3-D histograms");
4952  return;
4953  }
4954 
4955  Double_t entries = fEntries;
4956  Int_t n = TMath::Min(axis->GetNbins(), labels->GetSize());
4957  std::vector<Int_t> a(n+2);
4958 
4959  Int_t i,j,k;
4960  std::vector<Double_t> cont;
4961  std::vector<Double_t> errors;
4962  THashList *labold = new THashList(labels->GetSize(),1);
4963  TIter nextold(labels);
4964  TObject *obj;
4965  while ((obj=nextold())) {
4966  labold->Add(obj);
4967  }
4968  labels->Clear();
4969  if (sort > 0) {
4970  //---sort by values of bins
4971  if (GetDimension() == 1) {
4972  cont.resize(n);
4973  if (fSumw2.fN) errors.resize(n);
4974  for (i=1;i<=n;i++) {
4975  cont[i-1] = GetBinContent(i);
4976  if (!errors.empty()) errors[i-1] = GetBinError(i);
4977  }
4978  if (sort ==1) TMath::Sort(n,cont.data(),a.data(),kTRUE); //sort by decreasing values
4979  else TMath::Sort(n,cont.data(),a.data(),kFALSE); //sort by increasing values
4980  for (i=1;i<=n;i++) {
4981  SetBinContent(i,cont[a[i-1]]);
4982  if (!errors.empty()) SetBinError(i,errors[a[i-1]]);
4983  }
4984  for (i=1;i<=n;i++) {
4985  obj = labold->At(a[i-1]);
4986  labels->Add(obj);
4987  obj->SetUniqueID(i);
4988  }
4989  } else if (GetDimension()== 2) {
4990  std::vector<Double_t> pcont(n+2);
4991  Int_t nx = fXaxis.GetNbins();
4992  Int_t ny = fYaxis.GetNbins();
4993  cont.resize( (nx+2)*(ny+2));
4994  if (fSumw2.fN) errors.resize( (nx+2)*(ny+2));
4995  for (i=1;i<=nx;i++) {
4996  for (j=1;j<=ny;j++) {
4997  cont[i+nx*j] = GetBinContent(i,j);
4998  if (!errors.empty()) errors[i+nx*j] = GetBinError(i,j);
4999  if (axis == GetXaxis()) k = i;
5000  else k = j;
5001  pcont[k-1] += cont[i+nx*j];
5002  }
5003  }
5004  if (sort ==1) TMath::Sort(n,pcont.data(),a.data(),kTRUE); //sort by decreasing values
5005  else TMath::Sort(n,pcont.data(),a.data(),kFALSE); //sort by increasing values
5006  for (i=0;i<n;i++) {
5007  obj = labold->At(a[i]);
5008  labels->Add(obj);
5009  obj->SetUniqueID(i+1);
5010  }
5011  if (axis == GetXaxis()) {
5012  for (i=1;i<=n;i++) {
5013  for (j=1;j<=ny;j++) {
5014  SetBinContent(i,j,cont[a[i-1]+1+nx*j]);
5015  if (!errors.empty()) SetBinError(i,j,errors[a[i-1]+1+nx*j]);
5016  }
5017  }
5018  }
5019  else {
5020  // using y axis
5021  for (i=1;i<=nx;i++) {
5022  for (j=1;j<=n;j++) {
5023  SetBinContent(i,j,cont[i+nx*(a[j-1]+1)]);
5024  if (!errors.empty()) SetBinError(i,j,errors[i+nx*(a[j-1]+1)]);
5025  }
5026  }
5027  }
5028  } else {
5029  //to be implemented for 3d
5030  }
5031  } else {
5032  //---alphabetic sort
5033  const UInt_t kUsed = 1<<18;
5034  TObject *objk=0;
5035  a[0] = 0;
5036  a[n+1] = n+1;
5037  for (i=1;i<=n;i++) {
5038  const char *label = "zzzzzzzzzzzz";
5039  for (j=1;j<=n;j++) {
5040  obj = labold->At(j-1);
5041  if (!obj) continue;
5042  if (obj->TestBit(kUsed)) continue;
5043  //use strcasecmp for case non-sensitive sort (may be an option)
5044  if (strcmp(label,obj->GetName()) < 0) continue;
5045  objk = obj;
5046  a[i] = j;
5047  label = obj->GetName();
5048  }
5049  if (objk) {
5050  objk->SetUniqueID(i);
5051  labels->Add(objk);
5052  objk->SetBit(kUsed);
5053  }
5054  }
5055  for (i=1;i<=n;i++) {
5056  obj = labels->At(i-1);
5057  if (!obj) continue;
5058  obj->ResetBit(kUsed);
5059  }
5060 
5061  if (GetDimension() == 1) {
5062  cont.resize(n+2);
5063  if (fSumw2.fN) errors.resize(n+2);
5064  for (i=1;i<=n;i++) {
5065  cont[i] = GetBinContent(a[i]);
5066  if (!errors.empty()) errors[i] = GetBinError(a[i]);
5067  }
5068  for (i=1;i<=n;i++) {
5069  SetBinContent(i,cont[i]);
5070  if (!errors.empty()) SetBinError(i,errors[i]);
5071  }
5072  } else if (GetDimension()== 2) {
5073  Int_t nx = fXaxis.GetNbins()+2;
5074  Int_t ny = fYaxis.GetNbins()+2;
5075  cont.resize(nx*ny);
5076  if (fSumw2.fN) errors.resize(nx*ny);
5077  for (i=0;i<nx;i++) {
5078  for (j=0;j<ny;j++) {
5079  cont[i+nx*j] = GetBinContent(i,j);
5080  if (!errors.empty()) errors[i+nx*j] = GetBinError(i,j);
5081  }
5082  }
5083  if (axis == GetXaxis()) {
5084  for (i=1;i<=n;i++) {
5085  for (j=0;j<ny;j++) {
5086  SetBinContent(i,j,cont[a[i]+nx*j]);
5087  if (!errors.empty()) SetBinError(i,j,errors[a[i]+nx*j]);
5088  }
5089  }
5090  } else {
5091  for (i=0;i<nx;i++) {
5092  for (j=1;j<=n;j++) {
5093  SetBinContent(i,j,cont[i+nx*a[j]]);
5094  if (!errors.empty()) SetBinError(i,j,errors[i+nx*a[j]]);
5095  }
5096  }
5097  }
5098  } else {
5099  Int_t nx = fXaxis.GetNbins()+2;
5100  Int_t ny = fYaxis.GetNbins()+2;
5101  Int_t nz = fZaxis.GetNbins()+2;
5102  cont.resize(nx*ny*nz);
5103  if (fSumw2.fN) errors.resize(nx*ny*nz);
5104  for (i=0;i<nx;i++) {
5105  for (j=0;j<ny;j++) {
5106  for (k=0;k<nz;k++) {
5107  cont[i+nx*(j+ny*k)] = GetBinContent(i,j,k);
5108  if (!errors.empty()) errors[i+nx*(j+ny*k)] = GetBinError(i,j,k);
5109  }
5110  }
5111  }
5112  if (axis == GetXaxis()) {
5113  // labels on x axis
5114  for (i=1;i<=n;i++) {
5115  for (j=0;j<ny;j++) {
5116  for (k=0;k<nz;k++) {
5117  SetBinContent(i,j,k,cont[a[i]+nx*(j+ny*k)]);
5118  if (!errors.empty()) SetBinError(i,j,k,errors[a[i]+nx*(j+ny*k)]);
5119  }
5120  }
5121  }
5122  }
5123  else if (axis == GetYaxis()) {
5124  // labels on y axis
5125  for (i=0;i<nx;i++) {
5126  for (j=1;j<=n;j++) {
5127  for (k=0;k<nz;k++) {
5128  SetBinContent(i,j,k,cont[i+nx*(a[j]+ny*k)]);
5129  if (!errors.empty()) SetBinError(i,j,k,errors[i+nx*(a[j]+ny*k)]);
5130  }
5131  }
5132  }
5133  }
5134  else {
5135  // labels on z axis
5136  for (i=0;i<nx;i++) {
5137  for (j=0;j<ny;j++) {
5138  for (k=1;k<=n;k++) {
5139  SetBinContent(i,j,k,cont[i+nx*(j+ny*a[k])]);
5140  if (!errors.empty()) SetBinError(i,j,k,errors[i+nx*(j+ny*a[k])]);
5141  }
5142  }
5143  }
5144  }
5145  }
5146  }
5147  fEntries = entries;
5148  delete labold;
5149 }
5150 
5151 ////////////////////////////////////////////////////////////////////////////////
5152 /// Test if two double are almost equal.
5153 
5154 static inline Bool_t AlmostEqual(Double_t a, Double_t b, Double_t epsilon = 0.00000001)
5155 {
5156  return TMath::Abs(a - b) < epsilon;
5157 }
5158 
5159 ////////////////////////////////////////////////////////////////////////////////
5160 /// Test if a double is almost an integer.
5161 
5162 static inline Bool_t AlmostInteger(Double_t a, Double_t epsilon = 0.00000001)
5163 {
5164  return AlmostEqual(a - TMath::Floor(a), 0, epsilon) ||
5165  AlmostEqual(a - TMath::Floor(a), 1, epsilon);
5166 }
5167 
5168 ////////////////////////////////////////////////////////////////////////////////
5169 /// Test if the binning is equidistant.
5170 
5171 static inline bool IsEquidistantBinning(const TAxis& axis)
5172 {
5173  // check if axis bin are equals
5174  if (!axis.GetXbins()->fN) return true; //
5175  // not able to check if there is only one axis entry
5176  bool isEquidistant = true;
5177  const Double_t firstBinWidth = axis.GetBinWidth(1);
5178  for (int i = 1; i < axis.GetNbins(); ++i) {
5179  const Double_t binWidth = axis.GetBinWidth(i);
5180  const bool match = TMath::AreEqualRel(firstBinWidth, binWidth, TMath::Limits<Double_t>::Epsilon());
5181  isEquidistant &= match;
5182  if (!match)
5183  break;
5184  }
5185  return isEquidistant;
5186 }
5187 
5188 ////////////////////////////////////////////////////////////////////////////////
5189 /// Same limits and bins.
5190 
5191 Bool_t TH1::SameLimitsAndNBins(const TAxis& axis1, const TAxis& axis2)
5192 {
5193  return axis1.GetNbins() == axis2.GetNbins()
5194  && axis1.GetXmin() == axis2.GetXmin()
5195  && axis1.GetXmax() == axis2.GetXmax();
5196 }
5197 
5198 ////////////////////////////////////////////////////////////////////////////////
5199 /// Finds new limits for the axis for the Merge function.
5200 /// returns false if the limits are incompatible
5201 
5202 Bool_t TH1::RecomputeAxisLimits(TAxis& destAxis, const TAxis& anAxis)
5203 {
5204  if (SameLimitsAndNBins(destAxis, anAxis))
5205  return kTRUE;
5206 
5207  if (!IsEquidistantBinning(destAxis) || !IsEquidistantBinning(anAxis))
5208  return kFALSE; // not equidistant user binning not supported
5209 
5210  Double_t width1 = destAxis.GetBinWidth(0);
5211  Double_t width2 = anAxis.GetBinWidth(0);
5212  if (width1 == 0 || width2 == 0)
5213  return kFALSE; // no binning not supported
5214 
5215  Double_t xmin = TMath::Min(destAxis.GetXmin(), anAxis.GetXmin());
5216  Double_t xmax = TMath::Max(destAxis.GetXmax(), anAxis.GetXmax());
5217  Double_t width = TMath::Max(width1, width2);
5218 
5219  // check the bin size
5220  if (!AlmostInteger(width/width1) || !AlmostInteger(width/width2))
5221  return kFALSE;
5222 
5223  // std::cout << "Find new limit using given axis " << anAxis.GetXmin() << " , " << anAxis.GetXmax() << " bin width " << width2 << std::endl;
5224  // std::cout << " and destination axis " << destAxis.GetXmin() << " , " << destAxis.GetXmax() << " bin width " << width1 << std::endl;
5225 
5226 
5227  // check the limits
5228  Double_t delta;
5229  delta = (destAxis.GetXmin() - xmin)/width1;
5230  if (!AlmostInteger(delta))
5231  xmin -= (TMath::Ceil(delta) - delta)*width1;
5232 
5233  delta = (anAxis.GetXmin() - xmin)/width2;
5234  if (!AlmostInteger(delta))
5235  xmin -= (TMath::Ceil(delta) - delta)*width2;
5236 
5237 
5238  delta = (destAxis.GetXmin() - xmin)/width1;
5239  if (!AlmostInteger(delta))
5240  return kFALSE;
5241 
5242 
5243  delta = (xmax - destAxis.GetXmax())/width1;
5244  if (!AlmostInteger(delta))
5245  xmax += (TMath::Ceil(delta) - delta)*width1;
5246 
5247 
5248  delta = (xmax - anAxis.GetXmax())/width2;
5249  if (!AlmostInteger(delta))
5250  xmax += (TMath::Ceil(delta) - delta)*width2;
5251 
5252 
5253  delta = (xmax - destAxis.GetXmax())/width1;
5254  if (!AlmostInteger(delta))
5255  return kFALSE;
5256 #ifdef DEBUG
5257  if (!AlmostInteger((xmax - xmin) / width)) { // unnecessary check
5258  printf("TH1::RecomputeAxisLimits - Impossible\n");
5259  return kFALSE;
5260  }
5261 #endif
5262 
5263 
5264  destAxis.Set(TMath::Nint((xmax - xmin)/width), xmin, xmax);
5265 
5266  //std::cout << "New re-computed axis : [ " << xmin << " , " << xmax << " ] width = " << width << " nbins " << destAxis.GetNbins() << std::endl;
5267 
5268  return kTRUE;
5269 }
5270 
5271 ////////////////////////////////////////////////////////////////////////////////
5272 /// Add all histograms in the collection to this histogram.
5273 /// This function computes the min/max for the x axis,
5274 /// compute a new number of bins, if necessary,
5275 /// add bin contents, errors and statistics.
5276 /// If all histograms have bin labels, bins with identical labels
5277 /// will be merged, no matter what their order is.
5278 /// If overflows are present and limits are different the function will fail.
5279 /// The function returns the total number of entries in the result histogram
5280 /// if the merge is successful, -1 otherwise.
5281 ///
5282 /// IMPORTANT remark. The axis x may have different number
5283 /// of bins and different limits, BUT the largest bin width must be
5284 /// a multiple of the smallest bin width and the upper limit must also
5285 /// be a multiple of the bin width.
5286 /// Example:
5287 ///
5288 /// ~~~ {.cpp}
5289 /// void atest() {
5290 /// TH1F *h1 = new TH1F("h1","h1",110,-110,0);
5291 /// TH1F *h2 = new TH1F("h2","h2",220,0,110);
5292 /// TH1F *h3 = new TH1F("h3","h3",330,-55,55);
5293 /// TRandom r;
5294 /// for (Int_t i=0;i<10000;i++) {
5295 /// h1->Fill(r.Gaus(-55,10));
5296 /// h2->Fill(r.Gaus(55,10));
5297 /// h3->Fill(r.Gaus(0,10));
5298 /// }
5299 ///
5300 /// TList *list = new TList;
5301 /// list->Add(h1);
5302 /// list->Add(h2);
5303 /// list->Add(h3);
5304 /// TH1F *h = (TH1F*)h1->Clone("h");
5305 /// h->Reset();
5306 /// h->Merge(list);
5307 /// h->Draw();
5308 /// }
5309 /// ~~~
5310 
5312 {
5313  if (!li) return 0;
5314  if (li->IsEmpty()) return (Long64_t) GetEntries();
5315 
5316  // use TH1Merger class
5317  TH1Merger merger(*this,*li);
5318  Bool_t ret = merger();
5319 
5320  return (ret) ? GetEntries() : -1;
5321 }
5322 
5323 
5324 ////////////////////////////////////////////////////////////////////////////////
5325 /// Performs the operation: this = this*c1*f1
5326 /// if errors are defined (see TH1::Sumw2), errors are also recalculated.
5327 ///
5328 /// Only bins inside the function range are recomputed.
5329 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
5330 /// you should call Sumw2 before making this operation.
5331 /// This is particularly important if you fit the histogram after TH1::Multiply
5332 ///
5333 /// The function return kFALSE if the Multiply operation failed
5334 
5336 {
5337  if (!f1) {
5338  Error("Add","Attempt to multiply by a non-existing function");
5339  return kFALSE;
5340  }
5341 
5342  // delete buffer if it is there since it will become invalid
5343  if (fBuffer) BufferEmpty(1);
5344 
5345  Int_t nx = GetNbinsX() + 2; // normal bins + uf / of (cells)
5346  Int_t ny = GetNbinsY() + 2;
5347  Int_t nz = GetNbinsZ() + 2;
5348  if (fDimension < 2) ny = 1;
5349  if (fDimension < 3) nz = 1;
5350 
5351  // reset min-maximum
5352  SetMinimum();
5353  SetMaximum();
5354 
5355  // - Loop on bins (including underflows/overflows)
5356  Double_t xx[3];
5357  Double_t *params = 0;
5358  f1->InitArgs(xx,params);
5359 
5360  for (Int_t binz = 0; binz < nz; ++binz) {
5361  xx[2] = fZaxis.GetBinCenter(binz);
5362  for (Int_t biny = 0; biny < ny; ++biny) {
5363  xx[1] = fYaxis.GetBinCenter(biny);
5364  for (Int_t binx = 0; binx < nx; ++binx) {
5365  xx[0] = fXaxis.GetBinCenter(binx);
5366  if (!f1->IsInside(xx)) continue;
5368  Int_t bin = binx + nx * (biny + ny *binz);
5369  Double_t cu = c1*f1->EvalPar(xx);
5370  if (TF1::RejectedPoint()) continue;
5371  UpdateBinContent(bin, RetrieveBinContent(bin) * cu);
5372  if (fSumw2.fN) {
5373  fSumw2.fArray[bin] = cu * cu * GetBinErrorSqUnchecked(bin);
5374  }
5375  }
5376  }
5377  }
5378  ResetStats();
5379  return kTRUE;
5380 }
5381 
5382 ////////////////////////////////////////////////////////////////////////////////
5383 /// Multiply this histogram by h1.
5384 ///
5385 /// `this = this*h1`
5386 ///
5387 /// If errors of this are available (TH1::Sumw2), errors are recalculated.
5388 /// Note that if h1 has Sumw2 set, Sumw2 is automatically called for this
5389 /// if not already set.
5390 ///
5391 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
5392 /// you should call Sumw2 before making this operation.
5393 /// This is particularly important if you fit the histogram after TH1::Multiply
5394 ///
5395 /// The function return kFALSE if the Multiply operation failed
5396 
5397 Bool_t TH1::Multiply(const TH1 *h1)
5398 {
5399  if (!h1) {
5400  Error("Multiply","Attempt to multiply by a non-existing histogram");
5401  return kFALSE;
5402  }
5403 
5404  // delete buffer if it is there since it will become invalid
5405  if (fBuffer) BufferEmpty(1);
5406 
5407  try {
5408  CheckConsistency(this,h1);
5409  } catch(DifferentNumberOfBins&) {
5410  Error("Multiply","Attempt to multiply histograms with different number of bins");
5411  return kFALSE;
5412  } catch(DifferentAxisLimits&) {
5413  Warning("Multiply","Attempt to multiply histograms with different axis limits");
5414  } catch(DifferentBinLimits&) {
5415  Warning("Multiply","Attempt to multiply histograms with different bin limits");
5416  } catch(DifferentLabels&) {
5417  Warning("Multiply","Attempt to multiply histograms with different labels");
5418  }
5419 
5420  // Create Sumw2 if h1 has Sumw2 set
5421  if (fSumw2.fN == 0 && h1->GetSumw2N() != 0) Sumw2();
5422 
5423  // - Reset min- maximum
5424  SetMinimum();
5425  SetMaximum();
5426 
5427  // - Loop on bins (including underflows/overflows)
5428  for (Int_t i = 0; i < fNcells; ++i) {
5429  Double_t c0 = RetrieveBinContent(i);
5430  Double_t c1 = h1->RetrieveBinContent(i);
5431  UpdateBinContent(i, c0 * c1);
5432  if (fSumw2.fN) {
5433  fSumw2.fArray[i] = GetBinErrorSqUnchecked(i) * c1 * c1 + h1->GetBinErrorSqUnchecked(i) * c0 * c0;
5434  }
5435  }
5436  ResetStats();
5437  return kTRUE;
5438 }
5439 
5440 ////////////////////////////////////////////////////////////////////////////////
5441 /// Replace contents of this histogram by multiplication of h1 by h2.
5442 ///
5443 /// `this = (c1*h1)*(c2*h2)`
5444 ///
5445 /// If errors of this are available (TH1::Sumw2), errors are recalculated.
5446 /// Note that if h1 or h2 have Sumw2 set, Sumw2 is automatically called for this
5447 /// if not already set.
5448 ///
5449 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
5450 /// you should call Sumw2 before making this operation.
5451 /// This is particularly important if you fit the histogram after TH1::Multiply
5452 ///
5453 /// The function return kFALSE if the Multiply operation failed
5454 
5455 Bool_t TH1::Multiply(const TH1 *h1, const TH1 *h2, Double_t c1, Double_t c2, Option_t *option)
5456 {
5457  TString opt = option;
5458  opt.ToLower();
5459  // Bool_t binomial = kFALSE;
5460  // if (opt.Contains("b")) binomial = kTRUE;
5461  if (!h1 || !h2) {
5462  Error("Multiply","Attempt to multiply by a non-existing histogram");
5463  return kFALSE;
5464  }
5465 
5466  // delete buffer if it is there since it will become invalid
5467  if (fBuffer) BufferEmpty(1);
5468 
5469  try {
5470  CheckConsistency(h1,h2);
5471  CheckConsistency(this,h1);
5472  } catch(DifferentNumberOfBins&) {
5473  Error("Multiply","Attempt to multiply histograms with different number of bins");
5474  return kFALSE;
5475  } catch(DifferentAxisLimits&) {
5476  Warning("Multiply","Attempt to multiply histograms with different axis limits");
5477  } catch(DifferentBinLimits&) {
5478  Warning("Multiply","Attempt to multiply histograms with different bin limits");
5479  } catch(DifferentLabels&) {
5480  Warning("Multiply","Attempt to multiply histograms with different labels");
5481  }
5482 
5483  // Create Sumw2 if h1 or h2 have Sumw2 set
5484  if (fSumw2.fN == 0 && (h1->GetSumw2N() != 0 || h2->GetSumw2N() != 0)) Sumw2();
5485 
5486  // - Reset min - maximum
5487  SetMinimum();
5488  SetMaximum();
5489 
5490  // - Loop on bins (including underflows/overflows)
5491  Double_t c1sq = c1 * c1; Double_t c2sq = c2 * c2;
5492  for (Int_t i = 0; i < fNcells; ++i) {
5493  Double_t b1 = h1->RetrieveBinContent(i);
5494  Double_t b2 = h2->RetrieveBinContent(i);
5495  UpdateBinContent(i, c1 * b1 * c2 * b2);
5496  if (fSumw2.fN) {
5497  fSumw2.fArray[i] = c1sq * c2sq * (h1->GetBinErrorSqUnchecked(i) * b2 * b2 + h2->GetBinErrorSqUnchecked(i) * b1 * b1);
5498  }
5499  }
5500  ResetStats();
5501  return kTRUE;
5502 }
5503 
5504 ////////////////////////////////////////////////////////////////////////////////
5505 /// Control routine to paint any kind of histograms.
5506 ///
5507 /// This function is automatically called by TCanvas::Update.
5508 /// (see TH1::Draw for the list of options)
5509 
5510 void TH1::Paint(Option_t *option)
5511 {
5512  GetPainter(option);
5513 
5514  if (fPainter) {
5515  if (strlen(option) > 0) fPainter->Paint(option);
5516  else fPainter->Paint(fOption.Data());
5517  }
5518 }
5519 
5520 ////////////////////////////////////////////////////////////////////////////////
5521 /// Rebin this histogram
5522 ///
5523 /// #### case 1 xbins=0
5524 ///
5525 /// If newname is blank (default), the current histogram is modified and
5526 /// a pointer to it is returned.
5527 ///
5528 /// If newname is not blank, the current histogram is not modified, and a
5529 /// new histogram is returned which is a Clone of the current histogram
5530 /// with its name set to newname.
5531 ///
5532 /// The parameter ngroup indicates how many bins of this have to be merged
5533 /// into one bin of the result.
5534 ///
5535 /// If the original histogram has errors stored (via Sumw2), the resulting
5536 /// histograms has new errors correctly calculated.
5537 ///
5538 /// examples: if h1 is an existing TH1F histogram with 100 bins
5539 ///
5540 /// ~~~ {.cpp}
5541 /// h1->Rebin(); //merges two bins in one in h1: previous contents of h1 are lost
5542 /// h1->Rebin(5); //merges five bins in one in h1
5543 /// TH1F *hnew = h1->Rebin(5,"hnew"); // creates a new histogram hnew
5544 /// // merging 5 bins of h1 in one bin
5545 /// ~~~
5546 ///
5547 /// NOTE: If ngroup is not an exact divider of the number of bins,
5548 /// the top limit of the rebinned histogram is reduced
5549 /// to the upper edge of the last bin that can make a complete
5550 /// group. The remaining bins are added to the overflow bin.
5551 /// Statistics will be recomputed from the new bin contents.
5552 ///
5553 /// #### case 2 xbins!=0
5554 ///
5555 /// A new histogram is created (you should specify newname).
5556 /// The parameter ngroup is the number of variable size bins in the created histogram.
5557 /// The array xbins must contain ngroup+1 elements that represent the low-edges
5558 /// of the bins.
5559 /// If the original histogram has errors stored (via Sumw2), the resulting
5560 /// histograms has new errors correctly calculated.
5561 ///
5562 /// NOTE: The bin edges specified in xbins should correspond to bin edges
5563 /// in the original histogram. If a bin edge in the new histogram is
5564 /// in the middle of a bin in the original histogram, all entries in
5565 /// the split bin in the original histogram will be transfered to the
5566 /// lower of the two possible bins in the new histogram. This is
5567 /// probably not what you want.
5568 ///
5569 /// examples: if h1 is an existing TH1F histogram with 100 bins
5570 ///
5571 /// ~~~ {.cpp}
5572 /// Double_t xbins[25] = {...} array of low-edges (xbins[25] is the upper edge of last bin
5573 /// h1->Rebin(24,"hnew",xbins); //creates a new variable bin size histogram hnew
5574 /// ~~~
5575 
5576 TH1 *TH1::Rebin(Int_t ngroup, const char*newname, const Double_t *xbins)
5577 {
5578  Int_t nbins = fXaxis.GetNbins();
5579  Double_t xmin = fXaxis.GetXmin();
5580  Double_t xmax = fXaxis.GetXmax();
5581  if ((ngroup <= 0) || (ngroup > nbins)) {
5582  Error("Rebin", "Illegal value of ngroup=%d",ngroup);
5583  return 0;
5584  }
5585 
5586  if (fDimension > 1 || InheritsFrom(TProfile::Class())) {
5587  Error("Rebin", "Operation valid on 1-D histograms only");
5588  return 0;
5589  }
5590  if (!newname && xbins) {
5591  Error("Rebin","if xbins is specified, newname must be given");
5592  return 0;
5593  }
5594 
5595  Int_t newbins = nbins/ngroup;
5596  if (!xbins) {
5597  Int_t nbg = nbins/ngroup;
5598  if (nbg*ngroup != nbins) {
5599  Warning("Rebin", "ngroup=%d is not an exact divider of nbins=%d.",ngroup,nbins);
5600  }
5601  }
5602  else {
5603  // in the case that xbins is given (rebinning in variable bins), ngroup is
5604  // the new number of bins and number of grouped bins is not constant.
5605  // when looping for setting the contents for the new histogram we
5606  // need to loop on all bins of original histogram. Then set ngroup=nbins
5607  newbins = ngroup;
5608  ngroup = nbins;
5609  }
5610 
5611  // Save old bin contents into a new array
5612  Double_t entries = fEntries;
5613  Double_t *oldBins = new Double_t[nbins+2];
5614  Int_t bin, i;
5615  for (bin=0;bin<nbins+2;bin++) oldBins[bin] = RetrieveBinContent(bin);
5616  Double_t *oldErrors = 0;
5617  if (fSumw2.fN != 0) {
5618  oldErrors = new Double_t[nbins+2];
5619  for (bin=0;bin<nbins+2;bin++) oldErrors[bin] = GetBinError(bin);
5620  }
5621  // rebin will not include underflow/overflow if new axis range is larger than old axis range
5622  if (xbins) {
5623  if (xbins[0] < fXaxis.GetXmin() && oldBins[0] != 0 )
5624  Warning("Rebin","underflow entries will not be used when rebinning");
5625  if (xbins[newbins] > fXaxis.GetXmax() && oldBins[nbins+1] != 0 )
5626  Warning("Rebin","overflow entries will not be used when rebinning");
5627  }
5628 
5629 
5630  // create a clone of the old histogram if newname is specified
5631  TH1 *hnew = this;
5632  if ((newname && strlen(newname) > 0) || xbins) {
5633  hnew = (TH1*)Clone(newname);
5634  }
5635 
5636  //reset can extend bit to avoid an axis extension in SetBinContent
5637  UInt_t oldExtendBitMask = hnew->SetCanExtend(kNoAxis);
5638 
5639  // save original statistics
5640  Double_t stat[kNstat];
5641  GetStats(stat);
5642  bool resetStat = false;
5643  // change axis specs and rebuild bin contents array::RebinAx
5644  if(!xbins && (newbins*ngroup != nbins)) {
5645  xmax = fXaxis.GetBinUpEdge(newbins*ngroup);
5646  resetStat = true; //stats must be reset because top bins will be moved to overflow bin
5647  }
5648  // save the TAttAxis members (reset by SetBins)
5649  Int_t nDivisions = fXaxis.GetNdivisions();
5650  Color_t axisColor = fXaxis.GetAxisColor();
5651  Color_t labelColor = fXaxis.GetLabelColor();
5652  Style_t labelFont = fXaxis.GetLabelFont();
5653  Float_t labelOffset = fXaxis.GetLabelOffset();
5654  Float_t labelSize = fXaxis.GetLabelSize();
5655  Float_t tickLength = fXaxis.GetTickLength();
5656  Float_t titleOffset = fXaxis.GetTitleOffset();
5657  Float_t titleSize = fXaxis.GetTitleSize();
5658  Color_t titleColor = fXaxis.GetTitleColor();
5659  Style_t titleFont = fXaxis.GetTitleFont();
5660 
5661  if(!xbins && (fXaxis.GetXbins()->GetSize() > 0)){ // variable bin sizes
5662  Double_t *bins = new Double_t[newbins+1];
5663  for(i = 0; i <= newbins; ++i) bins[i] = fXaxis.GetBinLowEdge(1+i*ngroup);
5664  hnew->SetBins(newbins,bins); //this also changes errors array (if any)
5665  delete [] bins;
5666  } else if (xbins) {
5667  hnew->SetBins(newbins,xbins);
5668  } else {
5669  hnew->SetBins(newbins,xmin,xmax);
5670  }
5671 
5672  // Restore axis attributes
5673  fXaxis.SetNdivisions(nDivisions);
5674  fXaxis.SetAxisColor(axisColor);
5675  fXaxis.SetLabelColor(labelColor);
5676  fXaxis.SetLabelFont(labelFont);
5677  fXaxis.SetLabelOffset(labelOffset);
5678  fXaxis.SetLabelSize(labelSize);
5679  fXaxis.SetTickLength(tickLength);
5680  fXaxis.SetTitleOffset(titleOffset);
5681  fXaxis.SetTitleSize(titleSize);
5682  fXaxis.SetTitleColor(titleColor);
5683  fXaxis.SetTitleFont(titleFont);
5684 
5685  // copy merged bin contents (ignore under/overflows)
5686  // Start merging only once the new lowest edge is reached
5687  Int_t startbin = 1;
5688  const Double_t newxmin = hnew->GetXaxis()->GetBinLowEdge(1);
5689  while( fXaxis.GetBinCenter(startbin) < newxmin && startbin <= nbins ) {
5690  startbin++;
5691  }
5692  Int_t oldbin = startbin;
5693  Double_t binContent, binError;
5694  for (bin = 1;bin<=newbins;bin++) {
5695  binContent = 0;
5696  binError = 0;
5697  Int_t imax = ngroup;
5698  Double_t xbinmax = hnew->GetXaxis()->GetBinUpEdge(bin);
5699  for (i=0;i<ngroup;i++) {
5700  if( (oldbin+i > nbins) ||
5701  ( hnew != this && (fXaxis.GetBinCenter(oldbin+i) > xbinmax)) ) {
5702  imax = i;
5703  break;
5704  }
5705  binContent += oldBins[oldbin+i];
5706  if (oldErrors) binError += oldErrors[oldbin+i]*oldErrors[oldbin+i];
5707  }
5708  hnew->SetBinContent(bin,binContent);
5709  if (oldErrors) hnew->SetBinError(bin,TMath::Sqrt(binError));
5710  oldbin += imax;
5711  }
5712 
5713  // sum underflow and overflow contents until startbin
5714  binContent = 0;
5715  binError = 0;
5716  for (i = 0; i < startbin; ++i) {
5717  binContent += oldBins[i];
5718  if (oldErrors) binError += oldErrors[i]*oldErrors[i];
5719  }
5720  hnew->SetBinContent(0,binContent);
5721  if (oldErrors) hnew->SetBinError(0,TMath::Sqrt(binError));
5722  // sum overflow
5723  binContent = 0;
5724  binError = 0;
5725  for (i = oldbin; i <= nbins+1; ++i) {
5726  binContent += oldBins[i];
5727  if (oldErrors) binError += oldErrors[i]*oldErrors[i];
5728  }
5729  hnew->SetBinContent(newbins+1,binContent);
5730  if (oldErrors) hnew->SetBinError(newbins+1,TMath::Sqrt(binError));
5731 
5732  hnew->SetCanExtend(oldExtendBitMask); // restore previous state
5733 
5734  // restore statistics and entries modified by SetBinContent
5735  hnew->SetEntries(entries);
5736  if (!resetStat) hnew->PutStats(stat);
5737  delete [] oldBins;
5738  if (oldErrors) delete [] oldErrors;
5739  return hnew;
5740 }
5741 
5742 ////////////////////////////////////////////////////////////////////////////////
5743 /// finds new limits for the axis so that *point* is within the range and
5744 /// the limits are compatible with the previous ones (see TH1::Merge).
5745 /// new limits are put into *newMin* and *newMax* variables.
5746 /// axis - axis whose limits are to be recomputed
5747 /// point - point that should fit within the new axis limits
5748 /// newMin - new minimum will be stored here
5749 /// newMax - new maximum will be stored here.
5750 /// false if failed (e.g. if the initial axis limits are wrong
5751 /// or the new range is more than \f$ 2^{64} \f$ times the old one).
5752 
5753 Bool_t TH1::FindNewAxisLimits(const TAxis* axis, const Double_t point, Double_t& newMin, Double_t &newMax)
5754 {
5755  Double_t xmin = axis->GetXmin();
5756  Double_t xmax = axis->GetXmax();
5757  if (xmin >= xmax) return kFALSE;
5758  Double_t range = xmax-xmin;
5759  Double_t binsize = range / axis->GetNbins();
5760 
5761  //recompute new axis limits by doubling the current range
5762  Int_t ntimes = 0;
5763  while (point < xmin) {
5764  if (ntimes++ > 64)
5765  return kFALSE;
5766  xmin = xmin - range;
5767  range *= 2;
5768  binsize *= 2;
5769  // // make sure that the merging will be correct
5770  // if ( xmin / binsize - TMath::Floor(xmin / binsize) >= 0.5) {
5771  // xmin += 0.5 * binsize;
5772  // xmax += 0.5 * binsize; // won't work with a histogram with only one bin, but I don't care
5773  // }
5774  }
5775  while (point >= xmax) {
5776  if (ntimes++ > 64)
5777  return kFALSE;
5778  xmax = xmax + range;
5779  range *= 2;
5780  binsize *= 2;
5781  // // make sure that the merging will be correct
5782  // if ( xmin / binsize - TMath::Floor(xmin / binsize) >= 0.5) {
5783  // xmin -= 0.5 * binsize;
5784  // xmax -= 0.5 * binsize; // won't work with a histogram with only one bin, but I don't care
5785  // }
5786  }
5787  newMin = xmin;
5788  newMax = xmax;
5789  // Info("FindNewAxisLimits", "OldAxis: (%lf, %lf), new: (%lf, %lf), point: %lf",
5790  // axis->GetXmin(), axis->GetXmax(), xmin, xmax, point);
5791 
5792  return kTRUE;
5793 }
5794 
5795 ////////////////////////////////////////////////////////////////////////////////
5796 /// Histogram is resized along axis such that x is in the axis range.
5797 /// The new axis limits are recomputed by doubling iteratively
5798 /// the current axis range until the specified value x is within the limits.
5799 /// The algorithm makes a copy of the histogram, then loops on all bins
5800 /// of the old histogram to fill the extended histogram.
5801 /// Takes into account errors (Sumw2) if any.
5802 /// The algorithm works for 1-d, 2-D and 3-D histograms.
5803 /// The axis must be extendable before invoking this function.
5804 /// Ex:
5805 ///
5806 /// ~~~ {.cpp}
5807 /// h->GetXaxis()->SetCanExtend(kTRUE);
5808 /// ~~~
5809 
5810 void TH1::ExtendAxis(Double_t x, TAxis *axis)
5811 {
5812  if (!axis->CanExtend()) return;
5813  if (TMath::IsNaN(x)) { // x may be a NaN
5815  return;
5816  }
5817 
5818  if (axis->GetXmin() >= axis->GetXmax()) return;
5819  if (axis->GetNbins() <= 0) return;
5820 
5821  Double_t xmin, xmax;
5822  if (!FindNewAxisLimits(axis, x, xmin, xmax))
5823  return;
5824 
5825  //save a copy of this histogram
5826  TH1 *hold = (TH1*)IsA()->New();
5827  hold->SetDirectory(0);
5828  Copy(*hold);
5829  //set new axis limits
5830  axis->SetLimits(xmin,xmax);
5831 
5832  Int_t nbinsx = fXaxis.GetNbins();
5833  Int_t nbinsy = fYaxis.GetNbins();
5834  Int_t nbinsz = fZaxis.GetNbins();
5835 
5836  //now loop on all bins and refill
5837  Double_t bx,by,bz;
5838  Int_t errors = GetSumw2N();
5839  Int_t ix,iy,iz,ibin,binx,biny,binz,bin;
5840  Reset("ICE"); //reset only Integral, contents and Errors
5841  for (binz=1;binz<=nbinsz;binz++) {
5842  bz = hold->GetZaxis()->GetBinCenter(binz);
5843  iz = fZaxis.FindFixBin(bz);
5844  for (biny=1;biny<=nbinsy;biny++) {
5845  by = hold->GetYaxis()->GetBinCenter(biny);
5846  iy = fYaxis.FindFixBin(by);
5847  for (binx=1;binx<=nbinsx;binx++) {
5848  bx = hold->GetXaxis()->GetBinCenter(binx);
5849  ix = fXaxis.FindFixBin(bx);
5850  bin = hold->GetBin(binx,biny,binz);
5851  ibin= GetBin(ix,iy,iz);
5852  AddBinContent(ibin, hold->RetrieveBinContent(bin));
5853  if (errors) {
5854  fSumw2.fArray[ibin] += hold->GetBinErrorSqUnchecked(bin);
5855  }
5856  }
5857  }
5858  }
5859  delete hold;
5860 }
5861 
5862 ////////////////////////////////////////////////////////////////////////////////
5863 /// Recursively remove object from the list of functions
5864 
5865 void TH1::RecursiveRemove(TObject *obj)
5866 {
5867  if (fFunctions) {
5869  }
5870 }
5871 
5872 ////////////////////////////////////////////////////////////////////////////////
5873 /// Multiply this histogram by a constant c1.
5874 ///
5875 /// `this = c1*this`
5876 ///
5877 /// Note that both contents and errors(if any) are scaled.
5878 /// This function uses the services of TH1::Add
5879 ///
5880 /// IMPORTANT NOTE: Sumw2() is called automatically when scaling
5881 /// If you are not interested in the histogram statistics you can call
5882 /// Sumw2(off) or use the option "nosw2"
5883 ///
5884 /// One can scale an histogram such that the bins integral is equal to
5885 /// the normalization parameter via TH1::Scale(Double_t norm), where norm
5886 /// is the desired normalization divided by the integral of the histogram.
5887 ///
5888 /// If option contains "width" the bin contents and errors are divided
5889 /// by the bin width.
5890 
5891 void TH1::Scale(Double_t c1, Option_t *option)
5892 {
5894  TString opt = option; opt.ToLower();
5895  // store bin errors when scaling since cannot anymore be computed as sqrt(N)
5896  if (!opt.Contains("nosw2") && GetSumw2N() == 0) Sumw2();
5897  if (opt.Contains("width")) Add(this, this, c1, -1);
5898  else {
5899  if (fBuffer) BufferEmpty(1);
5900  for(Int_t i = 0; i < fNcells; ++i) UpdateBinContent(i, c1 * RetrieveBinContent(i));
5901  if (fSumw2.fN) for(Int_t i = 0; i < fNcells; ++i) fSumw2.fArray[i] *= (c1 * c1); // update errors
5902  SetMinimum(); SetMaximum(); // minimum and maximum value will be recalculated the next time
5903  }
5904 
5905  // if contours set, must also scale contours
5906  Int_t ncontours = GetContour();
5907  if (ncontours == 0) return;
5908  Double_t* levels = fContour.GetArray();
5909  for (Int_t i = 0; i < ncontours; ++i) levels[i] *= c1;
5910 }
5911 
5912 ////////////////////////////////////////////////////////////////////////////////
5913 /// Returns true if all axes are extendable.
5914 
5916 {
5917  Bool_t canExtend = fXaxis.CanExtend();
5918  if (GetDimension() > 1) canExtend &= fYaxis.CanExtend();
5919  if (GetDimension() > 2) canExtend &= fZaxis.CanExtend();
5920 
5921  return canExtend;
5922 }
5923 
5924 ////////////////////////////////////////////////////////////////////////////////
5925 /// Make the histogram axes extendable / not extendable according to the bit mask
5926 /// returns the previous bit mask specifying which axes are extendable
5927 
5928 UInt_t TH1::SetCanExtend(UInt_t extendBitMask)
5929 {
5930  UInt_t oldExtendBitMask = kNoAxis;
5931 
5932  if (fXaxis.CanExtend()) oldExtendBitMask |= kXaxis;
5933  if (extendBitMask & kXaxis) fXaxis.SetCanExtend(kTRUE);
5934  else fXaxis.SetCanExtend(kFALSE);
5935 
5936  if (GetDimension() > 1) {
5937  if (fYaxis.CanExtend()) oldExtendBitMask |= kYaxis;
5938  if (extendBitMask & kYaxis) fYaxis.SetCanExtend(kTRUE);
5939  else fYaxis.SetCanExtend(kFALSE);
5940  }
5941 
5942  if (GetDimension() > 2) {
5943  if (fZaxis.CanExtend()) oldExtendBitMask |= kZaxis;
5944  if (extendBitMask & kZaxis) fZaxis.SetCanExtend(kTRUE);
5945  else fZaxis.SetCanExtend(kFALSE);
5946  }
5947 
5948  return oldExtendBitMask;
5949 }
5950 
5951 ////////////////////////////////////////////////////////////////////////////////
5952 /// Static function to set the default buffer size for automatic histograms.
5953 /// When an histogram is created with one of its axis lower limit greater
5954 /// or equal to its upper limit, the function SetBuffer is automatically
5955 /// called with the default buffer size.
5956 
5957 void TH1::SetDefaultBufferSize(Int_t buffersize)
5958 {
5959  fgBufferSize = buffersize > 0 ? buffersize : 0;
5960 }
5961 
5962 ////////////////////////////////////////////////////////////////////////////////
5963 /// When this static function is called with `sumw2=kTRUE`, all new
5964 /// histograms will automatically activate the storage
5965 /// of the sum of squares of errors, ie TH1::Sumw2 is automatically called.
5966 
5967 void TH1::SetDefaultSumw2(Bool_t sumw2)
5968 {
5970 }
5971 
5972 ////////////////////////////////////////////////////////////////////////////////
5973 /// Change (i.e. set) the title
5974 ///
5975 /// if title is in the form `stringt;stringx;stringy;stringz`
5976 /// the histogram title is set to `stringt`, the x axis title to `stringx`,
5977 /// the y axis title to `stringy`, and the z axis title to `stringz`.
5978 ///
5979 /// To insert the character `;` in one of the titles, one should use `#;`
5980 /// or `#semicolon`.
5981 
5982 void TH1::SetTitle(const char *title)
5983 {
5984  fTitle = title;
5985  fTitle.ReplaceAll("#;",2,"#semicolon",10);
5986 
5987  // Decode fTitle. It may contain X, Y and Z titles
5988  TString str1 = fTitle, str2;
5989  Int_t isc = str1.Index(";");
5990  Int_t lns = str1.Length();
5991 
5992  if (isc >=0 ) {
5993  fTitle = str1(0,isc);
5994  str1 = str1(isc+1, lns);
5995  isc = str1.Index(";");
5996  if (isc >=0 ) {
5997  str2 = str1(0,isc);
5998  str2.ReplaceAll("#semicolon",10,";",1);
5999  fXaxis.SetTitle(str2.Data());
6000  lns = str1.Length();
6001  str1 = str1(isc+1, lns);
6002  isc = str1.Index(";");
6003  if (isc >=0 ) {
6004  str2 = str1(0,isc);
6005  str2.ReplaceAll("#semicolon",10,";",1);
6006  fYaxis.SetTitle(str2.Data());
6007  lns = str1.Length();
6008  str1 = str1(isc+1, lns);
6009  str1.ReplaceAll("#semicolon",10,";",1);
6010  fZaxis.SetTitle(str1.Data());
6011  } else {
6012  str1.ReplaceAll("#semicolon",10,";",1);
6013  fYaxis.SetTitle(str1.Data());
6014  }
6015  } else {
6016  str1.ReplaceAll("#semicolon",10,";",1);
6017  fXaxis.SetTitle(str1.Data());
6018  }
6019  }
6020 
6021  fTitle.ReplaceAll("#semicolon",10,";",1);
6022 
6023  if (gPad && TestBit(kMustCleanup)) gPad->Modified();
6024 }
6025 
6026 ////////////////////////////////////////////////////////////////////////////////
6027 /// Smooth array xx, translation of Hbook routine hsmoof.F
6028 /// based on algorithm 353QH twice presented by J. Friedman
6029 /// in Proc.of the 1974 CERN School of Computing, Norway, 11-24 August, 1974.
6030 
6031 void TH1::SmoothArray(Int_t nn, Double_t *xx, Int_t ntimes)
6032 {
6033  if (nn < 3 ) {
6034  ::Error("SmoothArray","Need at least 3 points for smoothing: n = %d",nn);
6035  return;
6036  }
6037 
6038  Int_t ii;
6039  Double_t hh[6] = {0,0,0,0,0,0};
6040 
6041  std::vector<double> yy(nn);
6042  std::vector<double> zz(nn);
6043  std::vector<double> rr(nn);
6044 
6045  for (Int_t pass=0;pass<ntimes;pass++) {
6046  // first copy original data into temp array
6047  std::copy(xx, xx+nn, zz.begin() );
6048 
6049  for (int noent = 0; noent < 2; ++noent) { // run algorithm two times
6050 
6051  // do 353 i.e. running median 3, 5, and 3 in a single loop
6052  for (int kk = 0; kk < 3; kk++) {
6053  std::copy(zz.begin(), zz.end(), yy.begin());
6054  int medianType = (kk != 1) ? 3 : 5;
6055  int ifirst = (kk != 1 ) ? 1 : 2;
6056  int ilast = (kk != 1 ) ? nn-1 : nn -2;
6057  //nn2 = nn - ik - 1;
6058  // do all elements beside the first and last point for median 3
6059  // and first two and last 2 for median 5
6060  for ( ii = ifirst; ii < ilast; ii++) {
6061  assert(ii - ifirst >= 0);
6062  for (int jj = 0; jj < medianType; jj++) {
6063  hh[jj] = yy[ii - ifirst + jj ];
6064  }
6065  zz[ii] = TMath::Median(medianType, hh);
6066  }
6067 
6068  if (kk == 0) { // first median 3
6069  // first point
6070  hh[0] = zz[1];
6071  hh[1] = zz[0];
6072  hh[2] = 3*zz[1] - 2*zz[2];
6073  zz[0] = TMath::Median(3, hh);
6074  // last point
6075  hh[0] = zz[nn - 2];
6076  hh[1] = zz[nn - 1];
6077  hh[2] = 3*zz[nn - 2] - 2*zz[nn - 3];
6078  zz[nn - 1] = TMath::Median(3, hh);
6079  }
6080 
6081  if (kk == 1) { // median 5
6082  for (ii = 0; ii < 3; ii++) {
6083  hh[ii] = yy[ii];
6084  }
6085  zz[1] = TMath::Median(3, hh);
6086  // last two points
6087  for (ii = 0; ii < 3; ii++) {
6088  hh[ii] = yy[nn - 3 + ii];
6089  }
6090  zz[nn - 2] = TMath::Median(3, hh);
6091  }
6092 
6093  }
6094 
6095  std::copy ( zz.begin(), zz.end(), yy.begin() );
6096 
6097  // quadratic interpolation for flat segments
6098  for (ii = 2; ii < (nn - 2); ii++) {
6099  if (zz[ii - 1] != zz[ii]) continue;
6100  if (zz[ii] != zz[ii + 1]) continue;
6101  hh[0] = zz[ii - 2] - zz[ii];
6102  hh[1] = zz[ii + 2] - zz[ii];
6103  if (hh[0] * hh[1] <= 0) continue;
6104  int jk = 1;
6105  if ( TMath::Abs(hh[1]) > TMath::Abs(hh[0]) ) jk = -1;
6106  yy[ii] = -0.5*zz[ii - 2*jk] + zz[ii]/0.75 + zz[ii + 2*jk] /6.;
6107  yy[ii + jk] = 0.5*(zz[ii + 2*jk] - zz[ii - 2*jk]) + zz[ii];
6108  }
6109 
6110  // running means
6111  //std::copy(zz.begin(), zz.end(), yy.begin());
6112  for (ii = 1; ii < nn - 1; ii++) {
6113  zz[ii] = 0.25*yy[ii - 1] + 0.5*yy[ii] + 0.25*yy[ii + 1];
6114  }
6115  zz[0] = yy[0];
6116  zz[nn - 1] = yy[nn - 1];
6117 
6118  if (noent == 0) {
6119 
6120  // save computed values
6121  std::copy(zz.begin(), zz.end(), rr.begin());
6122 
6123  // COMPUTE residuals
6124  for (ii = 0; ii < nn; ii++) {
6125  zz[ii] = xx[ii] - zz[ii];
6126  }
6127  }
6128 
6129  } // end loop on noent
6130 
6131 
6132  double xmin = TMath::MinElement(nn,xx);
6133  for (ii = 0; ii < nn; ii++) {
6134  if (xmin < 0) xx[ii] = rr[ii] + zz[ii];
6135  // make smoothing defined positive - not better using 0 ?
6136  else xx[ii] = TMath::Max((rr[ii] + zz[ii]),0.0 );
6137  }
6138  }
6139 }
6140 
6141 ////////////////////////////////////////////////////////////////////////////////
6142 /// Smooth bin contents of this histogram.
6143 /// if option contains "R" smoothing is applied only to the bins
6144 /// defined in the X axis range (default is to smooth all bins)
6145 /// Bin contents are replaced by their smooth values.
6146 /// Errors (if any) are not modified.
6147 /// the smoothing procedure is repeated ntimes (default=1)
6148 
6149 void TH1::Smooth(Int_t ntimes, Option_t *option)
6150 {
6151  if (fDimension != 1) {
6152  Error("Smooth","Smooth only supported for 1-d histograms");
6153  return;
6154  }
6155  Int_t nbins = fXaxis.GetNbins();
6156  if (nbins < 3) {
6157  Error("Smooth","Smooth only supported for histograms with >= 3 bins. Nbins = %d",nbins);
6158  return;
6159  }
6160 
6161  // delete buffer if it is there since it will become invalid
6162  if (fBuffer) BufferEmpty(1);
6163 
6164  Int_t firstbin = 1, lastbin = nbins;
6165  TString opt = option;
6166  opt.ToLower();
6167  if (opt.Contains("r")) {
6168  firstbin= fXaxis.GetFirst();
6169  lastbin = fXaxis.GetLast();
6170  }
6171  nbins = lastbin - firstbin + 1;
6172  Double_t *xx = new Double_t[nbins];
6173  Double_t nent = fEntries;
6174  Int_t i;
6175  for (i=0;i<nbins;i++) {
6176  xx[i] = RetrieveBinContent(i+firstbin);
6177  }
6178 
6179  TH1::SmoothArray(nbins,xx,ntimes);
6180 
6181  for (i=0;i<nbins;i++) {
6182  UpdateBinContent(i+firstbin,xx[i]);
6183  }
6184  fEntries = nent;
6185  delete [] xx;
6186 
6187  if (gPad) gPad->Modified();
6188 }
6189 
6190 ////////////////////////////////////////////////////////////////////////////////
6191 /// if flag=kTRUE, underflows and overflows are used by the Fill functions
6192 /// in the computation of statistics (mean value, StdDev).
6193 /// By default, underflows or overflows are not used.
6194 
6195 void TH1::StatOverflows(Bool_t flag)
6196 {
6198 }
6199 
6200 ////////////////////////////////////////////////////////////////////////////////
6201 /// Stream a class object.
6202 
6203 void TH1::Streamer(TBuffer &b)
6204 {
6205  if (b.IsReading()) {
6206  UInt_t R__s, R__c;
6207  Version_t R__v = b.ReadVersion(&R__s, &R__c);
6208  if (fDirectory) fDirectory->Remove(this);
6209  fDirectory = 0;
6210  if (R__v > 2) {
6211  b.ReadClassBuffer(TH1::Class(), this, R__v, R__s, R__c);
6212 
6214  fXaxis.SetParent(this);
6215  fYaxis.SetParent(this);
6216  fZaxis.SetParent(this);
6217  TIter next(fFunctions);
6218  TObject *obj;
6219  while ((obj=next())) {
6220  if (obj->InheritsFrom(TF1::Class())) ((TF1*)obj)->SetParent(this);
6221  }
6222  return;
6223  }
6224  //process old versions before automatic schema evolution
6225  TNamed::Streamer(b);
6226  TAttLine::Streamer(b);
6227  TAttFill::Streamer(b);
6228  TAttMarker::Streamer(b);
6229  b >> fNcells;
6230  fXaxis.Streamer(b);
6231  fYaxis.Streamer(b);
6232  fZaxis.Streamer(b);
6233  fXaxis.SetParent(this);
6234  fYaxis.SetParent(this);
6235  fZaxis.SetParent(this);
6236  b >> fBarOffset;
6237  b >> fBarWidth;
6238  b >> fEntries;
6239  b >> fTsumw;
6240  b >> fTsumw2;
6241  b >> fTsumwx;
6242  b >> fTsumwx2;
6243  if (R__v < 2) {
6244  Float_t maximum, minimum, norm;
6245  Float_t *contour=0;
6246  b >> maximum; fMaximum = maximum;
6247  b >> minimum; fMinimum = minimum;
6248  b >> norm; fNormFactor = norm;
6249  Int_t n = b.ReadArray(contour);
6250  fContour.Set(n);
6251  for (Int_t i=0;i<n;i++) fContour.fArray[i] = contour[i];
6252  delete [] contour;
6253  } else {
6254  b >> fMaximum;
6255  b >> fMinimum;
6256  b >> fNormFactor;
6257  fContour.Streamer(b);
6258  }
6259  fSumw2.Streamer(b);
6260  fOption.Streamer(b);
6261  fFunctions->Delete();
6262  fFunctions->Streamer(b);
6263  b.CheckByteCount(R__s, R__c, TH1::IsA());
6264 
6265  } else {
6266  b.WriteClassBuffer(TH1::Class(),this);
6267  }
6268 }
6269 
6270 ////////////////////////////////////////////////////////////////////////////////
6271 /// Print some global quantities for this histogram.
6272 /// \param[in] option
6273 /// - "base" is given, number of bins and ranges are also printed
6274 /// - "range" is given, bin contents and errors are also printed
6275 /// for all bins in the current range (default 1-->nbins)
6276 /// - "all" is given, bin contents and errors are also printed
6277 /// for all bins including under and overflows.
6278 
6279 void TH1::Print(Option_t *option) const
6280 {
6281  if (fBuffer) const_cast<TH1*>(this)->BufferEmpty();
6282  printf( "TH1.Print Name = %s, Entries= %d, Total sum= %g\n",GetName(),Int_t(fEntries),GetSumOfWeights());
6283  TString opt = option;
6284  opt.ToLower();
6285  Int_t all;
6286  if (opt.Contains("all")) all = 0;
6287  else if (opt.Contains("range")) all = 1;
6288  else if (opt.Contains("base")) all = 2;
6289  else return;
6290 
6291  Int_t bin, binx, biny, binz;
6292  Int_t firstx=0,lastx=0,firsty=0,lasty=0,firstz=0,lastz=0;
6293  if (all == 0) {
6294  lastx = fXaxis.GetNbins()+1;
6295  if (fDimension > 1) lasty = fYaxis.GetNbins()+1;
6296  if (fDimension > 2) lastz = fZaxis.GetNbins()+1;
6297  } else {
6298  firstx = fXaxis.GetFirst(); lastx = fXaxis.GetLast();
6299  if (fDimension > 1) {firsty = fYaxis.GetFirst(); lasty = fYaxis.GetLast();}
6300  if (fDimension > 2) {firstz = fZaxis.GetFirst(); lastz = fZaxis.GetLast();}
6301  }
6302 
6303  if (all== 2) {
6304  printf(" Title = %s\n", GetTitle());
6305  printf(" NbinsX= %d, xmin= %g, xmax=%g", fXaxis.GetNbins(), fXaxis.GetXmin(), fXaxis.GetXmax());
6306  if( fDimension > 1) printf(", NbinsY= %d, ymin= %g, ymax=%g", fYaxis.GetNbins(), fYaxis.GetXmin(), fYaxis.GetXmax());
6307  if( fDimension > 2) printf(", NbinsZ= %d, zmin= %g, zmax=%g", fZaxis.GetNbins(), fZaxis.GetXmin(), fZaxis.GetXmax());
6308  printf("\n");
6309  return;
6310  }
6311 
6312  Double_t w,e;
6313  Double_t x,y,z;
6314  if (fDimension == 1) {
6315  for (binx=firstx;binx<=lastx;binx++) {
6316  x = fXaxis.GetBinCenter(binx);
6317  w = RetrieveBinContent(binx);
6318  e = GetBinError(binx);
6319  if(fSumw2.fN) printf(" fSumw[%d]=%g, x=%g, error=%g\n",binx,w,x,e);
6320  else printf(" fSumw[%d]=%g, x=%g\n",binx,w,x);
6321  }
6322  }
6323  if (fDimension == 2) {
6324  for (biny=firsty;biny<=lasty;biny++) {
6325  y = fYaxis.GetBinCenter(biny);
6326  for (binx=firstx;binx<=lastx;binx++) {
6327  bin = GetBin(binx,biny);
6328  x = fXaxis.GetBinCenter(binx);
6329  w = RetrieveBinContent(bin);
6330  e = GetBinError(bin);
6331  if(fSumw2.fN) printf(" fSumw[%d][%d]=%g, x=%g, y=%g, error=%g\n",binx,biny,w,x,y,e);
6332  else printf(" fSumw[%d][%d]=%g, x=%g, y=%g\n",binx,biny,w,x,y);
6333  }
6334  }
6335  }
6336  if (fDimension == 3) {
6337  for (binz=firstz;binz<=lastz;binz++) {
6338  z = fZaxis.GetBinCenter(binz);
6339  for (biny=firsty;biny<=lasty;biny++) {
6340  y = fYaxis.GetBinCenter(biny);
6341  for (binx=firstx;binx<=lastx;binx++) {
6342  bin = GetBin(binx,biny,binz);
6343  x = fXaxis.GetBinCenter(binx);
6344  w = RetrieveBinContent(bin);
6345  e = GetBinError(bin);
6346  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);
6347  else printf(" fSumw[%d][%d][%d]=%g, x=%g, y=%g, z=%g\n",binx,biny,binz,w,x,y,z);
6348  }
6349  }
6350  }
6351  }
6352 }
6353 
6354 ////////////////////////////////////////////////////////////////////////////////
6355 /// Using the current bin info, recompute the arrays for contents and errors
6356 
6357 void TH1::Rebuild(Option_t *)
6358 {
6360  if (fSumw2.fN) {
6361  fSumw2.Set(fNcells);
6362  }
6363 }
6364 
6365 ////////////////////////////////////////////////////////////////////////////////
6366 /// Reset this histogram: contents, errors, etc.
6367 /// \param[in] option
6368 /// - "ICE" is specified, resets only Integral, Contents and Errors.
6369 /// - "ICES" is specified, resets only Integral, Contents , Errors and Statistics
6370 /// This option is used
6371 /// - "M" is specified, resets also Minimum and Maximum
6372 
6373 void TH1::Reset(Option_t *option)
6374 {
6375  // The option "ICE" is used when extending the histogram (in ExtendAxis, LabelInflate, etc..)
6376  // The option "ICES is used in combination with the buffer (see BufferEmpty and BufferFill)
6377 
6378  TString opt = option;
6379  opt.ToUpper();
6380  fSumw2.Reset();
6381  if (fIntegral) {delete [] fIntegral; fIntegral = 0;}
6382 
6383  if (opt.Contains("M")) {
6384  SetMinimum();
6385  SetMaximum();
6386  }
6387 
6388  if (opt.Contains("ICE") && !opt.Contains("S")) return;
6389 
6390  // Setting fBuffer[0] = 0 is like resetting the buffer but not deleting it
6391  // But what is the sense of calling BufferEmpty() ? For making the axes ?
6392  // BufferEmpty will update contents that later will be
6393  // reset in calling TH1D::Reset. For this we need to reset the stats afterwards
6394  // It may be needed for computing the axis limits....
6395  if (fBuffer) {BufferEmpty(); fBuffer[0] = 0;}
6396 
6397  // need to reset also the statistics
6398  // (needs to be done after calling BufferEmpty() )
6399  fTsumw = 0;
6400  fTsumw2 = 0;
6401  fTsumwx = 0;
6402  fTsumwx2 = 0;
6403  fEntries = 0;
6404 
6405  if (opt == "ICES") return;
6406 
6407 
6408  TObject *stats = fFunctions->FindObject("stats");
6409  fFunctions->Remove(stats);
6410  //special logic to support the case where the same object is
6411  //added multiple times in fFunctions.
6412  //This case happens when the same object is added with different
6413  //drawing modes
6414  TObject *obj;
6415  while ((obj = fFunctions->First())) {
6416  while(fFunctions->Remove(obj)) { }
6417  delete obj;
6418  }
6419  if(stats) fFunctions->Add(stats);
6420  fContour.Set(0);
6421 }
6422 
6423 ////////////////////////////////////////////////////////////////////////////////
6424 /// Save primitive as a C++ statement(s) on output stream out
6425 
6426 void TH1::SavePrimitive(std::ostream &out, Option_t *option /*= ""*/)
6427 {
6428  // empty the buffer before if it exists
6429  if (fBuffer) BufferEmpty();
6430 
6431  Bool_t nonEqiX = kFALSE;
6432  Bool_t nonEqiY = kFALSE;
6433  Bool_t nonEqiZ = kFALSE;
6434  Int_t i;
6435  static Int_t nxaxis = 0;
6436  static Int_t nyaxis = 0;
6437  static Int_t nzaxis = 0;
6438  TString sxaxis="xAxis",syaxis="yAxis",szaxis="zAxis";
6439 
6440  // Check if the histogram has equidistant X bins or not. If not, we
6441  // create an array holding the bins.
6442  if (GetXaxis()->GetXbins()->fN && GetXaxis()->GetXbins()->fArray) {
6443  nonEqiX = kTRUE;
6444  nxaxis++;
6445  sxaxis += nxaxis;
6446  out << " Double_t "<<sxaxis<<"[" << GetXaxis()->GetXbins()->fN
6447  << "] = {";
6448  for (i = 0; i < GetXaxis()->GetXbins()->fN; i++) {
6449  if (i != 0) out << ", ";
6450  out << GetXaxis()->GetXbins()->fArray[i];
6451  }
6452  out << "}; " << std::endl;
6453  }
6454  // If the histogram is 2 or 3 dimensional, check if the histogram
6455  // has equidistant Y bins or not. If not, we create an array
6456  // holding the bins.
6457  if (fDimension > 1 && GetYaxis()->GetXbins()->fN &&
6458  GetYaxis()->GetXbins()->fArray) {
6459  nonEqiY = kTRUE;
6460  nyaxis++;
6461  syaxis += nyaxis;
6462  out << " Double_t "<<syaxis<<"[" << GetYaxis()->GetXbins()->fN
6463  << "] = {";
6464  for (i = 0; i < GetYaxis()->GetXbins()->fN; i++) {
6465  if (i != 0) out << ", ";
6466  out << GetYaxis()->GetXbins()->fArray[i];
6467  }
6468  out << "}; " << std::endl;
6469  }
6470  // IF the histogram is 3 dimensional, check if the histogram
6471  // has equidistant Z bins or not. If not, we create an array
6472  // holding the bins.
6473  if (fDimension > 2 && GetZaxis()->GetXbins()->fN &&
6474  GetZaxis()->GetXbins()->fArray) {
6475  nonEqiZ = kTRUE;
6476  nzaxis++;
6477  szaxis += nzaxis;
6478  out << " Double_t "<<szaxis<<"[" << GetZaxis()->GetXbins()->fN
6479  << "] = {";
6480  for (i = 0; i < GetZaxis()->GetXbins()->fN; i++) {
6481  if (i != 0) out << ", ";
6482  out << GetZaxis()->GetXbins()->fArray[i];
6483  }
6484  out << "}; " << std::endl;
6485  }
6486 
6487  char quote = '"';
6488  out <<" "<<std::endl;
6489  out <<" "<< ClassName() <<" *";
6490 
6491  // Histogram pointer has by default the histogram name with an incremental suffix.
6492  // If the histogram belongs to a graph or a stack the suffix is not added because
6493  // the graph and stack objects are not aware of this new name. Same thing if
6494  // the histogram is drawn with the option COLZ because the TPaletteAxis drawn
6495  // when this option is selected, does not know this new name either.
6496  TString opt = option;
6497  opt.ToLower();
6498  static Int_t hcounter = 0;
6499  TString histName = GetName();
6500  if ( !histName.Contains("Graph")
6501  && !histName.Contains("_stack_")
6502  && !opt.Contains("colz")) {
6503  hcounter++;
6504  histName += "__";
6505  histName += hcounter;
6506  }
6507  histName = gInterpreter-> MapCppName(histName);
6508  const char *hname = histName.Data();
6509  if (!strlen(hname)) hname = "unnamed";
6510 
6511  TString t(GetTitle());
6512  t.ReplaceAll("\\","\\\\");
6513  t.ReplaceAll("\"","\\\"");
6514  out << hname << " = new " << ClassName() << "(" << quote
6515  << hname << quote << "," << quote<< t.Data() << quote
6516  << "," << GetXaxis()->GetNbins();
6517  if (nonEqiX)
6518  out << ", "<<sxaxis;
6519  else
6520  out << "," << GetXaxis()->GetXmin()
6521  << "," << GetXaxis()->GetXmax();
6522  if (fDimension > 1) {
6523  out << "," << GetYaxis()->GetNbins();
6524  if (nonEqiY)
6525  out << ", "<<syaxis;
6526  else
6527  out << "," << GetYaxis()->GetXmin()
6528  << "," << GetYaxis()->GetXmax();
6529  }
6530  if (fDimension > 2) {
6531  out << "," << GetZaxis()->GetNbins();
6532  if (nonEqiZ)
6533  out << ", "<<szaxis;
6534  else
6535  out << "," << GetZaxis()->GetXmin()
6536  << "," << GetZaxis()->GetXmax();
6537  }
6538  out << ");" << std::endl;
6539 
6540  // save bin contents
6541  Int_t bin;
6542  for (bin=0;bin<fNcells;bin++) {
6543  Double_t bc = RetrieveBinContent(bin);
6544  if (bc) {
6545  out<<" "<<hname<<"->SetBinContent("<<bin<<","<<bc<<");"<<std::endl;
6546  }
6547  }
6548 
6549  // save bin errors
6550  if (fSumw2.fN) {
6551  for (bin=0;bin<fNcells;bin++) {
6552  Double_t be = GetBinError(bin);
6553  if (be) {
6554  out<<" "<<hname<<"->SetBinError("<<bin<<","<<be<<");"<<std::endl;
6555  }
6556  }
6557  }
6558 
6559  TH1::SavePrimitiveHelp(out, hname, option);
6560 }
6561 
6562 ////////////////////////////////////////////////////////////////////////////////
6563 /// Helper function for the SavePrimitive functions from TH1
6564 /// or classes derived from TH1, eg TProfile, TProfile2D.
6565 
6566 void TH1::SavePrimitiveHelp(std::ostream &out, const char *hname, Option_t *option /*= ""*/)
6567 {
6568  char quote = '"';
6569  if (TMath::Abs(GetBarOffset()) > 1e-5) {
6570  out<<" "<<hname<<"->SetBarOffset("<<GetBarOffset()<<");"<<std::endl;
6571  }
6572  if (TMath::Abs(GetBarWidth()-1) > 1e-5) {
6573  out<<" "<<hname<<"->SetBarWidth("<<GetBarWidth()<<");"<<std::endl;
6574  }
6575  if (fMinimum != -1111) {
6576  out<<" "<<hname<<"->SetMinimum("<<fMinimum<<");"<<std::endl;
6577  }
6578  if (fMaximum != -1111) {
6579  out<<" "<<hname<<"->SetMaximum("<<fMaximum<<");"<<std::endl;
6580  }
6581  if (fNormFactor != 0) {
6582  out<<" "<<hname<<"->SetNormFactor("<<fNormFactor<<");"<<std::endl;
6583  }
6584  if (fEntries != 0) {
6585  out<<" "<<hname<<"->SetEntries("<<fEntries<<");"<<std::endl;
6586  }
6587  if (fDirectory == 0) {
6588  out<<" "<<hname<<"->SetDirectory(0);"<<std::endl;
6589  }
6590  if (TestBit(kNoStats)) {
6591  out<<" "<<hname<<"->SetStats(0);"<<std::endl;
6592  }
6593  if (fOption.Length() != 0) {
6594  out<<" "<<hname<<"->SetOption("<<quote<<fOption.Data()<<quote<<");"<<std::endl;
6595  }
6596 
6597  // save contour levels
6598  Int_t ncontours = GetContour();
6599  if (ncontours > 0) {
6600  out<<" "<<hname<<"->SetContour("<<ncontours<<");"<<std::endl;
6601  Double_t zlevel;
6602  for (Int_t bin=0;bin<ncontours;bin++) {
6603  if (gPad->GetLogz()) {
6604  zlevel = TMath::Power(10,GetContourLevel(bin));
6605  } else {
6606  zlevel = GetContourLevel(bin);
6607  }
6608  out<<" "<<hname<<"->SetContourLevel("<<bin<<","<<zlevel<<");"<<std::endl;
6609  }
6610  }
6611 
6612  // save list of functions
6614  TObject *obj;
6615  static Int_t funcNumber = 0;
6616  while (lnk) {
6617  obj = lnk->GetObject();
6618  obj->SavePrimitive(out,Form("nodraw #%d\n",++funcNumber));
6619  if (obj->InheritsFrom(TF1::Class())) {
6620  out<<" "<<hname<<"->GetListOfFunctions()->Add("
6621  <<Form("%s%d",obj->GetName(),funcNumber)<<");"<<std::endl;
6622  } else if (obj->InheritsFrom("TPaveStats")) {
6623  out<<" "<<hname<<"->GetListOfFunctions()->Add(ptstats);"<<std::endl;
6624  out<<" ptstats->SetParent("<<hname<<");"<<std::endl;
6625  } else {
6626  out<<" "<<hname<<"->GetListOfFunctions()->Add("
6627  <<obj->GetName()
6628  <<","<<quote<<lnk->GetOption()<<quote<<");"<<std::endl;
6629  }
6630  lnk = (TObjOptLink*)lnk->Next();
6631  }
6632 
6633  // save attributes
6634  SaveFillAttributes(out,hname,0,1001);
6635  SaveLineAttributes(out,hname,1,1,1);
6636  SaveMarkerAttributes(out,hname,1,1,1);
6637  fXaxis.SaveAttributes(out,hname,"->GetXaxis()");
6638  fYaxis.SaveAttributes(out,hname,"->GetYaxis()");
6639  fZaxis.SaveAttributes(out,hname,"->GetZaxis()");
6640  TString opt = option;
6641  opt.ToLower();
6642  if (!opt.Contains("nodraw")) {
6643  out<<" "<<hname<<"->Draw("
6644  <<quote<<option<<quote<<");"<<std::endl;
6645  }
6646 }
6647 
6648 ////////////////////////////////////////////////////////////////////////////////
6649 /// Copy current attributes from/to current style
6650 
6651 void TH1::UseCurrentStyle()
6652 {
6653  if (!gStyle) return;
6654  if (gStyle->IsReading()) {
6655  fXaxis.ResetAttAxis("X");
6656  fYaxis.ResetAttAxis("Y");
6657  fZaxis.ResetAttAxis("Z");
6668  Int_t dostat = gStyle->GetOptStat();
6669  if (gStyle->GetOptFit() && !dostat) dostat = 1000000001;
6670  SetStats(dostat);
6671  } else {
6683  }
6684  TIter next(GetListOfFunctions());
6685  TObject *obj;
6686 
6687  while ((obj = next())) {
6688  obj->UseCurrentStyle();
6689  }
6690 }
6691 
6692 ////////////////////////////////////////////////////////////////////////////////
6693 /// For axis = 1,2 or 3 returns the mean value of the histogram along
6694 /// X,Y or Z axis.
6695 ///
6696 /// For axis = 11, 12, 13 returns the standard error of the mean value
6697 /// of the histogram along X, Y or Z axis
6698 ///
6699 /// Note that the mean value/StdDev is computed using the bins in the currently
6700 /// defined range (see TAxis::SetRange). By default the range includes
6701 /// all bins from 1 to nbins included, excluding underflows and overflows.
6702 /// To force the underflows and overflows in the computation, one must
6703 /// call the static function TH1::StatOverflows(kTRUE) before filling
6704 /// the histogram.
6705 ///
6706 /// Return mean value of this histogram along the X axis.
6707 ///
6708 /// Note that the mean value/StdDev is computed using the bins in the currently
6709 /// defined range (see TAxis::SetRange). By default the range includes
6710 /// all bins from 1 to nbins included, excluding underflows and overflows.
6711 /// To force the underflows and overflows in the computation, one must
6712 /// call the static function TH1::StatOverflows(kTRUE) before filling
6713 /// the histogram.
6714 
6715 Double_t TH1::GetMean(Int_t axis) const
6716 {
6717  if (axis<1 || (axis>3 && axis<11) || axis>13) return 0;
6718  Double_t stats[kNstat];
6719  for (Int_t i=4;i<kNstat;i++) stats[i] = 0;
6720  GetStats(stats);
6721  if (stats[0] == 0) return 0;
6722  if (axis<4){
6723  Int_t ax[3] = {2,4,7};
6724  return stats[ax[axis-1]]/stats[0];
6725  } else {
6726  // mean error = StdDev / sqrt( Neff )
6727  Double_t stddev = GetStdDev(axis-10);
6728  Double_t neff = GetEffectiveEntries();
6729  return ( neff > 0 ? stddev/TMath::Sqrt(neff) : 0. );
6730  }
6731 }
6732 
6733 ////////////////////////////////////////////////////////////////////////////////
6734 /// Return standard error of mean of this histogram along the X axis.
6735 ///
6736 /// Note that the mean value/StdDev is computed using the bins in the currently
6737 /// defined range (see TAxis::SetRange). By default the range includes
6738 /// all bins from 1 to nbins included, excluding underflows and overflows.
6739 /// To force the underflows and overflows in the computation, one must
6740 /// call the static function TH1::StatOverflows(kTRUE) before filling
6741 /// the histogram.
6742 ///
6743 /// Also note, that although the definition of standard error doesn't include the
6744 /// assumption of normality, many uses of this feature implicitly assume it.
6745 
6746 Double_t TH1::GetMeanError(Int_t axis) const
6747 {
6748  return GetMean(axis+10);
6749 }
6750 
6751 ////////////////////////////////////////////////////////////////////////////////
6752 /// Returns the Standard Deviation (Sigma).
6753 /// The Sigma estimate is computed as
6754 /// \f[
6755 /// \sqrt{\frac{1}{N}(\sum(x_i-x_{mean})^2)}
6756 /// \f]
6757 /// For axis = 1,2 or 3 returns the Sigma value of the histogram along
6758 /// X, Y or Z axis
6759 /// For axis = 11, 12 or 13 returns the error of StdDev estimation along
6760 /// X, Y or Z axis for Normal distribution
6761 ///
6762 /// Note that the mean value/sigma is computed using the bins in the currently
6763 /// defined range (see TAxis::SetRange). By default the range includes
6764 /// all bins from 1 to nbins included, excluding underflows and overflows.
6765 /// To force the underflows and overflows in the computation, one must
6766 /// call the static function TH1::StatOverflows(kTRUE) before filling
6767 /// the histogram.
6768 
6769 Double_t TH1::GetStdDev(Int_t axis) const
6770 {
6771  if (axis<1 || (axis>3 && axis<11) || axis>13) return 0;
6772 
6773  Double_t x, stddev2, stats[kNstat];
6774  for (Int_t i=4;i<kNstat;i++) stats[i] = 0;
6775  GetStats(stats);
6776  if (stats[0] == 0) return 0;
6777  Int_t ax[3] = {2,4,7};
6778  Int_t axm = ax[axis%10 - 1];
6779  x = stats[axm]/stats[0];
6780  stddev2 = TMath::Abs(stats[axm+1]/stats[0] -x*x);
6781  if (axis<10)
6782  return TMath::Sqrt(stddev2);
6783  else {
6784  // The right formula for StdDev error depends on 4th momentum (see Kendall-Stuart Vol 1 pag 243)
6785  // formula valid for only gaussian distribution ( 4-th momentum = 3 * sigma^4 )
6786  Double_t neff = GetEffectiveEntries();
6787  return ( neff > 0 ? TMath::Sqrt(stddev2/(2*neff) ) : 0. );
6788  }
6789 }
6790 
6791 ////////////////////////////////////////////////////////////////////////////////
6792 /// Return error of standard deviation estimation for Normal distribution
6793 ///
6794 /// Note that the mean value/StdDev is computed using the bins in the currently
6795 /// defined range (see TAxis::SetRange). By default the range includes
6796 /// all bins from 1 to nbins included, excluding underflows and overflows.
6797 /// To force the underflows and overflows in the computation, one must
6798 /// call the static function TH1::StatOverflows(kTRUE) before filling
6799 /// the histogram.
6800 ///
6801 /// Value returned is standard deviation of sample standard deviation.
6802 /// Note that it is an approximated value which is valid only in the case that the
6803 /// original data distribution is Normal. The correct one would require
6804 /// the 4-th momentum value, which cannot be accurately estimated from an histogram since
6805 /// the x-information for all entries is not kept.
6806 
6808 {
6809  return GetStdDev(axis+10);
6810 }
6811 
6812 ////////////////////////////////////////////////////////////////////////////////
6813 /// - For axis = 1, 2 or 3 returns skewness of the histogram along x, y or z axis.
6814 /// - For axis = 11, 12 or 13 returns the approximate standard error of skewness
6815 /// of the histogram along x, y or z axis
6816 ///
6817 ///Note, that since third and fourth moment are not calculated
6818 ///at the fill time, skewness and its standard error are computed bin by bin
6819 
6820 Double_t TH1::GetSkewness(Int_t axis) const
6821 {
6823  if (axis > 0 && axis <= 3){
6824 
6825  Double_t mean = GetMean(axis);
6826  Double_t stddev = GetStdDev(axis);
6827  Double_t stddev3 = stddev*stddev*stddev;
6828 
6829  Int_t firstBinX = fXaxis.GetFirst();
6830  Int_t lastBinX = fXaxis.GetLast();
6831  Int_t firstBinY = fYaxis.GetFirst();
6832  Int_t lastBinY = fYaxis.GetLast();
6833  Int_t firstBinZ = fZaxis.GetFirst();
6834  Int_t lastBinZ = fZaxis.GetLast();
6835  // include underflow/overflow if TH1::StatOverflows(kTRUE) in case no range is set on the axis
6836  if (fgStatOverflows) {
6837  if ( !fXaxis.TestBit(TAxis::kAxisRange) ) {
6838  if (firstBinX == 1) firstBinX = 0;
6839  if (lastBinX == fXaxis.GetNbins() ) lastBinX += 1;
6840  }
6841  if ( !fYaxis.TestBit(TAxis::kAxisRange) ) {
6842  if (firstBinY == 1) firstBinY = 0;
6843  if (lastBinY == fYaxis.GetNbins() ) lastBinY += 1;
6844  }
6845  if ( !fZaxis.TestBit(TAxis::kAxisRange) ) {
6846  if (firstBinZ == 1) firstBinZ = 0;
6847  if (lastBinZ == fZaxis.GetNbins() ) lastBinZ += 1;
6848  }
6849  }
6850 
6851  Double_t x = 0;
6852  Double_t sum=0;
6853  Double_t np=0;
6854  for (Int_t binx = firstBinX; binx <= lastBinX; binx++) {
6855  for (Int_t biny = firstBinY; biny <= lastBinY; biny++) {
6856  for (Int_t binz = firstBinZ; binz <= lastBinZ; binz++) {
6857  if (axis==1 ) x = fXaxis.GetBinCenter(binx);
6858  else if (axis==2 ) x = fYaxis.GetBinCenter(biny);
6859  else if (axis==3 ) x = fZaxis.GetBinCenter(binz);
6860  Double_t w = GetBinContent(binx,biny,binz);
6861  np+=w;
6862  sum+=w*(x-mean)*(x-mean)*(x-mean);
6863  }
6864  }
6865  }
6866  sum/=np*stddev3;
6867  return sum;
6868  }
6869  else if (axis > 10 && axis <= 13) {
6870  //compute standard error of skewness
6871  // assume parent normal distribution use formula from Kendall-Stuart, Vol 1 pag 243, second edition
6872  Double_t neff = GetEffectiveEntries();
6873  return ( neff > 0 ? TMath::Sqrt(6./neff ) : 0. );
6874  }
6875  else {
6876  Error("GetSkewness", "illegal value of parameter");
6877  return 0;
6878  }
6879 }
6880 
6881 ////////////////////////////////////////////////////////////////////////////////
6882 /// - For axis =1, 2 or 3 returns kurtosis of the histogram along x, y or z axis.
6883 /// Kurtosis(gaussian(0, 1)) = 0.
6884 /// - For axis =11, 12 or 13 returns the approximate standard error of kurtosis
6885 /// of the histogram along x, y or z axis
6886 ////
6887 /// Note, that since third and fourth moment are not calculated
6888 /// at the fill time, kurtosis and its standard error are computed bin by bin
6889 
6890 Double_t TH1::GetKurtosis(Int_t axis) const
6891 {
6892  if (axis > 0 && axis <= 3){
6893 
6894  Double_t mean = GetMean(axis);
6895  Double_t stddev = GetStdDev(axis);
6896  Double_t stddev4 = stddev*stddev*stddev*stddev;
6897 
6898  Int_t firstBinX = fXaxis.GetFirst();
6899  Int_t lastBinX = fXaxis.GetLast();
6900  Int_t firstBinY = fYaxis.GetFirst();
6901  Int_t lastBinY = fYaxis.GetLast();
6902  Int_t firstBinZ = fZaxis.GetFirst();
6903  Int_t lastBinZ = fZaxis.GetLast();
6904  // include underflow/overflow if TH1::StatOverflows(kTRUE) in case no range is set on the axis
6905  if (fgStatOverflows) {
6906  if ( !fXaxis.TestBit(TAxis::kAxisRange) ) {
6907  if (firstBinX == 1) firstBinX = 0;
6908  if (lastBinX == fXaxis.GetNbins() ) lastBinX += 1;
6909  }
6910  if ( !fYaxis.TestBit(TAxis::kAxisRange) ) {
6911  if (firstBinY == 1) firstBinY = 0;
6912  if (lastBinY == fYaxis.GetNbins() ) lastBinY += 1;
6913  }
6914  if ( !fZaxis.TestBit(TAxis::kAxisRange) ) {
6915  if (firstBinZ == 1) firstBinZ = 0;
6916  if (lastBinZ == fZaxis.GetNbins() ) lastBinZ += 1;
6917  }
6918  }
6919 
6920  Double_t x = 0;
6921  Double_t sum=0;
6922  Double_t np=0;
6923  for (Int_t binx = firstBinX; binx <= lastBinX; binx++) {
6924  for (Int_t biny = firstBinY; biny <= lastBinY; biny++) {
6925  for (Int_t binz = firstBinZ; binz <= lastBinZ; binz++) {
6926  if (axis==1 ) x = fXaxis.GetBinCenter(binx);
6927  else if (axis==2 ) x = fYaxis.GetBinCenter(biny);
6928  else if (axis==3 ) x = fZaxis.GetBinCenter(binz);
6929  Double_t w = GetBinContent(binx,biny,binz);
6930  np+=w;
6931  sum+=w*(x-mean)*(x-mean)*(x-mean)*(x-mean);
6932  }
6933  }
6934  }
6935  sum/=(np*stddev4);
6936  return sum-3;
6937 
6938  } else if (axis > 10 && axis <= 13) {
6939  //compute standard error of skewness
6940  // assume parent normal distribution use formula from Kendall-Stuart, Vol 1 pag 243, second edition
6941  Double_t neff = GetEffectiveEntries();
6942  return ( neff > 0 ? TMath::Sqrt(24./neff ) : 0. );
6943  }
6944  else {
6945  Error("GetKurtosis", "illegal value of parameter");
6946  return 0;
6947  }
6948 }
6949 
6950 ////////////////////////////////////////////////////////////////////////////////
6951 /// fill the array stats from the contents of this histogram
6952 /// The array stats must be correctly dimensioned in the calling program.
6953 ///
6954 /// ~~~ {.cpp}
6955 /// stats[0] = sumw
6956 /// stats[1] = sumw2
6957 /// stats[2] = sumwx
6958 /// stats[3] = sumwx2
6959 /// ~~~
6960 ///
6961 /// If no axis-subrange is specified (via TAxis::SetRange), the array stats
6962 /// is simply a copy of the statistics quantities computed at filling time.
6963 /// If a sub-range is specified, the function recomputes these quantities
6964 /// from the bin contents in the current axis range.
6965 ///
6966 /// Note that the mean value/StdDev is computed using the bins in the currently
6967 /// defined range (see TAxis::SetRange). By default the range includes
6968 /// all bins from 1 to nbins included, excluding underflows and overflows.
6969 /// To force the underflows and overflows in the computation, one must
6970 /// call the static function TH1::StatOverflows(kTRUE) before filling
6971 /// the histogram.
6972 
6973 void TH1::GetStats(Double_t *stats) const
6974 {
6975  if (fBuffer) ((TH1*)this)->BufferEmpty();
6976 
6977  // Loop on bins (possibly including underflows/overflows)
6978  Int_t bin, binx;
6979  Double_t w,err;
6980  Double_t x;
6981  // case of labels with extension of axis range
6982  // statistics in x does not make any sense - set to zero
6983  if ((const_cast<TAxis&>(fXaxis)).GetLabels() && CanExtendAllAxes() ) {
6984  stats[0] = fTsumw;
6985  stats[1] = fTsumw2;
6986  stats[2] = 0;
6987  stats[3] = 0;
6988  }
6989  else if ((fTsumw == 0 && fEntries > 0) || fXaxis.TestBit(TAxis::kAxisRange)) {
6990  for (bin=0;bin<4;bin++) stats[bin] = 0;
6991 
6992  Int_t firstBinX = fXaxis.GetFirst();
6993  Int_t lastBinX = fXaxis.GetLast();
6994  // include underflow/overflow if TH1::StatOverflows(kTRUE) in case no range is set on the axis
6996  if (firstBinX == 1) firstBinX = 0;
6997  if (lastBinX == fXaxis.GetNbins() ) lastBinX += 1;
6998  }
6999  for (binx = firstBinX; binx <= lastBinX; binx++) {
7000  x = fXaxis.GetBinCenter(binx);
7001  //w = TMath::Abs(RetrieveBinContent(binx));
7002  // not sure what to do here if w < 0
7003  w = RetrieveBinContent(binx);
7004  err = TMath::Abs(GetBinError(binx));
7005  stats[0] += w;
7006  stats[1] += err*err;
7007  stats[2] += w*x;
7008  stats[3] += w*x*x;
7009  }
7010  // if (stats[0] < 0) {
7011  // // in case total is negative do something ??
7012  // stats[0] = 0;
7013  // }
7014  } else {
7015  stats[0] = fTsumw;
7016  stats[1] = fTsumw2;
7017  stats[2] = fTsumwx;
7018  stats[3] = fTsumwx2;
7019  }
7020 }
7021 
7022 ////////////////////////////////////////////////////////////////////////////////
7023 /// Replace current statistics with the values in array stats
7024 
7025 void TH1::PutStats(Double_t *stats)
7026 {
7027  fTsumw = stats[0];
7028  fTsumw2 = stats[1];
7029  fTsumwx = stats[2];
7030  fTsumwx2 = stats[3];
7031 }
7032 
7033 ////////////////////////////////////////////////////////////////////////////////
7034 /// Reset the statistics including the number of entries
7035 /// and replace with values calculates from bin content
7036 ///
7037 /// The number of entries is set to the total bin content or (in case of weighted histogram)
7038 /// to number of effective entries
7039 
7040 void TH1::ResetStats()
7041 {
7042  Double_t stats[kNstat] = {0};
7043  fTsumw = 0;
7044  fEntries = 1; // to force re-calculation of the statistics in TH1::GetStats
7045  GetStats(stats);
7046  PutStats(stats);
7048  // use effective entries for weighted histograms: (sum_w) ^2 / sum_w2
7049  if (fSumw2.fN > 0 && fTsumw > 0 && stats[1] > 0 ) fEntries = stats[0]*stats[0]/ stats[1];
7050 }
7051 
7052 ////////////////////////////////////////////////////////////////////////////////
7053 /// Return the sum of weights excluding under/overflows.
7054 
7056 {
7057  if (fBuffer) const_cast<TH1*>(this)->BufferEmpty();
7058 
7059  Int_t bin,binx,biny,binz;
7060  Double_t sum =0;
7061  for(binz=1; binz<=fZaxis.GetNbins(); binz++) {
7062  for(biny=1; biny<=fYaxis.GetNbins(); biny++) {
7063  for(binx=1; binx<=fXaxis.GetNbins(); binx++) {
7064  bin = GetBin(binx,biny,binz);
7065  sum += RetrieveBinContent(bin);
7066  }
7067  }
7068  }
7069  return sum;
7070 }
7071 
7072 ////////////////////////////////////////////////////////////////////////////////
7073 ///Return integral of bin contents. Only bins in the bins range are considered.
7074 ///
7075 /// By default the integral is computed as the sum of bin contents in the range.
7076 /// if option "width" is specified, the integral is the sum of
7077 /// the bin contents multiplied by the bin width in x.
7078 
7079 Double_t TH1::Integral(Option_t *option) const
7080 {
7081  return Integral(fXaxis.GetFirst(),fXaxis.GetLast(),option);
7082 }
7083 
7084 ////////////////////////////////////////////////////////////////////////////////
7085 /// Return integral of bin contents in range [binx1,binx2].
7086 ///
7087 /// By default the integral is computed as the sum of bin contents in the range.
7088 /// if option "width" is specified, the integral is the sum of
7089 /// the bin contents multiplied by the bin width in x.
7090 
7091 Double_t TH1::Integral(Int_t binx1, Int_t binx2, Option_t *option) const
7092 {
7093  double err = 0;
7094  return DoIntegral(binx1,binx2,0,-1,0,-1,err,option);
7095 }
7096 
7097 ////////////////////////////////////////////////////////////////////////////////
7098 /// Return integral of bin contents in range [binx1,binx2] and its error.
7099 ///
7100 /// By default the integral is computed as the sum of bin contents in the range.
7101 /// if option "width" is specified, the integral is the sum of
7102 /// the bin contents multiplied by the bin width in x.
7103 /// the error is computed using error propagation from the bin errors assuming that
7104 /// all the bins are uncorrelated
7105 
7106 Double_t TH1::IntegralAndError(Int_t binx1, Int_t binx2, Double_t & error, Option_t *option) const
7107 {
7108  return DoIntegral(binx1,binx2,0,-1,0,-1,error,option,kTRUE);
7109 }
7110 
7111 ////////////////////////////////////////////////////////////////////////////////
7112 /// Internal function compute integral and optionally the error between the limits
7113 /// specified by the bin number values working for all histograms (1D, 2D and 3D)
7114 
7115 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 ,
7116  Option_t *option, Bool_t doError) const
7118  if (fBuffer) ((TH1*)this)->BufferEmpty();
7119 
7120  Int_t nx = GetNbinsX() + 2;
7121  if (binx1 < 0) binx1 = 0;
7122  if (binx2 >= nx || binx2 < binx1) binx2 = nx - 1;
7123 
7124  if (GetDimension() > 1) {
7125  Int_t ny = GetNbinsY() + 2;
7126  if (biny1 < 0) biny1 = 0;
7127  if (biny2 >= ny || biny2 < biny1) biny2 = ny - 1;
7128  } else {
7129  biny1 = 0; biny2 = 0;
7130  }
7131 
7132  if (GetDimension() > 2) {
7133  Int_t nz = GetNbinsZ() + 2;
7134  if (binz1 < 0) binz1 = 0;
7135  if (binz2 >= nz || binz2 < binz1) binz2 = nz - 1;
7136  } else {
7137  binz1 = 0; binz2 = 0;
7138  }
7139 
7140  // - Loop on bins in specified range
7141  TString opt = option;
7142  opt.ToLower();
7143  Bool_t width = kFALSE;
7144  if (opt.Contains("width")) width = kTRUE;
7145 
7146 
7147  Double_t dx = 1., dy = .1, dz =.1;
7148  Double_t integral = 0;
7149  Double_t igerr2 = 0;
7150  for (Int_t binx = binx1; binx <= binx2; ++binx) {
7151  if (width) dx = fXaxis.GetBinWidth(binx);
7152  for (Int_t biny = biny1; biny <= biny2; ++biny) {
7153  if (width) dy = fYaxis.GetBinWidth(biny);
7154  for (Int_t binz = binz1; binz <= binz2; ++binz) {
7155  Int_t bin = GetBin(binx, biny, binz);
7156  Double_t dv = 0.0;
7157  if (width) {
7158  dz = fZaxis.GetBinWidth(binz);
7159  dv = dx * dy * dz;
7160  integral += RetrieveBinContent(bin) * dv;
7161  } else {
7162  integral += RetrieveBinContent(bin);
7163  }
7164  if (doError) {
7165  if (width) igerr2 += GetBinErrorSqUnchecked(bin) * dv * dv;
7166  else igerr2 += GetBinErrorSqUnchecked(bin);
7167  }
7168  }
7169  }
7170  }
7171 
7172  if (doError) error = TMath::Sqrt(igerr2);
7173  return integral;
7174 }
7175 
7176 ////////////////////////////////////////////////////////////////////////////////
7177 /// Statistical test of compatibility in shape between
7178 /// this histogram and h2, using the Anderson-Darling 2 sample test.
7179 ///
7180 /// The AD 2 sample test formula are derived from the paper
7181 /// F.W Scholz, M.A. Stephens "k-Sample Anderson-Darling Test".
7182 ///
7183 /// The test is implemented in root in the ROOT::Math::GoFTest class
7184 /// It is the same formula ( (6) in the paper), and also shown in
7185 /// [this preprint](http://arxiv.org/pdf/0804.0380v1.pdf)
7186 ///
7187 /// Binned data are considered as un-binned data
7188 /// with identical observation happening in the bin center.
7189 ///
7190 /// \param[in] option is a character string to specify options
7191 /// - "D" Put out a line of "Debug" printout
7192 /// - "T" Return the normalized A-D test statistic
7193 ///
7194 /// - Note1: Underflow and overflow are not considered in the test
7195 /// - Note2: The test works only for un-weighted histogram (i.e. representing counts)
7196 /// - Note3: The histograms are not required to have the same X axis
7197 /// - Note4: The test works only for 1-dimensional histograms
7198 
7199 Double_t TH1::AndersonDarlingTest(const TH1 *h2, Option_t *option) const
7200 {
7201  Double_t advalue = 0;
7202  Double_t pvalue = AndersonDarlingTest(h2, advalue);
7203 
7204  TString opt = option;
7205  opt.ToUpper();
7206  if (opt.Contains("D") ) {
7207  printf(" AndersonDarlingTest Prob = %g, AD TestStatistic = %g\n",pvalue,advalue);
7208  }
7209  if (opt.Contains("T") ) return advalue;
7210 
7211  return pvalue;
7212 }
7213 
7214 ////////////////////////////////////////////////////////////////////////////////
7215 /// Same function as above but returning also the test statistic value
7216 
7217 Double_t TH1::AndersonDarlingTest(const TH1 *h2, Double_t & advalue) const
7218 {
7219  if (GetDimension() != 1 || h2->GetDimension() != 1) {
7220  Error("AndersonDarlingTest","Histograms must be 1-D");
7221  return -1;
7222  }
7223 
7224  // empty the buffer. Probably we could add as an unbinned test
7225  if (fBuffer) ((TH1*)this)->BufferEmpty();
7226 
7227  // use the BinData class
7228  ROOT::Fit::BinData data1;
7229  ROOT::Fit::BinData data2;
7230 
7231  ROOT::Fit::FillData(data1, this, 0);
7232  ROOT::Fit::FillData(data2, h2, 0);
7233 
7234  double pvalue;
7235  ROOT::Math::GoFTest::AndersonDarling2SamplesTest(data1,data2, pvalue,advalue);
7236 
7237  return pvalue;
7238 }
7239 
7240 ////////////////////////////////////////////////////////////////////////////////
7241 /// Statistical test of compatibility in shape between
7242 /// this histogram and h2, using Kolmogorov test.
7243 /// Note that the KolmogorovTest (KS) test should in theory be used only for unbinned data
7244 /// and not for binned data as in the case of the histogram (see NOTE 3 below).
7245 /// So, before using this method blindly, read the NOTE 3.
7246 ///
7247 /// Default: Ignore under- and overflow bins in comparison
7248 ///
7249 /// \param[in] h2 histogram
7250 /// \param[in] option is a character string to specify options
7251 /// - "U" include Underflows in test (also for 2-dim)
7252 /// - "O" include Overflows (also valid for 2-dim)
7253 /// - "N" include comparison of normalizations
7254 /// - "D" Put out a line of "Debug" printout
7255 /// - "M" Return the Maximum Kolmogorov distance instead of prob
7256 /// - "X" Run the pseudo experiments post-processor with the following procedure:
7257 /// make pseudoexperiments based on random values from the parent
7258 /// distribution and compare the KS distance of the pseudoexperiment
7259 /// to the parent distribution. Bin the KS distances in a histogram,
7260 /// and then take the integral of all the KS values above the value
7261 /// obtained from the original data to Monte Carlo distribution.
7262 /// The number of pseudo-experiments nEXPT is currently fixed at 1000.
7263 /// The function returns the integral.
7264 /// (thanks to Ben Kilminster to submit this procedure). Note that
7265 /// this option "X" is much slower.
7266 ///
7267 /// The returned function value is the probability of test
7268 /// (much less than one means NOT compatible)
7269 ///
7270 /// Code adapted by Rene Brun from original HBOOK routine HDIFF
7271 ///
7272 /// NOTE1
7273 /// A good description of the Kolmogorov test can be seen at:
7274 /// http://www.itl.nist.gov/div898/handbook/eda/section3/eda35g.htm
7275 ///
7276 /// NOTE2
7277 /// see also alternative function TH1::Chi2Test
7278 /// The Kolmogorov test is assumed to give better results than Chi2Test
7279 /// in case of histograms with low statistics.
7280 ///
7281 /// NOTE3 (Jan Conrad, Fred James)
7282 /// "The returned value PROB is calculated such that it will be
7283 /// uniformly distributed between zero and one for compatible histograms,
7284 /// provided the data are not binned (or the number of bins is very large
7285 /// compared with the number of events). Users who have access to unbinned
7286 /// data and wish exact confidence levels should therefore not put their data
7287 /// into histograms, but should call directly TMath::KolmogorovTest. On
7288 /// the other hand, since TH1 is a convenient way of collecting data and
7289 /// saving space, this function has been provided. However, the values of
7290 /// PROB for binned data will be shifted slightly higher than expected,
7291 /// depending on the effects of the binning. For example, when comparing two
7292 /// uniform distributions of 500 events in 100 bins, the values of PROB,
7293 /// instead of being exactly uniformly distributed between zero and one, have
7294 /// a mean value of about 0.56. We can apply a useful
7295 /// rule: As long as the bin width is small compared with any significant
7296 /// physical effect (for example the experimental resolution) then the binning
7297 /// cannot have an important effect. Therefore, we believe that for all
7298 /// practical purposes, the probability value PROB is calculated correctly
7299 /// provided the user is aware that:
7300 ///
7301 /// 1. The value of PROB should not be expected to have exactly the correct
7302 /// distribution for binned data.
7303 /// 2. The user is responsible for seeing to it that the bin widths are
7304 /// small compared with any physical phenomena of interest.
7305 /// 3. The effect of binning (if any) is always to make the value of PROB
7306 /// slightly too big. That is, setting an acceptance criterion of (PROB>0.05
7307 /// will assure that at most 5% of truly compatible histograms are rejected,
7308 /// and usually somewhat less."
7309 ///
7310 /// Note also that for GoF test of unbinned data ROOT provides also the class
7311 /// ROOT::Math::GoFTest. The class has also method for doing one sample tests
7312 /// (i.e. comparing the data with a given distribution).
7313 
7314 Double_t TH1::KolmogorovTest(const TH1 *h2, Option_t *option) const
7315 {
7316  TString opt = option;
7317  opt.ToUpper();
7318 
7319  Double_t prob = 0;
7320  TH1 *h1 = (TH1*)this;
7321  if (h2 == 0) return 0;
7322  const TAxis *axis1 = h1->GetXaxis();
7323  const TAxis *axis2 = h2->GetXaxis();
7324  Int_t ncx1 = axis1->GetNbins();
7325  Int_t ncx2 = axis2->GetNbins();
7326 
7327  // Check consistency of dimensions
7328  if (h1->GetDimension() != 1 || h2->GetDimension() != 1) {
7329  Error("KolmogorovTest","Histograms must be 1-D\n");
7330  return 0;
7331  }
7332 
7333  // Check consistency in number of channels
7334  if (ncx1 != ncx2) {
7335  Error("KolmogorovTest","Number of channels is different, %d and %d\n",ncx1,ncx2);
7336  return 0;
7337  }
7338 
7339  // empty the buffer. Probably we could add as an unbinned test
7340  if (fBuffer) ((TH1*)this)->BufferEmpty();
7341 
7342  // Check consistency in channel edges
7343  Double_t difprec = 1e-5;
7344  Double_t diff1 = TMath::Abs(axis1->GetXmin() - axis2->GetXmin());
7345  Double_t diff2 = TMath::Abs(axis1->GetXmax() - axis2->GetXmax());
7346  if (diff1 > difprec || diff2 > difprec) {
7347  Error("KolmogorovTest","histograms with different binning");
7348  return 0;
7349  }
7350 
7351  Bool_t afunc1 = kFALSE;
7352  Bool_t afunc2 = kFALSE;
7353  Double_t sum1 = 0, sum2 = 0;
7354  Double_t ew1, ew2, w1 = 0, w2 = 0;
7355  Int_t bin;
7356  Int_t ifirst = 1;
7357  Int_t ilast = ncx1;
7358  // integral of all bins (use underflow/overflow if option)
7359  if (opt.Contains("U")) ifirst = 0;
7360  if (opt.Contains("O")) ilast = ncx1 +1;
7361  for (bin = ifirst; bin <= ilast; bin++) {
7362  sum1 += h1->RetrieveBinContent(bin);
7363  sum2 += h2->RetrieveBinContent(bin);
7364  ew1 = h1->GetBinError(bin);
7365  ew2 = h2->GetBinError(bin);
7366  w1 += ew1*ew1;
7367  w2 += ew2*ew2;
7368  }
7369  if (sum1 == 0) {
7370  Error("KolmogorovTest","Histogram1 %s integral is zero\n",h1->GetName());
7371  return 0;
7372  }
7373  if (sum2 == 0) {
7374  Error("KolmogorovTest","Histogram2 %s integral is zero\n",h2->GetName());
7375  return 0;
7376  }
7377 
7378  // calculate the effective entries.
7379  // the case when errors are zero (w1 == 0 or w2 ==0) are equivalent to
7380  // compare to a function. In that case the rescaling is done only on sqrt(esum2) or sqrt(esum1)
7381  Double_t esum1 = 0, esum2 = 0;
7382  if (w1 > 0)
7383  esum1 = sum1 * sum1 / w1;
7384  else
7385  afunc1 = kTRUE; // use later for calculating z
7386 
7387  if (w2 > 0)
7388  esum2 = sum2 * sum2 / w2;
7389  else
7390  afunc2 = kTRUE; // use later for calculating z
7391 
7392  if (afunc2 && afunc1) {
7393  Error("KolmogorovTest","Errors are zero for both histograms\n");
7394  return 0;
7395  }
7396 
7397 
7398  Double_t s1 = 1/sum1;
7399  Double_t s2 = 1/sum2;
7400 
7401  // Find largest difference for Kolmogorov Test
7402  Double_t dfmax =0, rsum1 = 0, rsum2 = 0;
7403 
7404  for (bin=ifirst;bin<=ilast;bin++) {
7405  rsum1 += s1*h1->RetrieveBinContent(bin);
7406  rsum2 += s2*h2->RetrieveBinContent(bin);
7407  dfmax = TMath::Max(dfmax,TMath::Abs(rsum1-rsum2));
7408  }
7409 
7410  // Get Kolmogorov probability
7411  Double_t z, prb1=0, prb2=0, prb3=0;
7412 
7413  // case h1 is exact (has zero errors)
7414  if (afunc1)
7415  z = dfmax*TMath::Sqrt(esum2);
7416  // case h2 has zero errors
7417  else if (afunc2)
7418  z = dfmax*TMath::Sqrt(esum1);
7419  else
7420  // for comparison between two data sets
7421  z = dfmax*TMath::Sqrt(esum1*esum2/(esum1+esum2));
7422 
7423  prob = TMath::KolmogorovProb(z);
7424 
7425  // option N to combine normalization makes sense if both afunc1 and afunc2 are false
7426  if (opt.Contains("N") && !(afunc1 || afunc2 ) ) {
7427  // Combine probabilities for shape and normalization,
7428  prb1 = prob;
7429  Double_t d12 = esum1-esum2;
7430  Double_t chi2 = d12*d12/(esum1+esum2);
7431  prb2 = TMath::Prob(chi2,1);
7432  // see Eadie et al., section 11.6.2
7433  if (prob > 0 && prb2 > 0) prob *= prb2*(1-TMath::Log(prob*prb2));
7434  else prob = 0;
7435  }
7436  // X option. Pseudo-experiments post-processor to determine KS probability
7437  const Int_t nEXPT = 1000;
7438  if (opt.Contains("X") && !(afunc1 || afunc2 ) ) {
7439  Double_t dSEXPT;
7440  TH1 *hExpt = (TH1*)(gDirectory ? gDirectory->CloneObject(this,kFALSE) : gROOT->CloneObject(this,kFALSE));
7441  // make nEXPT experiments (this should be a parameter)
7442  prb3 = 0;
7443  for (Int_t i=0; i < nEXPT; i++) {
7444  hExpt->Reset();
7445  hExpt->FillRandom(h1,(Int_t)esum2);
7446  dSEXPT = KolmogorovTest(hExpt,"M");
7447  if (dSEXPT>dfmax) prb3 += 1.0;
7448  }
7449  prb3 /= (Double_t)nEXPT;
7450  delete hExpt;
7451  }
7452 
7453  // debug printout
7454  if (opt.Contains("D")) {
7455  printf(" Kolmo Prob h1 = %s, sum bin content =%g effective entries =%g\n",h1->GetName(),sum1,esum1);
7456  printf(" Kolmo Prob h2 = %s, sum bin content =%g effective entries =%g\n",h2->GetName(),sum2,esum2);
7457  printf(" Kolmo Prob = %g, Max Dist = %g\n",prob,dfmax);
7458  if (opt.Contains("N"))
7459  printf(" Kolmo Prob = %f for shape alone, =%f for normalisation alone\n",prb1,prb2);
7460  if (opt.Contains("X"))
7461  printf(" Kolmo Prob = %f with %d pseudo-experiments\n",prb3,nEXPT);
7462  }
7463  // This numerical error condition should never occur:
7464  if (TMath::Abs(rsum1-1) > 0.002) Warning("KolmogorovTest","Numerical problems with h1=%s\n",h1->GetName());
7465  if (TMath::Abs(rsum2-1) > 0.002) Warning("KolmogorovTest","Numerical problems with h2=%s\n",h2->GetName());
7466 
7467  if(opt.Contains("M")) return dfmax;
7468  else if(opt.Contains("X")) return prb3;
7469  else return prob;
7470 }
7471 
7472 ////////////////////////////////////////////////////////////////////////////////
7473 /// Replace bin contents by the contents of array content
7474 
7475 void TH1::SetContent(const Double_t *content)
7476 {
7478  fTsumw = 0;
7479  for (Int_t i = 0; i < fNcells; ++i) UpdateBinContent(i, content[i]);
7480 }
7481 
7482 ////////////////////////////////////////////////////////////////////////////////
7483 /// Return contour values into array levels if pointer levels is non zero.
7484 ///
7485 /// The function returns the number of contour levels.
7486 /// see GetContourLevel to return one contour only
7487 
7489 {
7490  Int_t nlevels = fContour.fN;
7491  if (levels) {
7492  if (nlevels == 0) {
7493  nlevels = 20;
7494  SetContour(nlevels);
7495  } else {
7496  if (TestBit(kUserContour) == 0) SetContour(nlevels);
7497  }
7498  for (Int_t level=0; level<nlevels; level++) levels[level] = fContour.fArray[level];
7499  }
7500  return nlevels;
7501 }
7502 
7503 ////////////////////////////////////////////////////////////////////////////////
7504 /// Return value of contour number level.
7505 /// Use GetContour to return the array of all contour levels
7506 
7507 Double_t TH1::GetContourLevel(Int_t level) const
7508 {
7509  return (level >= 0 && level < fContour.fN) ? fContour.fArray[level] : 0.0;
7510 }
7511 
7512 ////////////////////////////////////////////////////////////////////////////////
7513 /// Return the value of contour number "level" in Pad coordinates.
7514 /// ie: if the Pad is in log scale along Z it returns le log of the contour level
7515 /// value. See GetContour to return the array of all contour levels
7516 
7518 {
7519  if (level <0 || level >= fContour.fN) return 0;
7520  Double_t zlevel = fContour.fArray[level];
7521 
7522  // In case of user defined contours and Pad in log scale along Z,
7523  // fContour.fArray doesn't contain the log of the contour whereas it does
7524  // in case of equidistant contours.
7525  if (gPad && gPad->GetLogz() && TestBit(kUserContour)) {
7526  if (zlevel <= 0) return 0;
7527  zlevel = TMath::Log10(zlevel);
7528  }
7529  return zlevel;
7530 }
7531 
7532 ////////////////////////////////////////////////////////////////////////////////
7533 /// Set the maximum number of entries to be kept in the buffer.
7534 
7535 void TH1::SetBuffer(Int_t buffersize, Option_t * /*option*/)
7536 {
7537  if (fBuffer) {
7538  BufferEmpty();
7539  delete [] fBuffer;
7540  fBuffer = 0;
7541  }
7542  if (buffersize <= 0) {
7543  fBufferSize = 0;
7544  return;
7545  }
7546  if (buffersize < 100) buffersize = 100;
7547  fBufferSize = 1 + buffersize*(fDimension+1);
7548  fBuffer = new Double_t[fBufferSize];
7549  memset(fBuffer,0,sizeof(Double_t)*fBufferSize);
7550 }
7551 
7552 ////////////////////////////////////////////////////////////////////////////////
7553 /// Set the number and values of contour levels.
7554 ///
7555 /// By default the number of contour levels is set to 20. The contours values
7556 /// in the array "levels" should be specified in increasing order.
7557 ///
7558 /// if argument levels = 0 or missing, equidistant contours are computed
7559 
7560 void TH1::SetContour(Int_t nlevels, const Double_t *levels)
7561 {
7562  Int_t level;
7564  if (nlevels <=0 ) {
7565  fContour.Set(0);
7566  return;
7567  }
7568  fContour.Set(nlevels);
7569 
7570  // - Contour levels are specified
7571  if (levels) {
7573  for (level=0; level<nlevels; level++) fContour.fArray[level] = levels[level];
7574  } else {
7575  // - contour levels are computed automatically as equidistant contours
7576  Double_t zmin = GetMinimum();
7577  Double_t zmax = GetMaximum();
7578  if ((zmin == zmax) && (zmin != 0)) {
7579  zmax += 0.01*TMath::Abs(zmax);
7580  zmin -= 0.01*TMath::Abs(zmin);
7581  }
7582  Double_t dz = (zmax-zmin)/Double_t(nlevels);
7583  if (gPad && gPad->GetLogz()) {
7584  if (zmax <= 0) return;
7585  if (zmin <= 0) zmin = 0.001*zmax;
7586  zmin = TMath::Log10(zmin);
7587  zmax = TMath::Log10(zmax);
7588  dz = (zmax-zmin)/Double_t(nlevels);
7589  }
7590  for (level=0; level<nlevels; level++) {
7591  fContour.fArray[level] = zmin + dz*Double_t(level);
7592  }
7593  }
7594 }
7595 
7596 ////////////////////////////////////////////////////////////////////////////////
7597 /// Set value for one contour level.
7598 
7599 void TH1::SetContourLevel(Int_t level, Double_t value)
7600 {
7601  if (level < 0 || level >= fContour.fN) return;
7603  fContour.fArray[level] = value;
7604 }
7605 
7606 ////////////////////////////////////////////////////////////////////////////////
7607 /// Return maximum value smaller than maxval of bins in the range,
7608 /// unless the value has been overridden by TH1::SetMaximum,
7609 /// in which case it returns that value. (This happens, for example,
7610 /// when the histogram is drawn and the y or z axis limits are changed
7611 ///
7612 /// To get the maximum value of bins in the histogram regardless of
7613 /// whether the value has been overridden, use
7614 ///
7615 /// ~~~ {.cpp}
7616 /// h->GetBinContent(h->GetMaximumBin())
7617 /// ~~~
7618 
7619 Double_t TH1::GetMaximum(Double_t maxval) const
7620 {
7621  if (fMaximum != -1111) return fMaximum;
7622 
7623  // empty the buffer
7624  if (fBuffer) ((TH1*)this)->BufferEmpty();
7625 
7626  Int_t bin, binx, biny, binz;
7627  Int_t xfirst = fXaxis.GetFirst();
7628  Int_t xlast = fXaxis.GetLast();
7629  Int_t yfirst = fYaxis.GetFirst();
7630  Int_t ylast = fYaxis.GetLast();
7631  Int_t zfirst = fZaxis.GetFirst();
7632  Int_t zlast = fZaxis.GetLast();
7633  Double_t maximum = -FLT_MAX, value;
7634  for (binz=zfirst;binz<=zlast;binz++) {
7635  for (biny=yfirst;biny<=ylast;biny++) {
7636  for (binx=xfirst;binx<=xlast;binx++) {
7637  bin = GetBin(binx,biny,binz);
7638  value = RetrieveBinContent(bin);
7639  if (value > maximum && value < maxval) maximum = value;
7640  }
7641  }
7642  }
7643  return maximum;
7644 }
7645 
7646 ////////////////////////////////////////////////////////////////////////////////
7647 /// Return location of bin with maximum value in the range.
7648 
7649 Int_t TH1::GetMaximumBin() const
7650 {
7651  Int_t locmax, locmay, locmaz;
7652  return GetMaximumBin(locmax, locmay, locmaz);
7653 }
7654 
7655 ////////////////////////////////////////////////////////////////////////////////
7656 /// Return location of bin with maximum value in the range.
7657 
7658 Int_t TH1::GetMaximumBin(Int_t &locmax, Int_t &locmay, Int_t &locmaz) const
7659 {
7660  // empty the buffer
7661  if (fBuffer) ((TH1*)this)->BufferEmpty();
7662 
7663  Int_t bin, binx, biny, binz;
7664  Int_t locm;
7665  Int_t xfirst = fXaxis.GetFirst();
7666  Int_t xlast = fXaxis.GetLast();
7667  Int_t yfirst = fYaxis.GetFirst();
7668  Int_t ylast = fYaxis.GetLast();
7669  Int_t zfirst = fZaxis.GetFirst();
7670  Int_t zlast = fZaxis.GetLast();
7671  Double_t maximum = -FLT_MAX, value;
7672  locm = locmax = locmay = locmaz = 0;
7673  for (binz=zfirst;binz<=zlast;binz++) {
7674  for (biny=yfirst;biny<=ylast;biny++) {
7675  for (binx=xfirst;binx<=xlast;binx++) {
7676  bin = GetBin(binx,biny,binz);
7677  value = RetrieveBinContent(bin);
7678  if (value > maximum) {
7679  maximum = value;
7680  locm = bin;
7681  locmax = binx;
7682  locmay = biny;
7683  locmaz = binz;
7684  }
7685  }
7686  }
7687  }
7688  return locm;
7689 }
7690 
7691 ////////////////////////////////////////////////////////////////////////////////
7692 /// Return minimum value larger than minval of bins in the range,
7693 /// unless the value has been overridden by TH1::SetMinimum,
7694 /// in which case it returns that value. (This happens, for example,
7695 /// when the histogram is drawn and the y or z axis limits are changed
7696 ///
7697 /// To get the minimum value of bins in the histogram regardless of
7698 /// whether the value has been overridden, use
7699 ///
7700 /// ~~~ {.cpp}
7701 /// h->GetBinContent(h->GetMinimumBin())
7702 /// ~~~
7703 
7704 Double_t TH1::GetMinimum(Double_t minval) const
7705 {
7706  if (fMinimum != -1111) return fMinimum;
7707 
7708  // empty the buffer
7709  if (fBuffer) ((TH1*)this)->BufferEmpty();
7710 
7711  Int_t bin, binx, biny, binz;
7712  Int_t xfirst = fXaxis.GetFirst();
7713  Int_t xlast = fXaxis.GetLast();
7714  Int_t yfirst = fYaxis.GetFirst();
7715  Int_t ylast = fYaxis.GetLast();
7716  Int_t zfirst = fZaxis.GetFirst();
7717  Int_t zlast = fZaxis.GetLast();
7718  Double_t minimum=FLT_MAX, value;
7719  for (binz=zfirst;binz<=zlast;binz++) {
7720  for (biny=yfirst;biny<=ylast;biny++) {
7721  for (binx=xfirst;binx<=xlast;binx++) {
7722  bin = GetBin(binx,biny,binz);
7723  value = RetrieveBinContent(bin);
7724  if (value < minimum && value > minval) minimum = value;
7725  }
7726  }
7727  }
7728  return minimum;
7729 }
7730 
7731 ////////////////////////////////////////////////////////////////////////////////
7732 /// Return location of bin with minimum value in the range.
7733 
7734 Int_t TH1::GetMinimumBin() const
7735 {
7736  Int_t locmix, locmiy, locmiz;
7737  return GetMinimumBin(locmix, locmiy, locmiz);
7738 }
7739 
7740 ////////////////////////////////////////////////////////////////////////////////
7741 /// Return location of bin with minimum value in the range.
7742 
7743 Int_t TH1::GetMinimumBin(Int_t &locmix, Int_t &locmiy, Int_t &locmiz) const
7744 {
7745  // empty the buffer
7746  if (fBuffer) ((TH1*)this)->BufferEmpty();
7747 
7748  Int_t bin, binx, biny, binz;
7749  Int_t locm;
7750  Int_t xfirst = fXaxis.GetFirst();
7751  Int_t xlast = fXaxis.GetLast();
7752  Int_t yfirst = fYaxis.GetFirst();
7753  Int_t ylast = fYaxis.GetLast();
7754  Int_t zfirst = fZaxis.GetFirst();
7755  Int_t zlast = fZaxis.GetLast();
7756  Double_t minimum = FLT_MAX, value;
7757  locm = locmix = locmiy = locmiz = 0;
7758  for (binz=zfirst;binz<=zlast;binz++) {
7759  for (biny=yfirst;biny<=ylast;biny++) {
7760  for (binx=xfirst;binx<=xlast;binx++) {
7761  bin = GetBin(binx,biny,binz);
7762  value = RetrieveBinContent(bin);
7763  if (value < minimum) {
7764  minimum = value;
7765  locm = bin;
7766  locmix = binx;
7767  locmiy = biny;
7768  locmiz = binz;
7769  }
7770  }
7771  }
7772  }
7773  return locm;
7774 }
7775 
7776 ///////////////////////////////////////////////////////////////////////////////
7777 /// Retrieve the minimum and maximum values in the histogram
7778 ///
7779 /// This will not return a cached value and will always search the
7780 /// histogram for the min and max values. The user can condition whether
7781 /// or not to call this with the GetMinimumStored() and GetMaximumStored()
7782 /// methods. If the cache is empty, then the value will be -1111. Users
7783 /// can then use the SetMinimum() or SetMaximum() methods to cache the results.
7784 /// For example, the following recipe will make efficient use of this method
7785 /// and the cached minimum and maximum values.
7786 //
7787 /// \code{.cpp}
7788 /// Double_t currentMin = pHist->GetMinimumStored();
7789 /// Double_t currentMax = pHist->GetMaximumStored();
7790 /// if ((currentMin == -1111) || (currentMax == -1111)) {
7791 /// pHist->GetMinimumAndMaximum(currentMin, currentMax);
7792 /// pHist->SetMinimum(currentMin);
7793 /// pHist->SetMaximum(currentMax);
7794 /// }
7795 /// \endcode
7796 ///
7797 /// \param min reference to variable that will hold found minimum value
7798 /// \param max reference to varaible that will hold found maximum value
7799 ///
7800 void TH1::GetMinimumAndMaximum(Double_t& min, Double_t& max) const
7801 {
7802  // empty the buffer
7803  if (fBuffer) ((TH1*)this)->BufferEmpty();
7804 
7805  Int_t bin, binx, biny, binz;
7806  Int_t xfirst = fXaxis.GetFirst();
7807  Int_t xlast = fXaxis.GetLast();
7808  Int_t yfirst = fYaxis.GetFirst();
7809  Int_t ylast = fYaxis.GetLast();
7810  Int_t zfirst = fZaxis.GetFirst();
7811  Int_t zlast = fZaxis.GetLast();
7812  min=FLT_MAX;
7813  max=FLT_MIN;
7814  Double_t value;
7815  for (binz=zfirst;binz<=zlast;binz++) {
7816  for (biny=yfirst;biny<=ylast;biny++) {
7817  for (binx=xfirst;binx<=xlast;binx++) {
7818  bin = GetBin(binx,biny,binz);
7819  value = RetrieveBinContent(bin);
7820  if (value < min) min = value;
7821  if (value > max) max = value;
7822  }
7823  }
7824  }
7825 }
7826 
7827 ////////////////////////////////////////////////////////////////////////////////
7828 /// Redefine x axis parameters.
7829 ///
7830 /// The X axis parameters are modified.
7831 /// The bins content array is resized
7832 /// if errors (Sumw2) the errors array is resized
7833 /// The previous bin contents are lost
7834 /// To change only the axis limits, see TAxis::SetRange
7835 
7836 void TH1::SetBins(Int_t nx, Double_t xmin, Double_t xmax)
7837 {
7838  if (GetDimension() != 1) {
7839  Error("SetBins","Operation only valid for 1-d histograms");
7840  return;
7841  }
7842  fXaxis.SetRange(0,0);
7843  fXaxis.Set(nx,xmin,xmax);
7844  fYaxis.Set(1,0,1);
7845  fZaxis.Set(1,0,1);
7846  fNcells = nx+2;
7847  SetBinsLength(fNcells);
7848  if (fSumw2.fN) {
7849  fSumw2.Set(fNcells);
7850  }
7851 }
7852 
7853 ////////////////////////////////////////////////////////////////////////////////
7854 /// Redefine x axis parameters with variable bin sizes.
7855 ///
7856 /// The X axis parameters are modified.
7857 /// The bins content array is resized
7858 /// if errors (Sumw2) the errors array is resized
7859 /// The previous bin contents are lost
7860 /// To change only the axis limits, see TAxis::SetRange
7861 /// xBins is supposed to be of length nx+1
7862 
7863 void TH1::SetBins(Int_t nx, const Double_t *xBins)
7864 {
7865  if (GetDimension() != 1) {
7866  Error("SetBins","Operation only valid for 1-d histograms");
7867  return;
7868  }
7869  fXaxis.SetRange(0,0);
7870  fXaxis.Set(nx,xBins);
7871  fYaxis.Set(1,0,1);
7872  fZaxis.Set(1,0,1);
7873  fNcells = nx+2;
7874  SetBinsLength(fNcells);
7875  if (fSumw2.fN) {
7876  fSumw2.Set(fNcells);
7877  }
7878 }
7879 
7880 ////////////////////////////////////////////////////////////////////////////////
7881 /// Redefine x and y axis parameters.
7882 ///
7883 /// The X and Y axis parameters are modified.
7884 /// The bins content array is resized
7885 /// if errors (Sumw2) the errors array is resized
7886 /// The previous bin contents are lost
7887 /// To change only the axis limits, see TAxis::SetRange
7888 
7889 void TH1::SetBins(Int_t nx, Double_t xmin, Double_t xmax, Int_t ny, Double_t ymin, Double_t ymax)
7890 {
7891  if (GetDimension() != 2) {
7892  Error("SetBins","Operation only valid for 2-D histograms");
7893  return;
7894  }
7895  fXaxis.SetRange(0,0);
7896  fYaxis.SetRange(0,0);
7897  fXaxis.Set(nx,xmin,xmax);
7898  fYaxis.Set(ny,ymin,ymax);
7899  fZaxis.Set(1,0,1);
7900  fNcells = (nx+2)*(ny+2);
7901  SetBinsLength(fNcells);
7902  if (fSumw2.fN) {
7903  fSumw2.Set(fNcells);
7904  }
7905 }
7906 
7907 ////////////////////////////////////////////////////////////////////////////////
7908 /// Redefine x and y axis parameters with variable bin sizes.
7909 ///
7910 /// The X and Y axis parameters are modified.
7911 /// The bins content array is resized
7912 /// if errors (Sumw2) the errors array is resized
7913 /// The previous bin contents are lost
7914 /// To change only the axis limits, see TAxis::SetRange
7915 /// xBins is supposed to be of length nx+1, yBins is supposed to be of length ny+1
7916 
7917 void TH1::SetBins(Int_t nx, const Double_t *xBins, Int_t ny, const Double_t *yBins)
7918 {
7919  if (GetDimension() != 2) {
7920  Error("SetBins","Operation only valid for 2-D histograms");
7921  return;
7922  }
7923  fXaxis.SetRange(0,0);
7924  fYaxis.SetRange(0,0);
7925  fXaxis.Set(nx,xBins);
7926  fYaxis.Set(ny,yBins);
7927  fZaxis.Set(1,0,1);
7928  fNcells = (nx+2)*(ny+2);
7929  SetBinsLength(fNcells);
7930  if (fSumw2.fN) {
7931  fSumw2.Set(fNcells);
7932  }
7933 }
7934 
7935 ////////////////////////////////////////////////////////////////////////////////
7936 /// Redefine x, y and z axis parameters.
7937 ///
7938 /// The X, Y and Z axis parameters are modified.
7939 /// The bins content array is resized
7940 /// if errors (Sumw2) the errors array is resized
7941 /// The previous bin contents are lost
7942 /// To change only the axis limits, see TAxis::SetRange
7943 
7944 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)
7945 {
7946  if (GetDimension() != 3) {
7947  Error("SetBins","Operation only valid for 3-D histograms");
7948  return;
7949  }
7950  fXaxis.SetRange(0,0);
7951  fYaxis.SetRange(0,0);
7952  fZaxis.SetRange(0,0);
7953  fXaxis.Set(nx,xmin,xmax);
7954  fYaxis.Set(ny,ymin,ymax);
7955  fZaxis.Set(nz,zmin,zmax);
7956  fNcells = (nx+2)*(ny+2)*(nz+2);
7957  SetBinsLength(fNcells);
7958  if (fSumw2.fN) {
7959  fSumw2.Set(fNcells);
7960  }
7961 }
7962 
7963 ////////////////////////////////////////////////////////////////////////////////
7964 /// Redefine x, y and z axis parameters with variable bin sizes.
7965 ///
7966 /// The X, Y and Z axis parameters are modified.
7967 /// The bins content array is resized
7968 /// if errors (Sumw2) the errors array is resized
7969 /// The previous bin contents are lost
7970 /// To change only the axis limits, see TAxis::SetRange
7971 /// xBins is supposed to be of length nx+1, yBins is supposed to be of length ny+1,
7972 /// zBins is supposed to be of length nz+1
7973 
7974 void TH1::SetBins(Int_t nx, const Double_t *xBins, Int_t ny, const Double_t *yBins, Int_t nz, const Double_t *zBins)
7975 {
7976  if (GetDimension() != 3) {
7977  Error("SetBins","Operation only valid for 3-D histograms");
7978  return;
7979  }
7980  fXaxis.SetRange(0,0);
7981  fYaxis.SetRange(0,0);
7982  fZaxis.SetRange(0,0);
7983  fXaxis.Set(nx,xBins);
7984  fYaxis.Set(ny,yBins);
7985  fZaxis.Set(nz,zBins);
7986  fNcells = (nx+2)*(ny+2)*(nz+2);
7987  SetBinsLength(fNcells);
7988  if (fSumw2.fN) {
7989  fSumw2.Set(fNcells);
7990  }
7991 }
7992 
7993 ////////////////////////////////////////////////////////////////////////////////
7994 /// By default when an histogram is created, it is added to the list
7995 /// of histogram objects in the current directory in memory.
7996 /// Remove reference to this histogram from current directory and add
7997 /// reference to new directory dir. dir can be 0 in which case the
7998 /// histogram does not belong to any directory.
7999 ///
8000 /// Note that the directory is not a real property of the histogram and
8001 /// it will not be copied when the histogram is copied or cloned.
8002 /// If the user wants to have the copied (cloned) histogram in the same
8003 /// directory, he needs to set again the directory using SetDirectory to the
8004 /// copied histograms
8005 
8006 void TH1::SetDirectory(TDirectory *dir)
8007 {
8008  if (fDirectory == dir) return;
8009  if (fDirectory) fDirectory->Remove(this);
8010  fDirectory = dir;
8011  if (fDirectory) fDirectory->Append(this);
8012 }
8013 
8014 ////////////////////////////////////////////////////////////////////////////////
8015 /// Replace bin errors by values in array error.
8016 
8017 void TH1::SetError(const Double_t *error)
8018 {
8019  for (Int_t i = 0; i < fNcells; ++i) SetBinError(i, error[i]);
8020 }
8021 
8022 ////////////////////////////////////////////////////////////////////////////////
8023 /// Change the name of this histogram
8024 ///
8025 
8026 void TH1::SetName(const char *name)
8027 {
8028  // Histograms are named objects in a THashList.
8029  // We must update the hashlist if we change the name
8030  // We protect this operation
8032  if (fDirectory) fDirectory->Remove(this);
8033  fName = name;
8034  if (fDirectory) fDirectory->Append(this);
8035 }
8036 
8037 ////////////////////////////////////////////////////////////////////////////////
8038 /// Change the name and title of this histogram
8039 
8040 void TH1::SetNameTitle(const char *name, const char *title)
8041 {
8042  // Histograms are named objects in a THashList.
8043  // We must update the hashlist if we change the name
8044  SetName(name);
8045  SetTitle(title);
8046 }
8047 
8048 ////////////////////////////////////////////////////////////////////////////////
8049 /// Set statistics option on/off
8050 ///
8051 /// By default, the statistics box is drawn.
8052 /// The paint options can be selected via gStyle->SetOptStats.
8053 /// This function sets/resets the kNoStats bin in the histogram object.
8054 /// It has priority over the Style option.
8055 
8056 void TH1::SetStats(Bool_t stats)
8057 {
8059  if (!stats) {
8060  SetBit(kNoStats);
8061  //remove the "stats" object from the list of functions
8062  if (fFunctions) {
8063  TObject *obj = fFunctions->FindObject("stats");
8064  if (obj) {
8065  fFunctions->Remove(obj);
8066  delete obj;
8067  }
8068  }
8069  }
8070 }
8071 
8072 ////////////////////////////////////////////////////////////////////////////////
8073 /// Create structure to store sum of squares of weights.
8074 ///
8075 /// if histogram is already filled, the sum of squares of weights
8076 /// is filled with the existing bin contents
8077 ///
8078 /// The error per bin will be computed as sqrt(sum of squares of weight)
8079 /// for each bin.
8080 ///
8081 /// This function is automatically called when the histogram is created
8082 /// if the static function TH1::SetDefaultSumw2 has been called before.
8083 /// If flag = false the structure is deleted
8084 
8085 void TH1::Sumw2(Bool_t flag)
8086 {
8087  if (!flag) {
8088  // clear the array if existing - do nothing otherwise
8089  if (fSumw2.fN > 0 ) fSumw2.Set(0);
8090  return;
8091  }
8092 
8093  if (fSumw2.fN == fNcells) {
8094  if (!fgDefaultSumw2 )
8095  Warning("Sumw2","Sum of squares of weights structure already created");
8096  return;
8097  }
8098 
8099  fSumw2.Set(fNcells);
8100 
8101  // empty the buffer
8102  if (fBuffer) BufferEmpty();
8103 
8104  if (fEntries > 0)
8105  for (Int_t i = 0; i < fNcells; ++i)
8107 }
8108 
8109 ////////////////////////////////////////////////////////////////////////////////
8110 /// Return pointer to function with name.
8111 ///
8112 ///
8113 /// Functions such as TH1::Fit store the fitted function in the list of
8114 /// functions of this histogram.
8115 
8116 TF1 *TH1::GetFunction(const char *name) const
8117 {
8118  return (TF1*)fFunctions->FindObject(name);
8119 }
8120 
8121 ////////////////////////////////////////////////////////////////////////////////
8122 /// Return value of error associated to bin number bin.
8123 ///
8124 /// if the sum of squares of weights has been defined (via Sumw2),
8125 /// this function returns the sqrt(sum of w2).
8126 /// otherwise it returns the sqrt(contents) for this bin.
8127 
8128 Double_t TH1::GetBinError(Int_t bin) const
8129 {
8130  if (bin < 0) bin = 0;
8131  if (bin >= fNcells) bin = fNcells-1;
8132  if (fBuffer) ((TH1*)this)->BufferEmpty();
8133  if (fSumw2.fN) return TMath::Sqrt(fSumw2.fArray[bin]);
8134 
8136 }
8137 
8138 ////////////////////////////////////////////////////////////////////////////////
8139 /// Return lower error associated to bin number bin.
8140 ///
8141 /// The error will depend on the statistic option used will return
8142 /// the binContent - lower interval value
8143 
8145 {
8146  if (fBinStatErrOpt == kNormal) return GetBinError(bin);
8147  // in case of weighted histogram check if it is really weighted
8148  if (fSumw2.fN && fTsumw != fTsumw2) return GetBinError(bin);
8149 
8150  if (bin < 0) bin = 0;
8151  if (bin >= fNcells) bin = fNcells-1;
8152  if (fBuffer) ((TH1*)this)->BufferEmpty();
8153 
8154  Double_t alpha = 1.- 0.682689492;
8155  if (fBinStatErrOpt == kPoisson2) alpha = 0.05;
8156 
8157  Double_t c = RetrieveBinContent(bin);
8158  Int_t n = int(c);
8159  if (n < 0) {
8160  Warning("GetBinErrorLow","Histogram has negative bin content-force usage to normal errors");
8161  ((TH1*)this)->fBinStatErrOpt = kNormal;
8162  return GetBinError(bin);
8163  }
8164 
8165  if (n == 0) return 0;
8166  return c - ROOT::Math::gamma_quantile( alpha/2, n, 1.);
8167 }
8168 
8169 ////////////////////////////////////////////////////////////////////////////////
8170 /// Return upper error associated to bin number bin.
8171 ///
8172 /// The error will depend on the statistic option used will return
8173 /// the binContent - upper interval value
8174 
8176 {
8177  if (fBinStatErrOpt == kNormal) return GetBinError(bin);
8178  // in case of weighted histogram check if it is really weighted
8179  if (fSumw2.fN && fTsumw != fTsumw2) return GetBinError(bin);
8180  if (bin < 0) bin = 0;
8181  if (bin >= fNcells) bin = fNcells-1;
8182  if (fBuffer) ((TH1*)this)->BufferEmpty();
8183 
8184  Double_t alpha = 1.- 0.682689492;
8185  if (fBinStatErrOpt == kPoisson2) alpha = 0.05;
8186 
8187  Double_t c = RetrieveBinContent(bin);
8188  Int_t n = int(c);
8189  if (n < 0) {
8190  Warning("GetBinErrorUp","Histogram has negative bin content-force usage to normal errors");
8191  ((TH1*)this)->fBinStatErrOpt = kNormal;
8192  return GetBinError(bin);
8193  }
8194 
8195  // for N==0 return an upper limit at 0.68 or (1-alpha)/2 ?
8196  // decide to return always (1-alpha)/2 upper interval
8197  //if (n == 0) return ROOT::Math::gamma_quantile_c(alpha,n+1,1);
8198  return ROOT::Math::gamma_quantile_c( alpha/2, n+1, 1) - c;
8199 }
8200 
8201 //L.M. These following getters are useless and should be probably deprecated
8202 ////////////////////////////////////////////////////////////////////////////////
8203 /// Return bin center for 1D histogram.
8204 /// Better to use h1.GetXaxis().GetBinCenter(bin)
8205 
8206 Double_t TH1::GetBinCenter(Int_t bin) const
8207 {
8208  if (fDimension == 1) return fXaxis.GetBinCenter(bin);
8209  Error("GetBinCenter","Invalid method for a %d-d histogram - return a NaN",fDimension);
8210  return TMath::QuietNaN();
8211 }
8212 
8213 ////////////////////////////////////////////////////////////////////////////////
8214 /// Return bin lower edge for 1D histogram.
8215 /// Better to use h1.GetXaxis().GetBinLowEdge(bin)
8216 
8218 {
8219  if (fDimension == 1) return fXaxis.GetBinLowEdge(bin);
8220  Error("GetBinLowEdge","Invalid method for a %d-d histogram - return a NaN",fDimension);
8221  return TMath::QuietNaN();
8222 }
8223 
8224 ////////////////////////////////////////////////////////////////////////////////
8225 /// Return bin width for 1D histogram.
8226 /// Better to use h1.GetXaxis().GetBinWidth(bin)
8227 
8228 Double_t TH1::GetBinWidth(Int_t bin) const
8229 {
8230  if (fDimension == 1) return fXaxis.GetBinWidth(bin);
8231  Error("GetBinWidth","Invalid method for a %d-d histogram - return a NaN",fDimension);
8232  return TMath::QuietNaN();
8233 }
8234 
8235 ////////////////////////////////////////////////////////////////////////////////
8236 /// Fill array with center of bins for 1D histogram
8237 /// Better to use h1.GetXaxis().GetCenter(center)
8238 
8239 void TH1::GetCenter(Double_t *center) const
8240 {
8241  if (fDimension == 1) {
8242  fXaxis.GetCenter(center);
8243  return;
8244  }
8245  Error("GetCenter","Invalid method for a %d-d histogram ",fDimension);
8246 }
8247 
8248 ////////////////////////////////////////////////////////////////////////////////
8249 /// Fill array with low edge of bins for 1D histogram
8250 /// Better to use h1.GetXaxis().GetLowEdge(edge)
8251 
8252 void TH1::GetLowEdge(Double_t *edge) const
8253 {
8254  if (fDimension == 1) {
8255  fXaxis.GetLowEdge(edge);
8256  return;
8257  }
8258  Error("GetLowEdge","Invalid method for a %d-d histogram ",fDimension);
8259 }
8260 
8261 ////////////////////////////////////////////////////////////////////////////////
8262 /// See convention for numbering bins in TH1::GetBin
8263 
8264 void TH1::SetBinError(Int_t bin, Double_t error)
8265 {
8266  if (!fSumw2.fN) Sumw2();
8267  if (bin < 0 || bin>= fSumw2.fN) return;
8268  fSumw2.fArray[bin] = error * error;
8269 }
8270 
8271 ////////////////////////////////////////////////////////////////////////////////
8272 /// Set bin content
8273 /// see convention for numbering bins in TH1::GetBin
8274 /// In case the bin number is greater than the number of bins and
8275 /// the timedisplay option is set or CanExtendAllAxes(),
8276 /// the number of bins is automatically doubled to accommodate the new bin
8277 
8278 void TH1::SetBinContent(Int_t bin, Double_t content)
8279 {
8281  fTsumw = 0;
8282  if (bin < 0) return;
8283  if (bin >= fNcells-1) {
8284  if (fXaxis.GetTimeDisplay() || CanExtendAllAxes() ) {
8285  while (bin >= fNcells-1) LabelsInflate();
8286  } else {
8287  if (bin == fNcells-1) UpdateBinContent(bin, content);
8288  return;
8289  }
8290  }
8291  UpdateBinContent(bin, content);
8292 }
8293 
8294 ////////////////////////////////////////////////////////////////////////////////
8295 /// See convention for numbering bins in TH1::GetBin
8296 
8297 void TH1::SetBinError(Int_t binx, Int_t biny, Double_t error)
8298 {
8299  if (binx < 0 || binx > fXaxis.GetNbins() + 1) return;
8300  if (biny < 0 || biny > fYaxis.GetNbins() + 1) return;
8301  SetBinError(GetBin(binx, biny), error);
8302 }
8303 
8304 ////////////////////////////////////////////////////////////////////////////////
8305 /// See convention for numbering bins in TH1::GetBin
8306 
8307 void TH1::SetBinError(Int_t binx, Int_t biny, Int_t binz, Double_t error)
8308 {
8309  if (binx < 0 || binx > fXaxis.GetNbins() + 1) return;
8310  if (biny < 0 || biny > fYaxis.GetNbins() + 1) return;
8311  if (binz < 0 || binz > fZaxis.GetNbins() + 1) return;
8312  SetBinError(GetBin(binx, biny, binz), error);
8313 }
8314 
8315 ////////////////////////////////////////////////////////////////////////////////
8316 /// This function calculates the background spectrum in this histogram.
8317 /// The background is returned as a histogram.
8318 ///
8319 /// \param[in] niter number of iterations (default value = 2)
8320 /// Increasing niter make the result smoother and lower.
8321 /// \param[in] option may contain one of the following options
8322 /// - to set the direction parameter
8323 /// "BackDecreasingWindow". By default the direction is BackIncreasingWindow
8324 /// - filterOrder-order of clipping filter (default "BackOrder2")
8325 /// possible values= "BackOrder4" "BackOrder6" "BackOrder8"
8326 /// - "nosmoothing" - if selected, the background is not smoothed
8327 /// By default the background is smoothed.
8328 /// - smoothWindow - width of smoothing window, (default is "BackSmoothing3")
8329 /// possible values= "BackSmoothing5" "BackSmoothing7" "BackSmoothing9"
8330 /// "BackSmoothing11" "BackSmoothing13" "BackSmoothing15"
8331 /// - "nocompton" - if selected the estimation of Compton edge
8332 /// will be not be included (by default the compton estimation is set)
8333 /// - "same" if this option is specified, the resulting background
8334 /// histogram is superimposed on the picture in the current pad.
8335 /// This option is given by default.
8336 ///
8337 /// NOTE that the background is only evaluated in the current range of this histogram.
8338 /// i.e., if this has a bin range (set via h->GetXaxis()->SetRange(binmin, binmax),
8339 /// the returned histogram will be created with the same number of bins
8340 /// as this input histogram, but only bins from binmin to binmax will be filled
8341 /// with the estimated background.
8342 
8343 TH1 *TH1::ShowBackground(Int_t niter, Option_t *option)
8344 {
8346  return (TH1*)gROOT->ProcessLineFast(Form("TSpectrum::StaticBackground((TH1*)0x%lx,%d,\"%s\")",
8347  (ULong_t)this, niter, option));
8348 }
8349 
8350 ////////////////////////////////////////////////////////////////////////////////
8351 /// Interface to TSpectrum::Search.
8352 /// The function finds peaks in this histogram where the width is > sigma
8353 /// and the peak maximum greater than threshold*maximum bin content of this.
8354 /// For more details see TSpectrum::Search.
8355 /// Note the difference in the default value for option compared to TSpectrum::Search
8356 /// option="" by default (instead of "goff").
8357 
8358 Int_t TH1::ShowPeaks(Double_t sigma, Option_t *option, Double_t threshold)
8359 {
8360  return (Int_t)gROOT->ProcessLineFast(Form("TSpectrum::StaticSearch((TH1*)0x%lx,%g,\"%s\",%g)",
8361  (ULong_t)this, sigma, option, threshold));
8362 }
8363 
8364 ////////////////////////////////////////////////////////////////////////////////
8365 /// For a given transform (first parameter), fills the histogram (second parameter)
8366 /// with the transform output data, specified in the third parameter
8367 /// If the 2nd parameter h_output is empty, a new histogram (TH1D or TH2D) is created
8368 /// and the user is responsible for deleting it.
8369 ///
8370 /// Available options:
8371 /// - "RE" - real part of the output
8372 /// - "IM" - imaginary part of the output
8373 /// - "MAG" - magnitude of the output
8374 /// - "PH" - phase of the output
8375 
8376 TH1* TH1::TransformHisto(TVirtualFFT *fft, TH1* h_output, Option_t *option)
8377 {
8378  if (!fft || !fft->GetN() ) {
8379  ::Error("TransformHisto","Invalid FFT transform class");
8380  return 0;
8381  }
8382 
8383  if (fft->GetNdim()>2){
8384  ::Error("TransformHisto","Only 1d and 2D transform are supported");
8385  return 0;
8386  }
8387  Int_t binx,biny;
8388  TString opt = option;
8389  opt.ToUpper();
8390  Int_t *n = fft->GetN();
8391  TH1 *hout=0;
8392  if (h_output) {
8393  hout = h_output;
8394  }
8395  else {
8396  TString name = TString::Format("out_%s", opt.Data());
8397  if (fft->GetNdim()==1)
8398  hout = new TH1D(name, name,n[0], 0, n[0]);
8399  else if (fft->GetNdim()==2)
8400  hout = new TH2D(name, name, n[0], 0, n[0], n[1], 0, n[1]);
8401  }
8402  R__ASSERT(hout != 0);
8403  TString type=fft->GetType();
8404  Int_t ind[2];
8405  if (opt.Contains("RE")){
8406  if (type.Contains("2C") || type.Contains("2HC")) {
8407  Double_t re, im;
8408  for (binx = 1; binx<=hout->GetNbinsX(); binx++) {
8409  for (biny=1; biny<=hout->GetNbinsY(); biny++) {
8410  ind[0] = binx-1; ind[1] = biny-1;
8411  fft->GetPointComplex(ind, re, im);
8412  hout->SetBinContent(binx, biny, re);
8413  }
8414  }
8415  } else {
8416  for (binx = 1; binx<=hout->GetNbinsX(); binx++) {
8417  for (biny=1; biny<=hout->GetNbinsY(); biny++) {
8418  ind[0] = binx-1; ind[1] = biny-1;
8419  hout->SetBinContent(binx, biny, fft->GetPointReal(ind));
8420  }
8421  }
8422  }
8423  }
8424  if (opt.Contains("IM")) {
8425  if (type.Contains("2C") || type.Contains("2HC")) {
8426  Double_t re, im;
8427  for (binx = 1; binx<=hout->GetNbinsX(); binx++) {
8428  for (biny=1; biny<=hout->GetNbinsY(); biny++) {
8429  ind[0] = binx-1; ind[1] = biny-1;
8430  fft->GetPointComplex(ind, re, im);
8431  hout->SetBinContent(binx, biny, im);
8432  }
8433  }
8434  } else {
8435  ::Error("TransformHisto","No complex numbers in the output");
8436  return 0;
8437  }
8438  }
8439  if (opt.Contains("MA")) {
8440  if (type.Contains("2C") || type.Contains("2HC")) {
8441  Double_t re, im;
8442  for (binx = 1; binx<=hout->GetNbinsX(); binx++) {
8443  for (biny=1; biny<=hout->GetNbinsY(); biny++) {
8444  ind[0] = binx-1; ind[1] = biny-1;
8445  fft->GetPointComplex(ind, re, im);
8446  hout->SetBinContent(binx, biny, TMath::Sqrt(re*re + im*im));
8447  }
8448  }
8449  } else {
8450  for (binx = 1; binx<=hout->GetNbinsX(); binx++) {
8451  for (biny=1; biny<=hout->GetNbinsY(); biny++) {
8452  ind[0] = binx-1; ind[1] = biny-1;
8453  hout->SetBinContent(binx, biny, TMath::Abs(fft->GetPointReal(ind)));
8454  }
8455  }
8456  }
8457  }
8458  if (opt.Contains("PH")) {
8459  if (type.Contains("2C") || type.Contains("2HC")){
8460  Double_t re, im, ph;
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  fft->GetPointComplex(ind, re, im);
8465  if (TMath::Abs(re) > 1e-13){
8466  ph = TMath::ATan(im/re);
8467  //find the correct quadrant
8468  if (re<0 && im<0)
8469  ph -= TMath::Pi();
8470  if (re<0 && im>=0)
8471  ph += TMath::Pi();
8472  } else {
8473  if (TMath::Abs(im) < 1e-13)
8474  ph = 0;
8475  else if (im>0)
8476  ph = TMath::Pi()*0.5;
8477  else
8478  ph = -TMath::Pi()*0.5;
8479  }
8480  hout->SetBinContent(binx, biny, ph);
8481  }
8482  }
8483  } else {
8484  printf("Pure real output, no phase");
8485  return 0;
8486  }
8487  }
8488 
8489  return hout;
8490 }
8491 
8492 ////////////////////////////////////////////////////////////////////////////////
8493 /// Raw retrieval of bin content on internal data structure
8494 /// see convention for numbering bins in TH1::GetBin
8495 
8497 {
8498  AbstractMethod("RetrieveBinContent");
8499  return 0;
8500 }
8501 
8502 ////////////////////////////////////////////////////////////////////////////////
8503 /// Raw update of bin content on internal data structure
8504 /// see convention for numbering bins in TH1::GetBin
8505 
8507 {
8508  AbstractMethod("UpdateBinContent");
8509 }
8510 
8511 ////////////////////////////////////////////////////////////////////////////////
8512 /// Print value overload
8513 
8514 std::string cling::printValue(TH1 *val) {
8515  std::ostringstream strm;
8516  strm << cling::printValue((TObject*)val) << " NbinsX: " << val->GetNbinsX();
8517  return strm.str();
8518 }
8519 
8520 //______________________________________________________________________________
8521 // TH1C methods
8522 // TH1C : histograms with one byte per channel. Maximum bin content = 127
8523 //______________________________________________________________________________
8524 
8525 ClassImp(TH1C)
8526 
8527 ////////////////////////////////////////////////////////////////////////////////
8528 /// Constructor.
8529 
8530 TH1C::TH1C(): TH1(), TArrayC()
8531 {
8533  SetBinsLength(3);
8534  if (fgDefaultSumw2) Sumw2();
8535 }
8536 
8537 ////////////////////////////////////////////////////////////////////////////////
8538 /// Create a 1-Dim histogram with fix bins of type char (one byte per channel)
8539 /// (see TH1::TH1 for explanation of parameters)
8540 
8541 TH1C::TH1C(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
8542 : TH1(name,title,nbins,xlow,xup)
8544  fDimension = 1;
8545  TArrayC::Set(fNcells);
8546 
8547  if (xlow >= xup) SetBuffer(fgBufferSize);
8548  if (fgDefaultSumw2) Sumw2();
8549 }
8550 
8551 ////////////////////////////////////////////////////////////////////////////////
8552 /// Create a 1-Dim histogram with variable bins of type char (one byte per channel)
8553 /// (see TH1::TH1 for explanation of parameters)
8554 
8555 TH1C::TH1C(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
8556 : TH1(name,title,nbins,xbins)
8558  fDimension = 1;
8559  TArrayC::Set(fNcells);
8560  if (fgDefaultSumw2) Sumw2();
8561 }
8562 
8563 ////////////////////////////////////////////////////////////////////////////////
8564 /// Create a 1-Dim histogram with variable bins of type char (one byte per channel)
8565 /// (see TH1::TH1 for explanation of parameters)
8566 
8567 TH1C::TH1C(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
8568 : TH1(name,title,nbins,xbins)
8570  fDimension = 1;
8571  TArrayC::Set(fNcells);
8572  if (fgDefaultSumw2) Sumw2();
8573 }
8574 
8575 ////////////////////////////////////////////////////////////////////////////////
8576 /// Destructor.
8577 
8578 TH1C::~TH1C()
8579 {
8581 
8582 ////////////////////////////////////////////////////////////////////////////////
8583 /// Copy constructor.
8584 
8585 TH1C::TH1C(const TH1C &h1c) : TH1(), TArrayC()
8586 {
8587  ((TH1C&)h1c).Copy(*this);
8588 }
8589 
8590 ////////////////////////////////////////////////////////////////////////////////
8591 /// Increment bin content by 1.
8592 
8593 void TH1C::AddBinContent(Int_t bin)
8594 {
8595  if (fArray[bin] < 127) fArray[bin]++;
8596 }
8597 
8598 ////////////////////////////////////////////////////////////////////////////////
8599 /// Increment bin content by w.
8600 
8601 void TH1C::AddBinContent(Int_t bin, Double_t w)
8602 {
8603  Int_t newval = fArray[bin] + Int_t(w);
8604  if (newval > -128 && newval < 128) {fArray[bin] = Char_t(newval); return;}
8605  if (newval < -127) fArray[bin] = -127;
8606  if (newval > 127) fArray[bin] = 127;
8607 }
8608 
8609 ////////////////////////////////////////////////////////////////////////////////
8610 /// Copy this to newth1
8611 
8612 void TH1C::Copy(TObject &newth1) const
8613 {
8614  TH1::Copy(newth1);
8615 }
8616 
8617 ////////////////////////////////////////////////////////////////////////////////
8618 /// Reset.
8619 
8620 void TH1C::Reset(Option_t *option)
8621 {
8622  TH1::Reset(option);
8623  TArrayC::Reset();
8624 }
8625 
8626 ////////////////////////////////////////////////////////////////////////////////
8627 /// Set total number of bins including under/overflow
8628 /// Reallocate bin contents array
8629 
8630 void TH1C::SetBinsLength(Int_t n)
8631 {
8632  if (n < 0) n = fXaxis.GetNbins() + 2;
8633  fNcells = n;
8634  TArrayC::Set(n);
8635 }
8636 
8637 ////////////////////////////////////////////////////////////////////////////////
8638 /// Operator =
8639 
8640 TH1C& TH1C::operator=(const TH1C &h1)
8641 {
8642  if (this != &h1) ((TH1C&)h1).Copy(*this);
8643  return *this;
8644 }
8645 
8646 ////////////////////////////////////////////////////////////////////////////////
8647 /// Operator *
8648 
8649 TH1C operator*(Double_t c1, const TH1C &h1)
8650 {
8651  TH1C hnew = h1;
8652  hnew.Scale(c1);
8653  hnew.SetDirectory(0);
8654  return hnew;
8655 }
8656 
8657 ////////////////////////////////////////////////////////////////////////////////
8658 /// Operator +
8659 
8660 TH1C operator+(const TH1C &h1, const TH1C &h2)
8661 {
8662  TH1C hnew = h1;
8663  hnew.Add(&h2,1);
8664  hnew.SetDirectory(0);
8665  return hnew;
8666 }
8667 
8668 ////////////////////////////////////////////////////////////////////////////////
8669 /// Operator -
8670 
8671 TH1C operator-(const TH1C &h1, const TH1C &h2)
8672 {
8673  TH1C hnew = h1;
8674  hnew.Add(&h2,-1);
8675  hnew.SetDirectory(0);
8676  return hnew;
8677 }
8678 
8679 ////////////////////////////////////////////////////////////////////////////////
8680 /// Operator *
8681 
8682 TH1C operator*(const TH1C &h1, const TH1C &h2)
8683 {
8684  TH1C hnew = h1;
8685  hnew.Multiply(&h2);
8686  hnew.SetDirectory(0);
8687  return hnew;
8688 }
8689 
8690 ////////////////////////////////////////////////////////////////////////////////
8691 /// Operator /
8692 
8693 TH1C operator/(const TH1C &h1, const TH1C &h2)
8694 {
8695  TH1C hnew = h1;
8696  hnew.Divide(&h2);
8697  hnew.SetDirectory(0);
8698  return hnew;
8699 }
8700 
8701 //______________________________________________________________________________
8702 // TH1S methods
8703 // TH1S : histograms with one short per channel. Maximum bin content = 32767
8704 //______________________________________________________________________________
8705 
8706 ClassImp(TH1S)
8707 
8708 ////////////////////////////////////////////////////////////////////////////////
8709 /// Constructor.
8710 
8711 TH1S::TH1S(): TH1(), TArrayS()
8712 {
8714  SetBinsLength(3);
8715  if (fgDefaultSumw2) Sumw2();
8716 }
8717 
8718 ////////////////////////////////////////////////////////////////////////////////
8719 /// Create a 1-Dim histogram with fix bins of type short
8720 /// (see TH1::TH1 for explanation of parameters)
8721 
8722 TH1S::TH1S(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
8723 : TH1(name,title,nbins,xlow,xup)
8725  fDimension = 1;
8726  TArrayS::Set(fNcells);
8727 
8728  if (xlow >= xup) SetBuffer(fgBufferSize);
8729  if (fgDefaultSumw2) Sumw2();
8730 }
8731 
8732 ////////////////////////////////////////////////////////////////////////////////
8733 /// Create a 1-Dim histogram with variable bins of type short
8734 /// (see TH1::TH1 for explanation of parameters)
8735 
8736 TH1S::TH1S(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
8737 : TH1(name,title,nbins,xbins)
8739  fDimension = 1;
8740  TArrayS::Set(fNcells);
8741  if (fgDefaultSumw2) Sumw2();
8742 }
8743 
8744 ////////////////////////////////////////////////////////////////////////////////
8745 /// Create a 1-Dim histogram with variable bins of type short
8746 /// (see TH1::TH1 for explanation of parameters)
8747 
8748 TH1S::TH1S(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
8749 : TH1(name,title,nbins,xbins)
8751  fDimension = 1;
8752  TArrayS::Set(fNcells);
8753  if (fgDefaultSumw2) Sumw2();
8754 }
8755 
8756 ////////////////////////////////////////////////////////////////////////////////
8757 /// Destructor.
8758 
8759 TH1S::~TH1S()
8760 {
8762 
8763 ////////////////////////////////////////////////////////////////////////////////
8764 /// Copy constructor.
8765 
8766 TH1S::TH1S(const TH1S &h1s) : TH1(), TArrayS()
8767 {
8768  ((TH1S&)h1s).Copy(*this);
8769 }
8770 
8771 ////////////////////////////////////////////////////////////////////////////////
8772 /// Increment bin content by 1.
8773 
8774 void TH1S::AddBinContent(Int_t bin)
8775 {
8776  if (fArray[bin] < 32767) fArray[bin]++;
8777 }
8778 
8779 ////////////////////////////////////////////////////////////////////////////////
8780 /// Increment bin content by w
8781 
8782 void TH1S::AddBinContent(Int_t bin, Double_t w)
8783 {
8784  Int_t newval = fArray[bin] + Int_t(w);
8785  if (newval > -32768 && newval < 32768) {fArray[bin] = Short_t(newval); return;}
8786  if (newval < -32767) fArray[bin] = -32767;
8787  if (newval > 32767) fArray[bin] = 32767;
8788 }
8789 
8790 ////////////////////////////////////////////////////////////////////////////////
8791 /// Copy this to newth1
8792 
8793 void TH1S::Copy(TObject &newth1) const
8794 {
8795  TH1::Copy(newth1);
8796 }
8797 
8798 ////////////////////////////////////////////////////////////////////////////////
8799 /// Reset.
8800 
8801 void TH1S::Reset(Option_t *option)
8802 {
8803  TH1::Reset(option);
8804  TArrayS::Reset();
8805 }
8806 
8807 ////////////////////////////////////////////////////////////////////////////////
8808 /// Set total number of bins including under/overflow
8809 /// Reallocate bin contents array
8810 
8811 void TH1S::SetBinsLength(Int_t n)
8812 {
8813  if (n < 0) n = fXaxis.GetNbins() + 2;
8814  fNcells = n;
8815  TArrayS::Set(n);
8816 }
8817 
8818 ////////////////////////////////////////////////////////////////////////////////
8819 /// Operator =
8820 
8821 TH1S& TH1S::operator=(const TH1S &h1)
8822 {
8823  if (this != &h1) ((TH1S&)h1).Copy(*this);
8824  return *this;
8825 }
8826 
8827 ////////////////////////////////////////////////////////////////////////////////
8828 /// Operator *
8829 
8830 TH1S operator*(Double_t c1, const TH1S &h1)
8831 {
8832  TH1S hnew = h1;
8833  hnew.Scale(c1);
8834  hnew.SetDirectory(0);
8835  return hnew;
8836 }
8837 
8838 ////////////////////////////////////////////////////////////////////////////////
8839 /// Operator +
8840 
8841 TH1S operator+(const TH1S &h1, const TH1S &h2)
8842 {
8843  TH1S hnew = h1;
8844  hnew.Add(&h2,1);
8845  hnew.SetDirectory(0);
8846  return hnew;
8847 }
8848 
8849 ////////////////////////////////////////////////////////////////////////////////
8850 /// Operator -
8851 
8852 TH1S operator-(const TH1S &h1, const TH1S &h2)
8853 {
8854  TH1S hnew = h1;
8855  hnew.Add(&h2,-1);
8856  hnew.SetDirectory(0);
8857  return hnew;
8858 }
8859 
8860 ////////////////////////////////////////////////////////////////////////////////
8861 /// Operator *
8862 
8863 TH1S operator*(const TH1S &h1, const TH1S &h2)
8864 {
8865  TH1S hnew = h1;
8866  hnew.Multiply(&h2);
8867  hnew.SetDirectory(0);
8868  return hnew;
8869 }
8870 
8871 ////////////////////////////////////////////////////////////////////////////////
8872 /// Operator /
8873 
8874 TH1S operator/(const TH1S &h1, const TH1S &h2)
8875 {
8876  TH1S hnew = h1;
8877  hnew.Divide(&h2);
8878  hnew.SetDirectory(0);
8879  return hnew;
8880 }
8881 
8882 //______________________________________________________________________________
8883 // TH1I methods
8884 // TH1I : histograms with one int per channel. Maximum bin content = 2147483647
8885 //______________________________________________________________________________
8886 
8887 ClassImp(TH1I)
8888 
8889 ////////////////////////////////////////////////////////////////////////////////
8890 /// Constructor.
8891 
8892 TH1I::TH1I(): TH1(), TArrayI()
8893 {
8895  SetBinsLength(3);
8896  if (fgDefaultSumw2) Sumw2();
8897 }
8898 
8899 ////////////////////////////////////////////////////////////////////////////////
8900 /// Create a 1-Dim histogram with fix bins of type integer
8901 /// (see TH1::TH1 for explanation of parameters)
8902 
8903 TH1I::TH1I(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
8904 : TH1(name,title,nbins,xlow,xup)
8906  fDimension = 1;
8907  TArrayI::Set(fNcells);
8908 
8909  if (xlow >= xup) SetBuffer(fgBufferSize);
8910  if (fgDefaultSumw2) Sumw2();
8911 }
8912 
8913 ////////////////////////////////////////////////////////////////////////////////
8914 /// Create a 1-Dim histogram with variable bins of type integer
8915 /// (see TH1::TH1 for explanation of parameters)
8916 
8917 TH1I::TH1I(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
8918 : TH1(name,title,nbins,xbins)
8920  fDimension = 1;
8921  TArrayI::Set(fNcells);
8922  if (fgDefaultSumw2) Sumw2();
8923 }
8924 
8925 ////////////////////////////////////////////////////////////////////////////////
8926 /// Create a 1-Dim histogram with variable bins of type integer
8927 /// (see TH1::TH1 for explanation of parameters)
8928 
8929 TH1I::TH1I(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
8930 : TH1(name,title,nbins,xbins)
8932  fDimension = 1;
8933  TArrayI::Set(fNcells);
8934  if (fgDefaultSumw2) Sumw2();
8935 }
8936 
8937 ////////////////////////////////////////////////////////////////////////////////
8938 /// Destructor.
8939 
8940 TH1I::~TH1I()
8941 {
8943 
8944 ////////////////////////////////////////////////////////////////////////////////
8945 /// Copy constructor.
8946 
8947 TH1I::TH1I(const TH1I &h1i) : TH1(), TArrayI()
8948 {
8949  ((TH1I&)h1i).Copy(*this);
8950 }
8951 
8952 ////////////////////////////////////////////////////////////////////////////////
8953 /// Increment bin content by 1.
8954 
8955 void TH1I::AddBinContent(Int_t bin)
8956 {
8957  if (fArray[bin] < 2147483647) fArray[bin]++;
8958 }
8959 
8960 ////////////////////////////////////////////////////////////////////////////////
8961 /// Increment bin content by w
8962 
8963 void TH1I::AddBinContent(Int_t bin, Double_t w)
8964 {
8965  Int_t newval = fArray[bin] + Int_t(w);
8966  if (newval > -2147483647 && newval < 2147483647) {fArray[bin] = Int_t(newval); return;}
8967  if (newval < -2147483647) fArray[bin] = -2147483647;
8968  if (newval > 2147483647) fArray[bin] = 2147483647;
8969 }
8970 
8971 ////////////////////////////////////////////////////////////////////////////////
8972 /// Copy this to newth1
8973 
8974 void TH1I::Copy(TObject &newth1) const
8975 {
8976  TH1::Copy(newth1);
8977 }
8978 
8979 ////////////////////////////////////////////////////////////////////////////////
8980 /// Reset.
8981 
8982 void TH1I::Reset(Option_t *option)
8983 {
8984  TH1::Reset(option);
8985  TArrayI::Reset();
8986 }
8987 
8988 ////////////////////////////////////////////////////////////////////////////////
8989 /// Set total number of bins including under/overflow
8990 /// Reallocate bin contents array
8991 
8992 void TH1I::SetBinsLength(Int_t n)
8993 {
8994  if (n < 0) n = fXaxis.GetNbins() + 2;
8995  fNcells = n;
8996  TArrayI::Set(n);
8997 }
8998 
8999 ////////////////////////////////////////////////////////////////////////////////
9000 /// Operator =
9001 
9002 TH1I& TH1I::operator=(const TH1I &h1)
9003 {
9004  if (this != &h1) ((TH1I&)h1).Copy(*this);
9005  return *this;
9006 }
9007 
9008 
9009 ////////////////////////////////////////////////////////////////////////////////
9010 /// Operator *
9011 
9012 TH1I operator*(Double_t c1, const TH1I &h1)
9013 {
9014  TH1I hnew = h1;
9015  hnew.Scale(c1);
9016  hnew.SetDirectory(0);
9017  return hnew;
9018 }
9019 
9020 ////////////////////////////////////////////////////////////////////////////////
9021 /// Operator +
9022 
9023 TH1I operator+(const TH1I &h1, const TH1I &h2)
9024 {
9025  TH1I hnew = h1;
9026  hnew.Add(&h2,1);
9027  hnew.SetDirectory(0);
9028  return hnew;
9029 }
9030 
9031 ////////////////////////////////////////////////////////////////////////////////
9032 /// Operator -
9033 
9034 TH1I operator-(const TH1I &h1, const TH1I &h2)
9035 {
9036  TH1I hnew = h1;
9037  hnew.Add(&h2,-1);
9038  hnew.SetDirectory(0);
9039  return hnew;
9040 }
9041 
9042 ////////////////////////////////////////////////////////////////////////////////
9043 /// Operator *
9044 
9045 TH1I operator*(const TH1I &h1, const TH1I &h2)
9046 {
9047  TH1I hnew = h1;
9048  hnew.Multiply(&h2);
9049  hnew.SetDirectory(0);
9050  return hnew;
9051 }
9052 
9053 ////////////////////////////////////////////////////////////////////////////////
9054 /// Operator /
9055 
9056 TH1I operator/(const TH1I &h1, const TH1I &h2)
9057 {
9058  TH1I hnew = h1;
9059  hnew.Divide(&h2);
9060  hnew.SetDirectory(0);
9061  return hnew;
9062 }
9063 
9064 //______________________________________________________________________________
9065 // TH1F methods
9066 // TH1F : histograms with one float per channel. Maximum precision 7 digits
9067 //______________________________________________________________________________
9068 
9069 ClassImp(TH1F)
9070 
9071 ////////////////////////////////////////////////////////////////////////////////
9072 /// Constructor.
9073 
9074 TH1F::TH1F(): TH1(), TArrayF()
9075 {
9077  SetBinsLength(3);
9078  if (fgDefaultSumw2) Sumw2();
9079 }
9080 
9081 ////////////////////////////////////////////////////////////////////////////////
9082 /// Create a 1-Dim histogram with fix bins of type float
9083 /// (see TH1::TH1 for explanation of parameters)
9084 
9085 TH1F::TH1F(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
9086 : TH1(name,title,nbins,xlow,xup)
9088  fDimension = 1;
9089  TArrayF::Set(fNcells);
9090 
9091  if (xlow >= xup) SetBuffer(fgBufferSize);
9092  if (fgDefaultSumw2) Sumw2();
9093 }
9094 
9095 ////////////////////////////////////////////////////////////////////////////////
9096 /// Create a 1-Dim histogram with variable bins of type float
9097 /// (see TH1::TH1 for explanation of parameters)
9098 
9099 TH1F::TH1F(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
9100 : TH1(name,title,nbins,xbins)
9102  fDimension = 1;
9103  TArrayF::Set(fNcells);
9104  if (fgDefaultSumw2) Sumw2();
9105 }
9106 
9107 ////////////////////////////////////////////////////////////////////////////////
9108 /// Create a 1-Dim histogram with variable bins of type float
9109 /// (see TH1::TH1 for explanation of parameters)
9110 
9111 TH1F::TH1F(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
9112 : TH1(name,title,nbins,xbins)
9114  fDimension = 1;
9115  TArrayF::Set(fNcells);
9116  if (fgDefaultSumw2) Sumw2();
9117 }
9118 
9119 ////////////////////////////////////////////////////////////////////////////////
9120 /// Create a histogram from a TVectorF
9121 /// by default the histogram name is "TVectorF" and title = ""
9122 
9123 TH1F::TH1F(const TVectorF &v)
9124 : TH1("TVectorF","",v.GetNrows(),0,v.GetNrows())
9126  TArrayF::Set(fNcells);
9127  fDimension = 1;
9128  Int_t ivlow = v.GetLwb();
9129  for (Int_t i=0;i<fNcells-2;i++) {
9130  SetBinContent(i+1,v(i+ivlow));
9131  }
9132  TArrayF::Set(fNcells);
9133  if (fgDefaultSumw2) Sumw2();
9134 }
9135 
9136 ////////////////////////////////////////////////////////////////////////////////
9137 /// Copy Constructor.
9138 
9139 TH1F::TH1F(const TH1F &h) : TH1(), TArrayF()
9140 {
9141  ((TH1F&)h).Copy(*this);
9142 }
9143 
9144 ////////////////////////////////////////////////////////////////////////////////
9145 /// Destructor.
9146 
9147 TH1F::~TH1F()
9148 {
9150 
9151 ////////////////////////////////////////////////////////////////////////////////
9152 /// Copy this to newth1.
9153 
9154 void TH1F::Copy(TObject &newth1) const
9155 {
9156  TH1::Copy(newth1);
9157 }
9158 
9159 ////////////////////////////////////////////////////////////////////////////////
9160 /// Reset.
9161 
9162 void TH1F::Reset(Option_t *option)
9163 {
9164  TH1::Reset(option);
9165  TArrayF::Reset();
9166 }
9167 
9168 ////////////////////////////////////////////////////////////////////////////////
9169 /// Set total number of bins including under/overflow
9170 /// Reallocate bin contents array
9171 
9172 void TH1F::SetBinsLength(Int_t n)
9173 {
9174  if (n < 0) n = fXaxis.GetNbins() + 2;
9175  fNcells = n;
9176  TArrayF::Set(n);
9177 }
9178 
9179 ////////////////////////////////////////////////////////////////////////////////
9180 /// Operator =
9181 
9182 TH1F& TH1F::operator=(const TH1F &h1)
9183 {
9184  if (this != &h1) ((TH1F&)h1).Copy(*this);
9185  return *this;
9186 }
9187 
9188 ////////////////////////////////////////////////////////////////////////////////
9189 /// Operator *
9190 
9191 TH1F operator*(Double_t c1, const TH1F &h1)
9192 {
9193  TH1F hnew = h1;
9194  hnew.Scale(c1);
9195  hnew.SetDirectory(0);
9196  return hnew;
9197 }
9198 
9199 ////////////////////////////////////////////////////////////////////////////////
9200 /// Operator +
9201 
9202 TH1F operator+(const TH1F &h1, const TH1F &h2)
9203 {
9204  TH1F hnew = h1;
9205  hnew.Add(&h2,1);
9206  hnew.SetDirectory(0);
9207  return hnew;
9208 }
9209 
9210 ////////////////////////////////////////////////////////////////////////////////
9211 /// Operator -
9212 
9213 TH1F operator-(const TH1F &h1, const TH1F &h2)
9214 {
9215  TH1F hnew = h1;
9216  hnew.Add(&h2,-1);
9217  hnew.SetDirectory(0);
9218  return hnew;
9219 }
9220 
9221 ////////////////////////////////////////////////////////////////////////////////
9222 /// Operator *
9223 
9224 TH1F operator*(const TH1F &h1, const TH1F &h2)
9225 {
9226  TH1F hnew = h1;
9227  hnew.Multiply(&h2);
9228  hnew.SetDirectory(0);
9229  return hnew;
9230 }
9231 
9232 ////////////////////////////////////////////////////////////////////////////////
9233 /// Operator /
9234 
9235 TH1F operator/(const TH1F &h1, const TH1F &h2)
9236 {
9237  TH1F hnew = h1;
9238  hnew.Divide(&h2);
9239  hnew.SetDirectory(0);
9240  return hnew;
9241 }
9242 
9243 //______________________________________________________________________________
9244 // TH1D methods
9245 // TH1D : histograms with one double per channel. Maximum precision 14 digits
9246 //______________________________________________________________________________
9247 
9248 ClassImp(TH1D)
9249 
9250 ////////////////////////////////////////////////////////////////////////////////
9251 /// Constructor.
9252 
9253 TH1D::TH1D(): TH1(), TArrayD()
9254 {
9256  SetBinsLength(3);
9257  if (fgDefaultSumw2) Sumw2();
9258 }
9259 
9260 ////////////////////////////////////////////////////////////////////////////////
9261 /// Create a 1-Dim histogram with fix bins of type double
9262 /// (see TH1::TH1 for explanation of parameters)
9263 
9264 TH1D::TH1D(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
9265 : TH1(name,title,nbins,xlow,xup)
9267  fDimension = 1;
9268  TArrayD::Set(fNcells);
9269 
9270  if (xlow >= xup) SetBuffer(fgBufferSize);
9271  if (fgDefaultSumw2) Sumw2();
9272 }
9273 
9274 ////////////////////////////////////////////////////////////////////////////////
9275 /// Create a 1-Dim histogram with variable bins of type double
9276 /// (see TH1::TH1 for explanation of parameters)
9277 
9278 TH1D::TH1D(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
9279 : TH1(name,title,nbins,xbins)
9281  fDimension = 1;
9282  TArrayD::Set(fNcells);
9283  if (fgDefaultSumw2) Sumw2();
9284 }
9285 
9286 ////////////////////////////////////////////////////////////////////////////////
9287 /// Create a 1-Dim histogram with variable bins of type double
9288 /// (see TH1::TH1 for explanation of parameters)
9289 
9290 TH1D::TH1D(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
9291 : TH1(name,title,nbins,xbins)
9293  fDimension = 1;
9294  TArrayD::Set(fNcells);
9295  if (fgDefaultSumw2) Sumw2();
9296 }
9297 
9298 ////////////////////////////////////////////////////////////////////////////////
9299 /// Create a histogram from a TVectorD
9300 /// by default the histogram name is "TVectorD" and title = ""
9301 
9302 TH1D::TH1D(const TVectorD &v)
9303 : TH1("TVectorD","",v.GetNrows(),0,v.GetNrows())
9305  TArrayD::Set(fNcells);
9306  fDimension = 1;
9307  Int_t ivlow = v.GetLwb();
9308  for (Int_t i=0;i<fNcells-2;i++) {
9309  SetBinContent(i+1,v(i+ivlow));
9310  }
9311  TArrayD::Set(fNcells);
9312  if (fgDefaultSumw2) Sumw2();
9313 }
9314 
9315 ////////////////////////////////////////////////////////////////////////////////
9316 /// Destructor.
9317 
9318 TH1D::~TH1D()
9319 {
9321 
9322 ////////////////////////////////////////////////////////////////////////////////
9323 /// Constructor.
9324 
9325 TH1D::TH1D(const TH1D &h1d) : TH1(), TArrayD()
9326 {
9327  ((TH1D&)h1d).Copy(*this);
9328 }
9329 
9330 ////////////////////////////////////////////////////////////////////////////////
9331 /// Copy this to newth1
9332 
9333 void TH1D::Copy(TObject &newth1) const
9334 {
9335  TH1::Copy(newth1);
9336 }
9337 
9338 ////////////////////////////////////////////////////////////////////////////////
9339 /// Reset.
9340 
9341 void TH1D::Reset(Option_t *option)
9342 {
9343  TH1::Reset(option);
9344  TArrayD::Reset();
9345 }
9346 
9347 ////////////////////////////////////////////////////////////////////////////////
9348 /// Set total number of bins including under/overflow
9349 /// Reallocate bin contents array
9350 
9351 void TH1D::SetBinsLength(Int_t n)
9352 {
9353  if (n < 0) n = fXaxis.GetNbins() + 2;
9354  fNcells = n;
9355  TArrayD::Set(n);
9356 }
9357 
9358 ////////////////////////////////////////////////////////////////////////////////
9359 /// Operator =
9360 
9361 TH1D& TH1D::operator=(const TH1D &h1)
9362 {
9363  if (this != &h1) ((TH1D&)h1).Copy(*this);
9364  return *this;
9365 }
9366 
9367 ////////////////////////////////////////////////////////////////////////////////
9368 /// Operator *
9369 
9370 TH1D operator*(Double_t c1, const TH1D &h1)
9371 {
9372  TH1D hnew = h1;
9373  hnew.Scale(c1);
9374  hnew.SetDirectory(0);
9375  return hnew;
9376 }
9377 
9378 ////////////////////////////////////////////////////////////////////////////////
9379 /// Operator +
9380 
9381 TH1D operator+(const TH1D &h1, const TH1D &h2)
9382 {
9383  TH1D hnew = h1;
9384  hnew.Add(&h2,1);
9385  hnew.SetDirectory(0);
9386  return hnew;
9387 }
9388 
9389 ////////////////////////////////////////////////////////////////////////////////
9390 /// Operator -
9391 
9392 TH1D operator-(const TH1D &h1, const TH1D &h2)
9393 {
9394  TH1D hnew = h1;
9395  hnew.Add(&h2,-1);
9396  hnew.SetDirectory(0);
9397  return hnew;
9398 }
9399 
9400 ////////////////////////////////////////////////////////////////////////////////
9401 /// Operator *
9402 
9403 TH1D operator*(const TH1D &h1, const TH1D &h2)
9404 {
9405  TH1D hnew = h1;
9406  hnew.Multiply(&h2);
9407  hnew.SetDirectory(0);
9408  return hnew;
9409 }
9410 
9411 ////////////////////////////////////////////////////////////////////////////////
9412 /// Operator /
9413 
9414 TH1D operator/(const TH1D &h1, const TH1D &h2)
9415 {
9416  TH1D hnew = h1;
9417  hnew.Divide(&h2);
9418  hnew.SetDirectory(0);
9419  return hnew;
9420 }
9421 
9422 ////////////////////////////////////////////////////////////////////////////////
9423 ///return pointer to histogram with name
9424 ///hid if id >=0
9425 ///h_id if id <0
9426 
9427 TH1 *R__H(Int_t hid)
9428 {
9429  TString hname;
9430  if(hid >= 0) hname.Form("h%d",hid);
9431  else hname.Form("h_%d",hid);
9432  return (TH1*)gDirectory->Get(hname);
9433 }
9434 
9435 ////////////////////////////////////////////////////////////////////////////////
9436 ///return pointer to histogram with name hname
9437 
9438 TH1 *R__H(const char * hname)
9439 {
9440  return (TH1*)gDirectory->Get(hname);
9441 }
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:6197
const int nx
Definition: kalman.C:16
const int ndata
TString fTitle
Definition: TNamed.h:37
Abstract array base class.
Definition: TArray.h:33
virtual void Browse(TBrowser *b)
Browse the Histogram object.
Definition: TH1.cxx:708
Int_t GetFirst() const
Return first bin on the axis i.e.
Definition: TAxis.cxx:444
virtual void SavePrimitive(std::ostream &out, Option_t *option="")
Save primitive as a C++ statement(s) on output stream out.
Definition: TH1.cxx:6428
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 * GetTitle() const
Returns title of object.
Definition: TNamed.h:52
virtual void SetBinsLength(Int_t n=-1)
Set total number of bins including under/overflow Reallocate bin contents array.
Definition: TH1.cxx:9353
void Copy(TAttMarker &attmarker) const
Copy this marker attributes to a new TAttMarker.
Definition: TAttMarker.cxx:194
virtual Style_t GetLineStyle() const
Return the line style.
Definition: TAttLine.h:40
virtual Style_t GetFillStyle() const
Return the fill area style.
Definition: TAttFill.h:36
virtual void SetNameTitle(const char *name, const char *title)
Change the name and title of this histogram.
Definition: TH1.cxx:8042
virtual void SetLineWidth(Width_t lwidth)
Set the line width.
Definition: TAttLine.h:49
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:3442
Double_t fNormFactor
Normalization factor.
Definition: TH1.h:116
virtual void SetBarOffset(Float_t offset=0.25)
Definition: TH1.h:361
virtual void Scale(Double_t c1=1, Option_t *option="")
Multiply this histogram by a constant c1.
Definition: TH1.cxx:5893
virtual Color_t GetAxisColor() const
Definition: TAttAxis.h:42
virtual Int_t Fill(Double_t x)
Increment bin with abscissa X by 1.
Definition: TH1.cxx:3127
virtual Int_t ShowPeaks(Double_t sigma=2, Option_t *option="", Double_t threshold=0.05)
Interface to TSpectrum::Search.
Definition: TH1.cxx:8360
virtual Double_t GetBinErrorLow(Int_t bin) const
Return lower error associated to bin number bin.
Definition: TH1.cxx:8146
TList * GetListOfFunctions() const
Definition: TH1.h:248
TH1D & operator=(const TH1D &h1)
Operator =.
Definition: TH1.cxx:9363
void SetBarWidth(Float_t barwidth=0.5)
Definition: TStyle.h:327
static long int sum(long int i)
Definition: Factory.cxx:1785
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:646
virtual void Paint(Option_t *option="")
Control routine to paint any kind of histograms.
Definition: TH1.cxx:5512
float xmin
Definition: THbookFile.cxx:93
virtual TH1 * DrawNormalized(Option_t *option="", Double_t norm=1) const
Draw a normalized copy of this histogram.
Definition: TH1.cxx:2927
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:405
virtual Color_t GetLabelColor() const
Definition: TAttAxis.h:43
virtual void GetLowEdge(Double_t *edge) const
Return an array with the lod edge of all bins.
Definition: TAxis.cxx:548
virtual Double_t PoissonD(Double_t mean)
Generates a random number according to a Poisson law.
Definition: TRandom.cxx:414
Double_t Floor(Double_t x)
Definition: TMath.h:473
void Set(Int_t n)
Set size of this array to n chars.
Definition: TArrayC.cxx:105
Int_t AxisChoice(Option_t *axis) const
Choose an axis according to "axis".
Definition: Haxis.cxx:14
virtual ~TH1I()
Destructor.
Definition: TH1.cxx:8942
long long Long64_t
Definition: RtypesCore.h:69
virtual Double_t GetBinContent(Int_t bin) const
Return content of bin number bin.
Definition: TH1.cxx:4640
Bool_t IsBinOverflow(Int_t bin) const
Return true if the bin is overflow.
Definition: TH1.cxx:4742
virtual void SetMaximum(Double_t maximum=-1111)
Definition: TH1.h:399
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:6653
Bool_t CanExtend() const
Definition: TAxis.h:88
virtual void LabelsOption(Option_t *option="h", Option_t *axis="X")
Set option(s) to draw axis with labels.
Definition: TH1.cxx:4908
short Style_t
Definition: RtypesCore.h:76
virtual void SetLimits(Double_t xmin, Double_t xmax)
Definition: TAxis.h:160
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:1891
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:3520
Bool_t IsReading() const
Definition: TBuffer.h:83
Double_t Log(Double_t x)
Definition: TMath.h:526
Option_t * GetDrawOption() const
Get option used by the graphics system to draw this object.
Definition: TBrowser.h:108
Short_t fBarWidth
(1000*width) for bar charts or legos
Definition: TH1.h:108
virtual Bool_t InheritsFrom(const char *classname) const
Returns kTRUE if object inherits from class "classname".
Definition: TObject.cxx:488
short Version_t
Definition: RtypesCore.h:61
TH1C()
Constructor.
Definition: TH1.cxx:8532
static Bool_t fgDefaultSumw2
!flag to call TH1::Sumw2 automatically at histogram creation time
Definition: TH1.h:131
virtual Int_t DistancetoPrimitive(Int_t px, Int_t py)=0
Computes distance from point (px,py) to the object.
Ssiz_t Length() const
Definition: TString.h:390
TVirtualHistPainter * GetPainter(Option_t *option="")
Return pointer to painter.
Definition: TH1.cxx:4101
virtual void FitPanel()
Display a panel with all histogram fit options.
Definition: TH1.cxx:3916
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:8008
Bool_t GetCanvasPreferGL() const
Definition: TStyle.h:189
Short_t * fArray
Definition: TArrayS.h:32
Style_t GetHistLineStyle() const
Definition: TStyle.h:236
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:6975
return c
virtual Int_t GetMaximumBin() const
Return location of bin with maximum value in the range.
Definition: TH1.cxx:7651
const char Option_t
Definition: RtypesCore.h:62
const char * GetBinLabel(Int_t bin) const
Return label for bin.
Definition: TAxis.cxx:426
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:49
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:622
virtual void SetError(const Double_t *error)
Replace bin errors by values in array error.
Definition: TH1.cxx:8019
Bool_t IsBinUnderflow(Int_t bin) const
Return true if the bin is underflow.
Definition: TH1.cxx:4763
TString & ReplaceAll(const TString &s1, const TString &s2)
Definition: TString.h:635
TAxis fYaxis
Y axis descriptor.
Definition: TH1.h:105
virtual Int_t BufferFill(Double_t x, Double_t w)
accumulate arguments in buffer.
Definition: TH1.cxx:1321
virtual void SetContour(Int_t nlevels, const Double_t *levels=0)
Set the number and values of contour levels.
Definition: TH1.cxx:7562
R__EXTERN TStyle * gStyle
Definition: TStyle.h:418
virtual void PutStats(Double_t *stats)
Replace current statistics with the values in array stats.
Definition: TH1.cxx:7027
void SetHistLineWidth(Width_t width=1)
Definition: TStyle.h:373
virtual Int_t GetDimension() const
Definition: TH1.h:287
TList * fFunctions
->Pointer to list of functions (fits and user)
Definition: TH1.h:120
virtual void SetBins(Int_t nx, Double_t xmin, Double_t xmax)
Redefine x axis parameters.
Definition: TH1.cxx:7838
Int_t GetNrows() const
Definition: TVectorT.h:81
virtual void SetName(const char *name)
Set the name of the TNamed.
Definition: TNamed.cxx:131
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:3971
static Bool_t fgStatOverflows
!flag to use under/overflows in statistics
Definition: TH1.h:130
static Bool_t SameLimitsAndNBins(const TAxis &axis1, const TAxis &axis2)
Same limits and bins.
Definition: TH1.cxx:5193
virtual ~TH1F()
Destructor.
Definition: TH1.cxx:9149
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 void Info(const char *method, const char *msgfmt,...) const
Issue info message.
Definition: TObject.cxx:899
virtual void SetNdivisions(Int_t n=510, Bool_t optim=kTRUE)
Set the number of divisions for this axis.
Definition: TAttAxis.cxx:229
virtual Bool_t GetTimeDisplay() const
Definition: TAxis.h:132
TVectorT.
Definition: TMatrixTBase.h:89
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:4192
void Copy(TAttLine &attline) const
Copy this line attributes to a new TAttLine.
Definition: TAttLine.cxx:162
void ToUpper()
Change string to upper case.
Definition: TString.cxx:1102
virtual void Reset(Option_t *option="")
Reset.
Definition: TH1.cxx:8622
TH1D()
Constructor.
Definition: TH1.cxx:9255
friend TH1D operator/(const TH1D &h1, const TH1D &h2)
Operator /.
Definition: TH1.cxx:9416
static bool CheckAxisLimits(const TAxis *a1, const TAxis *a2)
Check that the axis limits of the histograms are the same.
Definition: TH1.cxx:1414
Buffer base class used for serializing objects.
Definition: TBuffer.h:42
friend TH1S operator+(const TH1S &h1, const TH1S &h2)
Operator +.
Definition: TH1.cxx:8843
virtual Double_t GetBinLowEdge(Int_t bin) const
Return low edge of bin.
Definition: TAxis.cxx:504
virtual void Copy(TObject &hnew) const
Copy this to newth1.
Definition: TH1.cxx:8614
virtual void Copy(TObject &hnew) const
Copy this to newth1.
Definition: TH1.cxx:8795
TH1F()
Constructor.
Definition: TH1.cxx:9076
#define R__ASSERT(e)
Definition: TError.h:98
virtual void SetMinimum(Double_t minimum=-1111)
Definition: TH1.h:400
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:364
Int_t LoadPlugin()
Load the plugin library for this handler.
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...
Basic string class.
Definition: TString.h:137
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:575
virtual TObject * GetUserFunc() const
tomato 1-D histogram with a short per channel (see TH1 documentation)
Definition: TH1.h:493
void H1InitExpo()
Compute Initial values of parameters for an exponential.
Definition: TH1.cxx:4298
Array of floats (32 bits per element).
Definition: TArrayF.h:29
virtual Double_t GetNormFactor() const
Definition: TH1.h:305
void Copy(TAttFill &attfill) const
Copy this fill attributes to a new TAttFill.
Definition: TAttFill.cxx:200
virtual void SetTitleFont(Style_t font=62)
Set the title font.
Definition: TAttAxis.cxx:290
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:2427
Short_t Min(Short_t a, Short_t b)
Definition: TMathBase.h:170
void ToLower()
Change string to lower-case.
Definition: TString.cxx:1089
int Int_t
Definition: RtypesCore.h:41
bool Bool_t
Definition: RtypesCore.h:59
void SetBarOffset(Float_t baroff=0.5)
Definition: TStyle.h:326
TArc * a
Definition: textangle.C:12
R__EXTERN TVirtualMutex * gROOTMutex
Definition: TROOT.h:63
const Bool_t kFALSE
Definition: Rtypes.h:92
virtual Color_t GetTitleColor() const
Definition: TAttAxis.h:50
virtual Double_t GetBinWidth(Int_t bin) const
Return bin width.
Definition: TAxis.cxx:526
Int_t GetOptStat() const
Definition: TStyle.h:245
virtual void SetFillStyle(Style_t fstyle)
Set the fill area style.
Definition: TAttFill.h:44
virtual void Smooth(Int_t ntimes=1, Option_t *option="")
Smooth bin contents of this histogram.
Definition: TH1.cxx:6151
virtual TObject * FindObject(const char *name) const
Find an object in this list using its name.
Definition: TList.cxx:497
#define gInterpreter
Definition: TInterpreter.h:515
Histogram is forced to be not weighted even when the histogram is filled with weighted different than...
Definition: TH1.h:179
int nbins[3]
virtual Double_t GetStdDevError(Int_t axis=1) const
Return error of standard deviation estimation for Normal distribution.
Definition: TH1.cxx:6809
TArrayD fSumw2
Array of sum of squares of weights.
Definition: TH1.h:118
virtual Style_t GetTitleFont() const
Definition: TAttAxis.h:51
virtual void UseCurrentStyle()
Set current style settings in this object This function is called when either TCanvas::UseCurrentStyl...
Definition: TObject.cxx:760
virtual Int_t GetNbinsX() const
Definition: TH1.h:301
static Bool_t AlmostInteger(Double_t a, Double_t epsilon=0.00000001)
Test if a double is almost an integer.
Definition: TH1.cxx:5164
void Reset()
Definition: TArrayF.h:49
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:8254
virtual Double_t Integral(Double_t a, Double_t b, Double_t epsrel=1.e-12)
IntegralOneDim or analytical integral.
Definition: TF1.cxx:2272
const char * Class
Definition: TXMLSetup.cxx:64
Style_t GetHistFillStyle() const
Definition: TStyle.h:235
void Copy(TArrayD &array) const
Definition: TArrayD.h:44
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:5204
TAxis fZaxis
Z axis descriptor.
Definition: TH1.h:106
virtual Double_t GetEntries() const
Return the current number of entries.
Definition: TH1.cxx:4055
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:5337
Long_t ExecPlugin(int nargs, const T &...params)
virtual void SetBinsLength(Int_t n=-1)
Set total number of bins including under/overflow Reallocate bin contents array.
Definition: TH1.cxx:9174
virtual Float_t GetTitleSize() const
Definition: TAttAxis.h:48
TF1 * gF1
Definition: TH1.cxx:522
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:8241
virtual void SetLabelOffset(Float_t offset=0.005)
Set distance between the axis and the labels The distance is expressed in per cent of the pad width...
Definition: TAttAxis.cxx:193
Short_t Abs(Short_t d)
Definition: TMathBase.h:110
virtual TObject * At(Int_t idx) const
Returns the object at position idx. Returns 0 if idx is out of range.
Definition: TList.cxx:311
friend TH1D operator+(const TH1D &h1, const TH1D &h2)
Operator +.
Definition: TH1.cxx:9383
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:1356
virtual TH1 * GetHistogram() const
Return a pointer to the histogram used to visualise the function.
Definition: TF1.cxx:1303
Array of integers (32 bits per element).
Definition: TArrayI.h:29
void Reset(Char_t val=0)
Definition: TArrayC.h:49
LongDouble_t Power(LongDouble_t x, LongDouble_t y)
Definition: TMath.h:501
void SetBit(UInt_t f, Bool_t set)
Set or unset the user status bits as specified in f.
Definition: TObject.cxx:739
virtual void SetBuffer(Int_t buffersize, Option_t *option="")
Set the maximum number of entries to be kept in the buffer.
Definition: TH1.cxx:7537
Double_t fTsumwx2
Total Sum of weight*X*X.
Definition: TH1.h:113
virtual void Reset(Option_t *option="")
Reset this histogram: contents, errors, etc.
Definition: TH1.cxx:6375
friend TH1S operator-(const TH1S &h1, const TH1S &h2)
Operator -.
Definition: TH1.cxx:8854
static void AddDirectory(Bool_t add=kTRUE)
Sets the flag controlling the automatic add of histograms in memory.
Definition: TH1.cxx:1220
TObject * Clone(const char *newname=0) const
Make a complete copy of the underlying object.
Definition: TH1.cxx:2546
if object in a list can be deleted
Definition: TObject.h:63
virtual void SetBarWidth(Float_t width=0.5)
Definition: TH1.h:362
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:165
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
TDirectory * fDirectory
!Pointer to directory holding this histogram
Definition: TH1.h:123
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:5969
virtual Double_t GetBinWidth(Int_t bin) const
Return bin width for 1D histogram.
Definition: TH1.cxx:8230
Marker Attributes class.
Definition: TAttMarker.h:24
virtual TObject * Clone(const char *newname="") const
Make a clone of an collection using the Streamer facility.
const char * Data() const
Definition: TString.h:349
virtual Double_t GetSkewness(Int_t axis=1) const
Definition: TH1.cxx:6822
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:1463
NOTE: Must always be 0 !!!
Definition: TH1.h:93
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:4694
virtual Int_t GetContour(Double_t *levels=0)
Return contour values into array levels if pointer levels is non zero.
Definition: TH1.cxx:7490
TH1C & operator=(const TH1C &h1)
Operator =.
Definition: TH1.cxx:8642
virtual void Paint(Option_t *option="")=0
This method must be overridden if a class wants to paint itself.
virtual Double_t GetRandom() const
Return a random number distributed according the histogram bin contents.
Definition: TH1.cxx:4589
Fill Area Attributes class.
Definition: TAttFill.h:24
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:4233
virtual Double_t GetBinErrorUp(Int_t bin) const
Return upper error associated to bin number bin.
Definition: TH1.cxx:8177
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:2335
virtual void Eval(TF1 *f1, Option_t *option="")
Evaluate function f1 at the center of bins of this histogram.
Definition: TH1.cxx:2975
virtual Double_t GetBinLowEdge(Int_t bin) const
Return bin lower edge for 1D histogram.
Definition: TH1.cxx:8219
Float_t GetBarOffset() const
Definition: TStyle.h:184
THashList implements a hybrid collection class consisting of a hash table and a list to store TObject...
Definition: THashList.h:36
static Bool_t GetDefaultSumw2()
Return kTRUE if TH1::Sumw2 must be called when creating new histograms.
Definition: TH1.cxx:4047
void SetHistFillColor(Color_t color=1)
Definition: TStyle.h:369
static void SetDefaultBufferSize(Int_t buffersize=1000)
Static function to set the default buffer size for automatic histograms.
Definition: TH1.cxx:5959
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
The TNamed class is the base class for all named ROOT classes.
Definition: TNamed.h:33
virtual ~TH1()
Histogram default destructor.
Definition: TH1.cxx:575
const int ny
Definition: kalman.C:17
virtual Bool_t IsEmpty() const
Definition: TCollection.h:99
Double_t GetAt(Int_t i) const
Definition: TArrayD.h:47
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:7117
virtual void Copy(TObject &named) const
Copy this to obj.
Definition: TNamed.cxx:85
friend TH1D operator-(const TH1D &h1, const TH1D &h2)
Operator -.
Definition: TH1.cxx:9394
virtual TObject * FindObject(const char *name) const
Search object named name in the list of functions.
Definition: TH1.cxx:3538
Double_t Log10(Double_t x)
Definition: TMath.h:529
virtual void SetContourLevel(Int_t level, Double_t value)
Set value for one contour level.
Definition: TH1.cxx:7601
TH1I()
Constructor.
Definition: TH1.cxx:8894
Abstract interface to a histogram painter.
virtual void SetMarkerColor(Color_t mcolor=1)
Set the marker color.
Definition: TAttMarker.h:43
virtual Option_t * GetType() const =0
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:4542
TH1S()
Constructor.
Definition: TH1.cxx:8713
TString & Append(const char *cs)
Definition: TString.h:492
void Sort(Index n, const Element *a, Index *index, Bool_t down=kTRUE)
Definition: TMath.h:989
Double_t * fArray
Definition: TArrayD.h:32
void H1InitGaus()
Compute Initial values of parameters for a gaussian.
Definition: TH1.cxx:4242
virtual void DrawPanel()=0
errors from Poisson interval at 95% CL (~ 2 sigma)
Definition: TH1.h:88
const Double_t sigma
TString fOption
histogram options
Definition: TH1.h:119
friend TH1I operator-(const TH1I &h1, const TH1I &h2)
Operator -.
Definition: TH1.cxx:9036
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:229
Float_t GetBarWidth() const
Definition: TStyle.h:185
virtual void GetRange(Double_t *xmin, Double_t *xmax) const
Return range of a generic N-D function.
Definition: TF1.cxx:1984
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
Definition: TObject.cxx:925
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:5755
virtual TH1 * DrawCopy(Option_t *option="", const char *name_postfix="_copy") const
Copy this histogram and Draw in the current pad.
Definition: TH1.cxx:2899
TH1F * h1
Definition: legend1.C:5
virtual void SetContent(const Double_t *content)
Replace bin contents by the contents of array content.
Definition: TH1.cxx:7477
virtual void AddBinContent(Int_t bin)
Increment bin content by 1.
Definition: TH1.cxx:1195
friend TH1C operator*(Double_t c1, const TH1C &h1)
Operator *.
Definition: TH1.cxx:8651
virtual void ResetStats()
Reset the statistics including the number of entries and replace with values calculates from bin cont...
Definition: TH1.cxx:7042
void Set(Int_t n)
Set size of this array to n ints.
Definition: TArrayI.cxx:105
TArrayD fContour
Array to display contour levels.
Definition: TH1.h:117
virtual void SetBinError(Int_t bin, Double_t error)
See convention for numbering bins in TH1::GetBin.
Definition: TH1.cxx:8266
Double_t GetXmin() const
Definition: TAxis.h:139
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:2357
user specified contour levels
Definition: TH1.h:173
virtual void LabelsInflate(Option_t *axis="X")
Double the number of bins for axis.
Definition: TH1.cxx:4849
void AndersonDarling2SamplesTest(Double_t &pvalue, Double_t &testStat) const
Definition: GoFTest.cxx:644
virtual Float_t GetTitleOffset() const
Definition: TAttAxis.h:47
Int_t GetOptFit() const
Definition: TStyle.h:244
short Color_t
Definition: RtypesCore.h:79
virtual void SetTimeDisplay(Int_t value)
Definition: TAxis.h:167
Double_t fTsumwx
Total Sum of weight*X.
Definition: TH1.h:112
void H1LeastSquareFit(Int_t n, Int_t m, Double_t *a)
Least squares lpolynomial fitting without weights.
Definition: TH1.cxx:4348
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:2608
virtual Double_t GetEffectiveEntries() const
Number of effective entries of the histogram.
Definition: TH1.cxx:4080
static Bool_t fgAddDirectory
!flag to add histograms to the directory
Definition: TH1.h:129
virtual void SetUniqueID(UInt_t uid)
Set the unique object id.
Definition: TObject.cxx:750
A doubly linked list.
Definition: TList.h:47
void Set(Int_t n)
Set size of this array to n shorts.
Definition: TArrayS.cxx:105
virtual Double_t Rndm()
Machine independent random number generator.
Definition: TRandom.cxx:512
Double_t fMinimum
Minimum value for plotting.
Definition: TH1.h:115
virtual void ExtendAxis(Double_t x, TAxis *axis)
Histogram is resized along axis such that x is in the axis range.
Definition: TH1.cxx:5812
Bool_t AreEqualRel(Double_t af, Double_t bf, Double_t relPrec)
Definition: TMath.h:196
virtual TH1 * FFT(TH1 *h_output, Option_t *option)
This function allows to do discrete Fourier transforms of TH1 and TH2.
Definition: TH1.cxx:3067
virtual Int_t DistancetoPrimitive(Int_t px, Int_t py)
Compute distance from point px,py to a line.
Definition: TH1.cxx:2591
void Reset()
Definition: TArrayS.h:49
virtual void AddBinContent(Int_t bin)
Increment bin content by 1.
Definition: TH1.cxx:8776
virtual void SetLineColor(Color_t lcolor)
Set the line color.
Definition: TAttLine.h:46
Bool_t IsReading() const
Definition: TStyle.h:290
don&#39;t draw stats box
Definition: TH1.h:172
friend TH1S operator/(const TH1S &h1, const TH1S &h2)
Operator /.
Definition: TH1.cxx:8876
Using a TBrowser one can browse all ROOT objects.
Definition: TBrowser.h:41
virtual void ExecuteEvent(Int_t event, Int_t px, Int_t py)
Execute action corresponding to one event.
Definition: TH1.cxx:3023
Int_t fN
Definition: TArray.h:40
virtual Double_t * GetIntegral()
Return a pointer to the array of bins integral.
Definition: TH1.cxx:2405
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:7201
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:887
virtual Double_t GetBinCenter(Int_t bin) const
Return bin center for 1D histogram.
Definition: TH1.cxx:8208
virtual Size_t GetMarkerSize() const
Return the marker size.
Definition: TAttMarker.h:38
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:449
virtual void SetParLimits(Int_t ipar, Double_t parmin, Double_t parmax)
Set limits for parameter ipar.
Definition: TF1.cxx:3218
friend TH1C operator-(const TH1C &h1, const TH1C &h2)
Operator -.
Definition: TH1.cxx:8673
Color_t GetHistFillColor() const
Definition: TStyle.h:233
friend TH1C operator+(const TH1C &h1, const TH1C &h2)
Operator +.
Definition: TH1.cxx:8662
void FillData(BinData &dv, const TH1 *hist, TF1 *func=0)
fill the data vector from a TH1.
virtual void Print(Option_t *option="") const
Print some global quantities for this histogram.
Definition: TH1.cxx:6281
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:6717
Width_t GetHistLineWidth() const
Definition: TStyle.h:237
virtual void FillRandom(const char *fname, Int_t ntimes=5000)
Fill histogram following distribution in function fname.
Definition: TH1.cxx:3295
virtual Double_t Integral(Option_t *option="") const
Return integral of bin contents.
Definition: TH1.cxx:7081
void SetHistFillStyle(Style_t styl=0)
Definition: TStyle.h:371
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:6033
Class to manage histogram axis.
Definition: TAxis.h:36
virtual void Draw(Option_t *option="")
Draw this histogram with options.
Definition: TH1.cxx:2853
static bool CheckBinLabels(const TAxis *a1, const TAxis *a2)
Check that axis have same labels.
Definition: TH1.cxx:1382
Array of shorts (16 bits per element).
Definition: TArrayS.h:29
SVector< double, 2 > v
Definition: Dict.h:5
if object ctor succeeded but object should not be used
Definition: TObject.h:70
TH1 * R__H(Int_t hid)
return pointer to histogram with name hid if id >=0 h_id if id <0
Definition: TH1.cxx:9429
virtual void SetFillColor(Color_t fcolor)
Set the fill area color.
Definition: TAttFill.h:42
Int_t GetNbins() const
Definition: TAxis.h:127
virtual char * GetObjectInfo(Int_t px, Int_t py) const
Redefines TObject::GetObjectInfo.
Definition: TH1.cxx:4092
A 3-Dim function with parameters.
Definition: TF3.h:30
virtual Double_t GetBinUpEdge(Int_t bin) const
Return up edge of bin.
Definition: TAxis.cxx:514
friend TH1I operator+(const TH1I &h1, const TH1I &h2)
Operator +.
Definition: TH1.cxx:9025
void SetCanExtend(Bool_t canExtend)
Definition: TAxis.h:92
tomato 1-D histogram with an int per channel (see TH1 documentation)}
Definition: TH1.h:534
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:7108
virtual const char * ClassName() const
Returns name of class to which the object belongs.
Definition: TObject.cxx:188
virtual TObject * Remove(TObject *obj)
Remove object from the list.
Definition: TList.cxx:675
virtual void Copy(TObject &hnew) const
Copy this to newth1.
Definition: TH1.cxx:8976
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:33
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:8378
static TVirtualFFT * FFT(Int_t ndim, Int_t *n, Option_t *option)
Returns a pointer to the FFT of requested size and type.
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:8280
virtual Color_t GetFillColor() const
Return the fill area color.
Definition: TAttFill.h:35
Collection abstract base class.
Definition: TCollection.h:48
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:7316
static Int_t fgBufferSize
!default buffer size for automatic histograms
Definition: TH1.h:128
virtual TH1 * Rebin(Int_t ngroup=2, const char *newname="", const Double_t *xbins=0)
Rebin this histogram.
Definition: TH1.cxx:5578
void Form(const char *fmt,...)
Formats a string using a printf style format descriptor.
Definition: TString.cxx:2322
Double_t fEntries
Number of entries.
Definition: TH1.h:109
virtual Double_t GetMeanError(Int_t axis=1) const
Return standard error of mean of this histogram along the X axis.
Definition: TH1.cxx:6748
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
Bool_t TestBit(UInt_t f) const
Definition: TObject.h:159
virtual void LabelsDeflate(Option_t *axis="X")
Reduce the number of bins for the axis passed in the option to the number of bins having a label...
Definition: TH1.cxx:4783
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:3254
TMarker * m
Definition: textangle.C:8
char * Form(const char *fmt,...)
virtual void Transform()=0
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 Double_t GetSumOfWeights() const
Return the sum of weights excluding under/overflows.
Definition: TH1.cxx:7057
Double_t E()
Definition: TMath.h:54
virtual TH1 * ShowBackground(Int_t niter=20, Option_t *option="same")
This function calculates the background spectrum in this histogram.
Definition: TH1.cxx:8345
virtual void SetBinsLength(Int_t n=-1)
Set total number of bins including under/overflow Reallocate bin contents array.
Definition: TH1.cxx:8994
virtual ~TH1C()
Destructor.
Definition: TH1.cxx:8580
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:3402
virtual Int_t GetNbinsZ() const
Definition: TH1.h:303
short Short_t
Definition: RtypesCore.h:35
TLine * l
Definition: textangle.C:4
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:967
virtual const char * GetName() const
Returns name of object.
Definition: TNamed.h:51
virtual Int_t GetSumw2N() const
Definition: TH1.h:319
virtual void SetMarkerStyle(Style_t mstyle=1)
Set the marker style.
Definition: TAttMarker.h:45
virtual Double_t GetKurtosis(Int_t axis=1) const
Definition: TH1.cxx:6892
TAxis * GetYaxis()
Definition: TH1.h:325
Class describing the binned data sets : vectors of x coordinates, y values and optionally error on y ...
Definition: BinData.h:61
Bin contents are average (used by Add)
Definition: TH1.h:178
virtual void GetPointComplex(Int_t ipoint, Double_t &re, Double_t &im, Bool_t fromInput=kFALSE) const =0
float xmax
Definition: THbookFile.cxx:93
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:1832
Double_t * fIntegral
!Integral of bins used by GetRandom
Definition: TH1.h:125
virtual Int_t * GetN() const =0
Bool_t IsNull() const
Definition: TString.h:387
virtual TObjLink * FirstLink() const
Definition: TList.h:101
static bool CheckConsistency(const TH1 *h1, const TH1 *h2)
Check histogram compatibility.
Definition: TH1.cxx:1498
void SetName(const char *name)
Definition: TCollection.h:116
A 2-Dim function with parameters.
Definition: TF2.h:33
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:4453
TH1()
Histogram default constructor.
Definition: TH1.cxx:548
R__EXTERN TRandom * gRandom
Definition: TRandom.h:66
virtual Color_t GetLineColor() const
Return the line color.
Definition: TAttLine.h:39
tomato 1-D histogram with a double per channel (see TH1 documentation)}
Definition: TH1.h:618
static Int_t GetDefaultBufferSize()
Static function return the default buffer size for automatic histograms the parameter fgBufferSize ma...
Definition: TH1.cxx:4038
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:36
virtual void Rebuild(Option_t *option="")
Using the current bin info, recompute the arrays for contents and errors.
Definition: TH1.cxx:6359
if object destructor must call RecursiveRemove()
Definition: TObject.h:64
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:46
friend TH1I operator/(const TH1I &h1, const TH1I &h2)
Operator /.
Definition: TH1.cxx:9058
REAL epsilon
Definition: triangle.c:617
virtual void SetTitleColor(Color_t color=1)
Set color of axis title.
Definition: TAttAxis.cxx:281
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:5867
EBinErrorOpt fBinStatErrOpt
option for bin statistical errors
Definition: TH1.h:127
virtual Int_t GetXlast() const
const Double_t * GetArray() const
Definition: TArrayD.h:45
errors with Normal (Wald) approximation: errorUp=errorLow= sqrt(N)
Definition: TH1.h:86
#define R__LOCKGUARD2(mutex)
Int_t GetSize() const
Definition: TArray.h:49
virtual void Copy(TObject &hnew) const
Copy this to newth1.
Definition: TH1.cxx:9335
TVirtualFFT is an interface class for Fast Fourier Transforms.
Definition: TVirtualFFT.h:92
Double_t Pi()
Definition: TMath.h:44
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:8028
friend TH1I operator*(Double_t c1, const TH1I &h1)
Operator *.
Definition: TH1.cxx:9014
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:616
virtual Int_t ReadClassBuffer(const TClass *cl, void *pointer, const TClass *onfile_class=0)=0
Double_t fTsumw2
Total Sum of squares of weights.
Definition: TH1.h:111
virtual Int_t GetNdim() const =0
virtual Int_t GetSize() const
Definition: TCollection.h:95
return c2
Definition: legend2.C:14
static const double x1[5]
virtual TObject * Remove(TObject *)
Remove an object from the in-memory list.
#define ClassImp(name)
Definition: Rtypes.h:279
class describing the range in the coordinates it supports multiple range in a coordinate.
Definition: DataRange.h:34
Int_t GetLwb() const
Definition: TVectorT.h:79
virtual const char * GetName() const
Returns name of object.
Definition: TObject.cxx:416
double Double_t
Definition: RtypesCore.h:55
Int_t * fArray
Definition: TArrayI.h:32
void SetHistLineStyle(Style_t styl=0)
Definition: TStyle.h:372
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:6568
Double_t fTsumw
Total Sum of weights.
Definition: TH1.h:110
friend TH1D operator*(Double_t c1, const TH1D &h1)
Operator *.
Definition: TH1.cxx:9372
virtual void Copy(TObject &axis) const
Copy axis structure to another axis.
Definition: TAxis.cxx:208
Describe directory structure in memory.
Definition: TDirectory.h:44
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:1064
virtual Style_t GetLabelFont() const
Definition: TAttAxis.h:44
unsigned long ULong_t
Definition: RtypesCore.h:51
Double_t GetXmax() const
Definition: TAxis.h:140
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 Int_t GetNdivisions() const
Definition: TAttAxis.h:41
TH1I & operator=(const TH1I &h1)
Operator =.
Definition: TH1.cxx:9004
The TH1 histogram class.
Definition: TH1.h:80
you should not use this method at all Int_t Int_t Double_t Double_t Double_t e
Definition: TRolke.cxx:630
void forward(const LAYERDATA &prevLayerData, LAYERDATA &currLayerData)
apply the weights (and functions) in forward direction of the DNN
Definition: NeuralNet.icc:539
THist< 2, double, THistStatContent, THistStatUncertainty > TH2D
Definition: THist.hxx:307
Color_t GetHistLineColor() const
Definition: TStyle.h:234
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:3475
virtual Int_t GetMinimumBin() const
Return location of bin with minimum value in the range.
Definition: TH1.cxx:7736
static bool IsEquidistantBinning(const TAxis &axis)
Test if the binning is equidistant.
Definition: TH1.cxx:5173
Short_t fBarOffset
(1000*offset) for bar charts or legos
Definition: TH1.h:107
virtual void SetLineStyle(Style_t lstyle)
Set the line style.
Definition: TAttLine.h:48
double Stat_t
Definition: RtypesCore.h:73
Array of doubles (64 bits per element).
Definition: TArrayD.h:29
virtual UInt_t GetUniqueID() const
Return the unique object id.
Definition: TObject.cxx:434
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:2229
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:8498
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.
virtual Int_t GetXfirst() const
Int_t GetLast() const
Return last bin on the axis i.e.
Definition: TAxis.cxx:455
TAxis * GetZaxis()
Definition: TH1.h:326
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:5930
virtual Double_t GetBinCenter(Int_t bin) const
Return center of bin.
Definition: TAxis.cxx:464
Mother of all ROOT objects.
Definition: TObject.h:44
virtual void SetBinsLength(Int_t n=-1)
Set total number of bins including under/overflow Reallocate bin contents array.
Definition: TH1.cxx:8813
you should not use this method at all Int_t Int_t z
Definition: TRolke.cxx:630
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:3501
virtual void ClearUnderflowAndOverflow()
Remove all the content from the underflow and overflow bins, without changing the number of entries A...
Definition: TH1.cxx:2338
virtual TObject * First() const
Return the first object in the list. Returns 0 when list is empty.
Definition: TList.cxx:557
virtual Float_t GetLabelSize() const
Definition: TAttAxis.h:46
char Char_t
Definition: RtypesCore.h:29
virtual Int_t GetNbinsY() const
Definition: TH1.h:302
TH1S & operator=(const TH1S &h1)
Operator =.
Definition: TH1.cxx:8823
virtual Double_t GetBinErrorSqUnchecked(Int_t bin) const
Definition: TH1.h:443
THashList * GetLabels() const
Definition: TAxis.h:123
Double_t fMaximum
Maximum value for plotting.
Definition: TH1.h:114
virtual Color_t GetMarkerColor() const
Return the marker color.
Definition: TAttMarker.h:36
virtual void DirectoryAutoAdd(TDirectory *)
Perform the automatic addition of the histogram to the given directory.
Definition: TH1.cxx:2569
TVirtualHistPainter * fPainter
!pointer to histogram painter
Definition: TH1.h:126
friend TH1C operator/(const TH1C &h1, const TH1C &h2)
Operator /.
Definition: TH1.cxx:8695
friend TH1S operator*(Double_t c1, const TH1S &h1)
Operator *.
Definition: TH1.cxx:8832
virtual void GetCenter(Double_t *center) const
Return an array with the center of all bins.
Definition: TAxis.cxx:539
static Bool_t RejectedPoint()
See TF1::RejectPoint above.
Definition: TF1.cxx:3411
virtual void DrawPanel()
Display a panel with all histogram drawing options.
Definition: TH1.cxx:2958
virtual Int_t FindFixBin(Double_t x) const
Find bin number corresponding to abscissa x.
Definition: TAxis.cxx:405
virtual void Add(TObject *obj)
Definition: TList.h:81
Int_t fBufferSize
fBuffer size
Definition: TH1.h:121
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:635
virtual void Copy(TObject &hnew) const
Copy this histogram structure to newth1.
Definition: TH1.cxx:2470
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:3230
Short_t Max(Short_t a, Short_t b)
Definition: TMathBase.h:202
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:2319
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
Definition: TString.h:567
virtual void Copy(TObject &hnew) const
Copy this to newth1.
Definition: TH1.cxx:9156
1-Dim function class
Definition: TF1.h:149
virtual void SetBinsLength(Int_t=-1)
Definition: TH1.h:377
Int_t IsNaN(Double_t x)
Definition: TMath.h:613
virtual TObject * GetObjectFit() const
Char_t * fArray
Definition: TArrayC.h:32
tomato 1-D histogram with a byte per channel (see TH1 documentation)
Definition: TH1.h:452
virtual void Sumw2(Bool_t flag=kTRUE)
Create structure to store sum of squares of weights.
Definition: TH1.cxx:8087
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:1191
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 Ceil(Double_t x)
Definition: TMath.h:467
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:1257
virtual Bool_t CanExtendAllAxes() const
Returns true if all axes are extendable.
Definition: TH1.cxx:5917
Int_t fDimension
!Histogram dimension (1, 2 or 3 dim)
Definition: TH1.h:124
THist< 1, double, THistStatContent, THistStatUncertainty > TH1D
Definition: THist.hxx:301
#define gPad
Definition: TVirtualPad.h:289
void Reset()
Definition: TArrayI.h:49
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 BufferEmpty(Int_t action=0)
Fill histogram with all entries in the buffer.
Definition: TH1.cxx:1238
virtual void SetParent(TObject *obj)
Definition: TAxis.h:163
void Set(Int_t n)
Set size of this array to n floats.
Definition: TArrayF.cxx:105
virtual ~TH1D()
Destructor.
Definition: TH1.cxx:9320
virtual void SetEntries(Double_t n)
Definition: TH1.h:387
TAxis fXaxis
X axis descriptor.
Definition: TH1.h:104
#define gDirectory
Definition: TDirectory.h:221
const TArrayD * GetXbins() const
Definition: TAxis.h:136
void ResetBit(UInt_t f)
Definition: TObject.h:158
virtual void SetParameter(Int_t param, Double_t value)
Definition: TF1.h:431
virtual void AddBinContent(Int_t bin)
Increment bin content by 1.
Definition: TH1.cxx:8957
virtual void SetTitle(const char *title)
Change (i.e.
Definition: TH1.cxx:5984
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 Double_t GetStdDev(Int_t axis=1) const
Returns the Standard Deviation (Sigma).
Definition: TH1.cxx:6771
Definition: first.py:1
const int nn
virtual Int_t Poisson(Double_t mean)
Generates a random integer N according to a Poisson law.
Definition: TRandom.cxx:362
Double_t Sqrt(Double_t x)
Definition: TMath.h:464
virtual void GetMinimumAndMaximum(Double_t &min, Double_t &max) const
Retrieve the minimum and maximum values in the histogram.
Definition: TH1.cxx:7802
virtual void AddBinContent(Int_t bin)
Increment bin content by 1.
Definition: TH1.cxx:8595
Ssiz_t Index(const char *pat, Ssiz_t i=0, ECaseCompare cmp=kExact) const
Definition: TString.h:582
virtual Bool_t IsInside(const Double_t *x) const
return kTRUE if the point is inside the function range
Definition: TF1.h:411
virtual void Set(Int_t nbins, Double_t xmin, Double_t xmax)
Initialize axis with fix bins.
Definition: TAxis.cxx:716
virtual Double_t GetBinError(Int_t bin) const
Return value of error associated to bin number bin.
Definition: TH1.cxx:8130
virtual Style_t GetMarkerStyle() const
Return the marker style.
Definition: TAttMarker.h:37
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:7621
const Bool_t kTRUE
Definition: Rtypes.h:91
float * q
Definition: THbookFile.cxx:87
virtual Width_t GetLineWidth() const
Return the line width.
Definition: TAttLine.h:41
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:5156
virtual Double_t EvalPar(const Double_t *x, const Double_t *params=0)
Evaluate function with given coordinates and parameters.
Definition: TF1.cxx:1220
virtual Float_t GetTickLength() const
Definition: TAttAxis.h:49
virtual Double_t GetPointReal(Int_t ipoint, Bool_t fromInput=kFALSE) const =0
virtual void SetTitle(const char *title="")
Set the title of the TNamed.
Definition: TNamed.cxx:155
void SetHistLineColor(Color_t color=1)
Definition: TStyle.h:370
virtual Float_t GetBarWidth() const
Definition: TH1.h:261
Double_t * fBuffer
[fBufferSize] entry buffer
Definition: TH1.h:122
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:4555
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:3565
double norm(double *x, double *p)
Definition: unuranDistr.cxx:40
Int_t Nint(T x)
Definition: TMath.h:480
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:8508
void Set(Int_t n)
Set size of this array to n doubles.
Definition: TArrayD.cxx:105
virtual TF1 * GetFunction(const char *name) const
Return pointer to function with name.
Definition: TH1.cxx:8118
static bool CheckEqualAxes(const TAxis *a1, const TAxis *a2)
Check that the axis are the same.
Definition: TH1.cxx:1427
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:8761
const Int_t n
Definition: legend1.C:16
Line Attributes class.
Definition: TAttLine.h:24
virtual Int_t GetNpar() const
Definition: TF1.h:349
void H1InitPolynom()
Compute Initial values of parameters for a polynom.
Definition: TH1.cxx:4318
virtual void SetStats(Bool_t stats=kTRUE)
Set statistics option on/off.
Definition: TH1.cxx:8058
TH1F & operator=(const TH1F &h1)
Operator =.
Definition: TH1.cxx:9184
Long64_t BinarySearch(Long64_t n, const T *array, T value)
Definition: TMath.h:931
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:7706
virtual Double_t GetContourLevel(Int_t level) const
Return value of contour number level.
Definition: TH1.cxx:7509
char name[80]
Definition: TGX11.cxx:109
virtual Double_t GetContourLevelPad(Int_t level) const
Return the value of contour number "level" in Pad coordinates.
Definition: TH1.cxx:7519
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:4665
virtual Float_t GetBarOffset() const
Definition: TH1.h:260
TAxis * GetXaxis()
Definition: TH1.h:324
virtual void SetBinsLength(Int_t n=-1)
Set total number of bins including under/overflow Reallocate bin contents array.
Definition: TH1.cxx:8632
virtual Long64_t Merge(TCollection *list)
Add all histograms in the collection to this histogram.
Definition: TH1.cxx:5313
virtual Version_t ReadVersion(UInt_t *start=0, UInt_t *bcnt=0, const TClass *cl=0)=0
virtual Int_t ReadArray(Bool_t *&b)=0
Int_t fNcells
number of bins(1D), cells (2D) +U/Overflows
Definition: TH1.h:103
T MinElement(Long64_t n, const T *a)
Definition: TMath.h:668
virtual Float_t GetLabelOffset() const
Definition: TAttAxis.h:45
void H1LeastSquareLinearFit(Int_t ndata, Double_t &a0, Double_t &a1, Int_t &ifail)
Least square linear fit without weights.
Definition: TH1.cxx:4407
Array of chars or bytes (8 bits per element).
Definition: TArrayC.h:29
virtual void SavePrimitive(std::ostream &out, Option_t *option="")
Save a primitive as a C++ statement(s) on output stream "out".
Definition: TObject.cxx:709
Double_t ATan(Double_t)
Definition: TMath.h:451
virtual void Warning(const char *method, const char *msgfmt,...) const
Issue warning message.
Definition: TObject.cxx:911