ROOT  6.07/01
Reference Guide
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
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 "TF2.h"
26 #include "TF3.h"
27 #include "TPluginManager.h"
28 #include "TVirtualPad.h"
29 #include "TRandom.h"
30 #include "TVirtualFitter.h"
31 #include "THLimitsFinder.h"
32 #include "TProfile.h"
33 #include "TStyle.h"
34 #include "TVectorF.h"
35 #include "TVectorD.h"
36 #include "TBrowser.h"
37 #include "TObjString.h"
38 #include "TError.h"
39 #include "TVirtualHistPainter.h"
40 #include "TVirtualFFT.h"
41 #include "TSystem.h"
42 
43 #include "HFitInterface.h"
44 #include "Fit/DataRange.h"
45 #include "Fit/BinData.h"
46 #include "Math/GoFTest.h"
47 #include "Math/MinimizerOptions.h"
48 #include "Math/QuantFuncMathCore.h"
49 
50 /** \addtogroup Hist
51 @{
52 \class TH1C \brief tomato 1-D histogram with a bype per channel (see TH1 documentation)
53 \class TH1S \brief tomato 1-D histogram with a short per channel (see TH1 documentation)
54 \class TH1I \brief tomato 1-D histogram with a int per channel (see TH1 documentation)}
55 \class TH1F \brief tomato 1-D histogram with a float per channel (see TH1 documentation)}
56 \class TH1D \brief tomato 1-D histogram with a double per channel (see TH1 documentation)}
57 @}
58 */
59 
60 ////////////////////////////////////////////////////////////////////////////////
61 /** \class TH1
62 The TH1 histogram class
63 <h2>The Histogram classes</h2>
64 ROOT supports the following histogram types:
65 <ul>
66  <li>1-D histograms:
67  <ul>
68  <li>TH1C : histograms with one byte per channel. Maximum bin content = 127
69  <li>TH1S : histograms with one short per channel. Maximum bin content = 32767
70  <li>TH1I : histograms with one int per channel. Maximum bin content = 2147483647
71  <li>TH1F : histograms with one float per channel. Maximum precision 7 digits
72  <li>TH1D : histograms with one double per channel. Maximum precision 14 digits
73  </ul>
74 
75  <li>2-D histograms:
76  <ul>
77  <li>TH2C : histograms with one byte per channel. Maximum bin content = 127
78  <li>TH2S : histograms with one short per channel. Maximum bin content = 32767
79  <li>TH2I : histograms with one int per channel. Maximum bin content = 2147483647
80  <li>TH2F : histograms with one float per channel. Maximum precision 7 digits
81  <li>TH2D : histograms with one double per channel. Maximum precision 14 digits
82  </ul>
83 
84  <li>3-D histograms:
85  <ul>
86  <li>TH3C : histograms with one byte per channel. Maximum bin content = 127
87  <li>TH3S : histograms with one short per channel. Maximum bin content = 32767
88  <li>TH3I : histograms with one int per channel. Maximum bin content = 2147483647
89  <li>TH3F : histograms with one float per channel. Maximum precision 7 digits
90  <li>TH3D : histograms with one double per channel. Maximum precision 14 digits
91  </ul>
92  <li>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 </ul>
101 
102 All histogram classes are derived from the base class TH1
103 <pre>
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 </pre>
137 
138 <h4>Creating histograms</h4>
139 <p>
140  Histograms are created by invoking one of the constructors, e.g.
141 <pre>
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 </pre>
145 <p> Histograms may also be created by:
146  <ul>
147  <li> calling the Clone function, see below
148  <li> making a projection from a 2-D or 3-D histogram, see below
149  <li> reading an histogram from a file
150  </ul>
151 <p> 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 <pre>
155  h->SetDirectory(0); for the current histogram h
156  TH1::AddDirectory(kFALSE); sets a global switch disabling the reference
157 </pre>
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 <h4>Fix or variable bin size</h4>
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 <pre>
173  TAxis *xaxis = h->GetXaxis(); etc.
174  Double_t binCenter = xaxis->GetBinCenter(bin), etc.
175 </pre>
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 <h4>Convention for numbering bins</h4>
180 
181  For all histogram types: nbins, xlow, xup
182 <pre>
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 </pre>
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 <pre>
191  Int_t gbin = h->GetBin(binx, biny, binz);
192 </pre>
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 <pre>
198  Double_t xcenter = h3->GetZaxis()->GetBinCenter(27);
199 </pre>
200  returns the center along z of bin number 27 (not the global bin)
201  in the 3-D histogram h3.
202 
203 <h4>Alphanumeric Bin Labels</h4>
204 
205  By default, an histogram axis is drawn with its numeric bin labels.
206  One can specify alphanumeric labels instead with:
207 <ul>
208  <li> 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 example in $ROOTSYS/tutorials/graphs/labels1.C, labels2.C
212  <li> call to a Fill function with one of the arguments being a string, e.g.
213 <pre>
214  hist1->Fill(somename, weigth);
215  hist2->Fill(x, somename, weight);
216  hist2->Fill(somename, y, weight);
217  hist2->Fill(somenamex, somenamey, weight);
218 </pre>
219  See example in $ROOTSYS/tutorials/hist/hlabels1.C, hlabels2.C
220  <li> via TTree::Draw.
221  see for example $ROOTSYS/tutorials/tree/cernstaff.C
222 <pre>
223  tree.Draw("Nation::Division");
224 </pre>
225  where "Nation" and "Division" are two branches of a Tree.
226 </ul>
227 
228 <p>When using the options 2 or 3 above, the labels are automatically
229  added to the list (THashList) of labels for a given axis.
230  By default, an axis is drawn with the order of bins corresponding
231  to the filling sequence. It is possible to reorder the axis
232 
233 <ul>
234  <li>alphabetically
235  <li>by increasing or decreasing values
236 </ul>
237 
238 <p> The reordering can be triggered via the TAxis context menu by selecting
239  the menu item "LabelsOption" or by calling directly
240  TH1::LabelsOption(option, axis) where
241 <ul>
242  <li>axis may be "X", "Y" or "Z"
243  <li>option may be:
244  <ul>
245  <li>"a" sort by alphabetic order
246  <li>">" sort by decreasing values
247  <li>"<" sort by increasing values
248  <li>"h" draw labels horizontal
249  <li>"v" draw labels vertical
250  <li>"u" draw labels up (end of label right adjusted)
251  <li>"d" draw labels down (start of label left adjusted)
252  </ul>
253 </ul>
254 <p> When using the option 2 above, new labels are added by doubling the current
255  number of bins in case one label does not exist yet.
256  When the Filling is terminated, it is possible to trim the number
257  of bins to match the number of active labels by calling
258 <pre>
259  TH1::LabelsDeflate(axis) with axis = "X", "Y" or "Z"
260 </pre>
261  This operation is automatic when using TTree::Draw.
262  Once bin labels have been created, they become persistent if the histogram
263  is written to a file or when generating the C++ code via SavePrimitive.
264 
265 <h4>Histograms with automatic bins</h4>
266 
267  When an histogram is created with an axis lower limit greater or equal
268  to its upper limit, the SetBuffer is automatically called with an
269  argument fBufferSize equal to fgBufferSize (default value=1000).
270  fgBufferSize may be reset via the static function TH1::SetDefaultBufferSize.
271  The axis limits will be automatically computed when the buffer will
272  be full or when the function BufferEmpty is called.
273 
274 <h4>Filling histograms</h4>
275 
276  An histogram is typically filled with statements like:
277 <pre>
278  h1->Fill(x);
279  h1->Fill(x, w); //fill with weight
280  h2->Fill(x, y)
281  h2->Fill(x, y, w)
282  h3->Fill(x, y, z)
283  h3->Fill(x, y, z, w)
284 </pre>
285  or via one of the Fill functions accepting names described above.
286  The Fill functions compute the bin number corresponding to the given
287  x, y or z argument and increment this bin by the given weight.
288  The Fill functions return the bin number for 1-D histograms or global
289  bin number for 2-D and 3-D histograms.
290 <p> If TH1::Sumw2 has been called before filling, the sum of squares of
291  weights is also stored.
292  One can also increment directly a bin number via TH1::AddBinContent
293  or replace the existing content via TH1::SetBinContent.
294  To access the bin content of a given bin, do:
295 <pre>
296  Double_t binContent = h->GetBinContent(bin);
297 </pre>
298 
299 <p> By default, the bin number is computed using the current axis ranges.
300  If the automatic binning option has been set via
301 <pre>
302  h->SetCanExtend(kAllAxes);
303 </pre>
304  then, the Fill Function will automatically extend the axis range to
305  accomodate the new value specified in the Fill argument. The method
306  used is to double the bin size until the new value fits in the range,
307  merging bins two by two. This automatic binning options is extensively
308  used by the TTree::Draw function when histogramming Tree variables
309  with an unknown range.
310 <p> This automatic binning option is supported for 1-D, 2-D and 3-D histograms.
311 
312  During filling, some statistics parameters are incremented to compute
313  the mean value and Root Mean Square with the maximum precision.
314 
315 <p> In case of histograms of type TH1C, TH1S, TH2C, TH2S, TH3C, TH3S
316  a check is made that the bin contents do not exceed the maximum positive
317  capacity (127 or 32767). Histograms of all types may have positive
318  or/and negative bin contents.
319 
320 <h4>Rebinning</h4>
321  At any time, an histogram can be rebinned via TH1::Rebin. This function
322  returns a new histogram with the rebinned contents.
323  If bin errors were stored, they are recomputed during the rebinning.
324 
325 <h4>Associated errors</h4>
326  By default, for each bin, the sum of weights is computed at fill time.
327  One can also call TH1::Sumw2 to force the storage and computation
328  of the sum of the square of weights per bin.
329  If Sumw2 has been called, the error per bin is computed as the
330  sqrt(sum of squares of weights), otherwise the error is set equal
331  to the sqrt(bin content).
332  To return the error for a given bin number, do:
333 <pre>
334  Double_t error = h->GetBinError(bin);
335 </pre>
336 
337 <h4>Associated functions</h4>
338  One or more object (typically a TF1*) can be added to the list
339  of functions (fFunctions) associated to each histogram.
340  When TH1::Fit is invoked, the fitted function is added to this list.
341  Given an histogram h, one can retrieve an associated function
342  with:
343 <pre>
344  TF1 *myfunc = h->GetFunction("myfunc");
345 </pre>
346 
347 <h4>Operations on histograms</h4>
348 
349  Many types of operations are supported on histograms or between histograms
350 <ul>
351  <li> Addition of an histogram to the current histogram.
352  <li> Additions of two histograms with coefficients and storage into the current
353  histogram.
354  <li> Multiplications and Divisions are supported in the same way as additions.
355  <li> The Add, Divide and Multiply functions also exist to add, divide or multiply
356  an histogram by a function.
357 </ul>
358  If an histogram has associated error bars (TH1::Sumw2 has been called),
359  the resulting error bars are also computed assuming independent histograms.
360  In case of divisions, Binomial errors are also supported.
361  One can mark a histogram to be an "average" histogram by setting its bit kIsAverage via
362  myhist.SetBit(TH1::kIsAverage);
363  When adding (see TH1::Add) average histograms, the histograms are averaged and not summed.
364 
365 <h4>Fitting histograms</h4>
366 
367  Histograms (1-D, 2-D, 3-D and Profiles) can be fitted with a user
368  specified function via TH1::Fit. When an histogram is fitted, the
369  resulting function with its parameters is added to the list of functions
370  of this histogram. If the histogram is made persistent, the list of
371  associated functions is also persistent. Given a pointer (see above)
372  to an associated function myfunc, one can retrieve the function/fit
373  parameters with calls such as:
374 <pre>
375  Double_t chi2 = myfunc->GetChisquare();
376  Double_t par0 = myfunc->GetParameter(0); value of 1st parameter
377  Double_t err0 = myfunc->GetParError(0); error on first parameter
378 </pre>
379 
380 <h4>Projections of histograms</h4>
381 
382 <p> One can:
383 <ul>
384  <li> make a 1-D projection of a 2-D histogram or Profile
385  see functions TH2::ProjectionX,Y, TH2::ProfileX,Y, TProfile::ProjectionX
386  <li> make a 1-D, 2-D or profile out of a 3-D histogram
387  see functions TH3::ProjectionZ, TH3::Project3D.
388 </ul>
389 
390 <p> One can fit these projections via:
391 <pre>
392  TH2::FitSlicesX,Y, TH3::FitSlicesZ.
393 </pre>
394 
395 <h4>Random Numbers and histograms</h4>
396 
397  TH1::FillRandom can be used to randomly fill an histogram using
398  the contents of an existing TF1 function or another
399  TH1 histogram (for all dimensions).
400 <p> For example the following two statements create and fill an histogram
401  10000 times with a default gaussian distribution of mean 0 and sigma 1:
402 <pre>
403  TH1F h1("h1", "histo from a gaussian", 100, -3, 3);
404  h1.FillRandom("gaus", 10000);
405 </pre>
406  TH1::GetRandom can be used to return a random number distributed
407  according the contents of an histogram.
408 
409 <h4>Making a copy of an histogram</h4>
410  Like for any other ROOT object derived from TObject, one can use
411  the Clone() function. This makes an identical copy of the original
412  histogram including all associated errors and functions, e.g.:
413 <pre>
414  TH1F *hnew = (TH1F*)h->Clone("hnew");
415 </pre>
416 
417 <h4>Normalizing histograms</h4>
418 
419  One can scale an histogram such that the bins integral is equal to
420  the normalization parameter via TH1::Scale(Double_t norm), where norm
421  is the desired normalization divided by the integral of the histogram.
422 
423 <h4>Drawing histograms</h4>
424 
425  Histograms are drawn via the THistPainter class. Each histogram has
426  a pointer to its own painter (to be usable in a multithreaded program).
427  Many drawing options are supported.
428  See THistPainter::Paint() for more details.
429 <p>
430  The same histogram can be drawn with different options in different pads.
431  When an histogram drawn in a pad is deleted, the histogram is
432  automatically removed from the pad or pads where it was drawn.
433  If an histogram is drawn in a pad, then filled again, the new status
434  of the histogram will be automatically shown in the pad next time
435  the pad is updated. One does not need to redraw the histogram.
436  To draw the current version of an histogram in a pad, one can use
437 <pre>
438  h->DrawCopy();
439 </pre>
440  This makes a clone (see Clone below) of the histogram. Once the clone
441  is drawn, the original histogram may be modified or deleted without
442  affecting the aspect of the clone.
443 <p>
444  One can use TH1::SetMaximum() and TH1::SetMinimum() to force a particular
445  value for the maximum or the minimum scale on the plot. (For 1-D
446  histograms this means the y-axis, while for 2-D histograms these
447  functions affect the z-axis).
448 <p>
449  TH1::UseCurrentStyle() can be used to change all histogram graphics
450  attributes to correspond to the current selected style.
451  This function must be called for each histogram.
452  In case one reads and draws many histograms from a file, one can force
453  the histograms to inherit automatically the current graphics style
454  by calling before gROOT->ForceStyle().
455 
456 
457 <h4>Setting Drawing histogram contour levels (2-D hists only)</h4>
458 
459  By default contours are automatically generated at equidistant
460  intervals. A default value of 20 levels is used. This can be modified
461  via TH1::SetContour() or TH1::SetContourLevel().
462  the contours level info is used by the drawing options "cont", "surf",
463  and "lego".
464 
465 <h4>Setting histogram graphics attributes</h4>
466 
467  The histogram classes inherit from the attribute classes:
468  TAttLine, TAttFill, and TAttMarker.
469  See the member functions of these classes for the list of options.
470 
471 <h4>Giving titles to the X, Y and Z axis</h4>
472 <pre>
473  h->GetXaxis()->SetTitle("X axis title");
474  h->GetYaxis()->SetTitle("Y axis title");
475 </pre>
476  The histogram title and the axis titles can be any TLatex string.
477  The titles are part of the persistent histogram.
478  It is also possible to specify the histogram title and the axis
479  titles at creation time. These titles can be given in the "title"
480  parameter. They must be separated by ";":
481 <pre>
482  TH1F* h=new TH1F("h", "Histogram title;X Axis;Y Axis;Z Axis", 100, 0, 1);
483 </pre>
484  Any title can be omitted:
485 <pre>
486  TH1F* h=new TH1F("h", "Histogram title;;Y Axis", 100, 0, 1);
487  TH1F* h=new TH1F("h", ";;Y Axis", 100, 0, 1);
488 </pre>
489  The method SetTitle has the same syntax:
490 <pre>
491 </pre>
492  h->SetTitle("Histogram title;Another X title Axis");
493 
494 <h4>Saving/Reading histograms to/from a ROOT file</h4>
495 
496  The following statements create a ROOT file and store an histogram
497  on the file. Because TH1 derives from TNamed, the key identifier on
498  the file is the histogram name:
499 <pre>
500  TFile f("histos.root", "new");
501  TH1F h1("hgaus", "histo from a gaussian", 100, -3, 3);
502  h1.FillRandom("gaus", 10000);
503  h1->Write();
504 </pre>
505  To read this histogram in another Root session, do:
506 <pre>
507  TFile f("histos.root");
508  TH1F *h = (TH1F*)f.Get("hgaus");
509 </pre>
510  One can save all histograms in memory to the file by:
511 <pre>
512  file->Write();
513 </pre>
514 
515 <h4>Miscelaneous operations</h4>
516 
517 <pre>
518  TH1::KolmogorovTest(): statistical test of compatibility in shape
519  between two histograms
520  TH1::Smooth() smooths the bin contents of a 1-d histogram
521  TH1::Integral() returns the integral of bin contents in a given bin range
522  TH1::GetMean(int axis) returns the mean value along axis
523  TH1::GetStdDev(int axis) returns the sigma distribution along axis
524  TH1::GetEntries() returns the number of entries
525  TH1::Reset() resets the bin contents and errors of an histogram
526 </pre>
527 */
528 
529 TF1 *gF1=0; //left for back compatibility (use TVirtualFitter::GetUserFunc instead)
530 
531 Int_t TH1::fgBufferSize = 1000;
535 
536 extern void H1InitGaus();
537 extern void H1InitExpo();
538 extern void H1InitPolynom();
539 extern void H1LeastSquareFit(Int_t n, Int_t m, Double_t *a);
540 extern void H1LeastSquareLinearFit(Int_t ndata, Double_t &a0, Double_t &a1, Int_t &ifail);
541 extern void H1LeastSquareSeqnd(Int_t n, Double_t *a, Int_t idim, Int_t &ifail, Int_t k, Double_t *b);
542 
543 // Internal exceptions for the CheckConsistency method
544 class DifferentDimension: public std::exception {};
545 class DifferentNumberOfBins: public std::exception {};
546 class DifferentAxisLimits: public std::exception {};
547 class DifferentBinLimits: public std::exception {};
548 class DifferentLabels: public std::exception {};
549 
551 
552 
553 ////////////////////////////////////////////////////////////////////////////////
554 /// Histogram default constructor.
555 
556 TH1::TH1(): TNamed(), TAttLine(), TAttFill(), TAttMarker()
557 {
558  fDirectory = 0;
559  fFunctions = new TList;
560  fNcells = 0;
561  fIntegral = 0;
562  fPainter = 0;
563  fEntries = 0;
564  fNormFactor = 0;
565  fTsumw = fTsumw2=fTsumwx=fTsumwx2=0;
566  fMaximum = -1111;
567  fMinimum = -1111;
568  fBufferSize = 0;
569  fBuffer = 0;
570  fBinStatErrOpt = kNormal;
571  fXaxis.SetName("xaxis");
572  fYaxis.SetName("yaxis");
573  fZaxis.SetName("zaxis");
574  fXaxis.SetParent(this);
575  fYaxis.SetParent(this);
576  fZaxis.SetParent(this);
577  UseCurrentStyle();
578 }
579 
580 
581 ////////////////////////////////////////////////////////////////////////////////
582 /// Histogram default destructor.
583 
585 {
586  if (!TestBit(kNotDeleted)) {
587  return;
588  }
589  delete[] fIntegral;
590  fIntegral = 0;
591  delete[] fBuffer;
592  fBuffer = 0;
593  if (fFunctions) {
595  TObject* obj = 0;
596  //special logic to support the case where the same object is
597  //added multiple times in fFunctions.
598  //This case happens when the same object is added with different
599  //drawing modes
600  //In the loop below we must be careful with objects (eg TCutG) that may
601  // have been added to the list of functions of several histograms
602  //and may have been already deleted.
603  while ((obj = fFunctions->First())) {
604  while(fFunctions->Remove(obj)) { }
605  if (!obj->TestBit(kNotDeleted)) {
606  break;
607  }
608  delete obj;
609  obj = 0;
610  }
611  delete fFunctions;
612  fFunctions = 0;
613  }
614  if (fDirectory) {
615  fDirectory->Remove(this);
616  fDirectory = 0;
617  }
618  delete fPainter;
619  fPainter = 0;
620 }
621 
622 
623 ////////////////////////////////////////////////////////////////////////////////
624 /// Normal constructor for fix bin size histograms. Creates the main histogram structure.
625 /// \param[in] name name of histogram (avoid blanks)
626 /// \param[in] title histogram title.
627 /// If title is of the form "stringt;stringx;stringy;stringz"
628 /// the histogram title is set to stringt,
629 /// the x axis title to stringy, the y axis title to stringy, etc.
630 /// \param[in] nbins number of bins
631 /// \param[in] xlow low edge of first bin
632 /// \param[in] xup upper edge of last bin (not included in last bin)
633 ///
634 /// When an histogram is created, it is automatically added to the list
635 /// of special objects in the current directory.
636 /// To find the pointer to this histogram in the current directory
637 /// by its name, do:
638 ///
639 /// TH1F *h1 = (TH1F*)gDirectory->FindObject(name);
640 
641 TH1::TH1(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
642  :TNamed(name,title), TAttLine(), TAttFill(), TAttMarker()
643 {
644  Build();
645  if (nbins <= 0) {Warning("TH1","nbins is <=0 - set to nbins = 1"); nbins = 1; }
646  fXaxis.Set(nbins,xlow,xup);
647  fNcells = fXaxis.GetNbins()+2;
648 }
649 
650 
651 ////////////////////////////////////////////////////////////////////////////////
652 /// Normal constructor for variable bin size histograms. Creates the main histogram structure.
653 /// \param[in] name name of histogram (avoid blanks)
654 /// \param[in] title histogram title.
655 /// If title is of the form "stringt;stringx;stringy;stringz"
656 /// the histogram title is set to stringt,
657 /// the x axis title to stringy, the y axis title to stringy, etc.
658 /// \param[in] nbins number of bins
659 /// \param[in] xbins array of low-edges for each bin.
660 /// This is an array of size nbins+1
661 
662 TH1::TH1(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
663  :TNamed(name,title), TAttLine(), TAttFill(), TAttMarker()
664 {
665  Build();
666  if (nbins <= 0) {Warning("TH1","nbins is <=0 - set to nbins = 1"); nbins = 1; }
667  if (xbins) fXaxis.Set(nbins,xbins);
668  else fXaxis.Set(nbins,0,1);
669  fNcells = fXaxis.GetNbins()+2;
670 }
671 
672 
673 ////////////////////////////////////////////////////////////////////////////////
674 /// Normal constructor for variable bin size histograms.
675 ///
676 /// \param[in] name name of histogram (avoid blanks)
677 /// \param[in] title histogram title.
678 /// If title is of the form "stringt;stringx;stringy;stringz"
679 /// the histogram title is set to stringt,
680 /// the x axis title to stringy, the y axis title to stringy, etc.
681 /// \param[in] nbins number of bins
682 /// \param[in] xbins array of low-edges for each bin.
683 /// This is an array of size nbins+1
684 
685 TH1::TH1(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
686  :TNamed(name,title), TAttLine(), TAttFill(), TAttMarker()
687 {
688  Build();
689  if (nbins <= 0) {Warning("TH1","nbins is <=0 - set to nbins = 1"); nbins = 1; }
690  if (xbins) fXaxis.Set(nbins,xbins);
691  else fXaxis.Set(nbins,0,1);
692  fNcells = fXaxis.GetNbins()+2;
693 }
694 
695 
696 ////////////////////////////////////////////////////////////////////////////////
697 /// Copy constructor.
698 /// The list of functions is not copied. (Use Clone if needed)
699 
701 {
702  ((TH1&)h).Copy(*this);
703 }
704 
705 
706 ////////////////////////////////////////////////////////////////////////////////
707 ///static function: cannot be inlined on Windows/NT
708 
710 {
711  return fgAddDirectory;
712 }
713 
714 
715 ////////////////////////////////////////////////////////////////////////////////
716 /// Browe the Histogram object.
717 
719 {
720  Draw(b ? b->GetDrawOption() : "");
721  gPad->Update();
722 }
723 
724 
725 ////////////////////////////////////////////////////////////////////////////////
726 /// Creates histogram basic data structure.
727 
729 {
730  fDirectory = 0;
731  fPainter = 0;
732  fIntegral = 0;
733  fEntries = 0;
734  fNormFactor = 0;
735  fTsumw = fTsumw2=fTsumwx=fTsumwx2=0;
736  fMaximum = -1111;
737  fMinimum = -1111;
738  fBufferSize = 0;
739  fBuffer = 0;
741  fXaxis.SetName("xaxis");
742  fYaxis.SetName("yaxis");
743  fZaxis.SetName("zaxis");
744  fYaxis.Set(1,0.,1.);
745  fZaxis.Set(1,0.,1.);
746  fXaxis.SetParent(this);
747  fYaxis.SetParent(this);
748  fZaxis.SetParent(this);
749 
750  SetTitle(fTitle.Data());
751 
752  fFunctions = new TList;
753 
754  UseCurrentStyle();
755 
756  if (TH1::AddDirectoryStatus()) {
758  if (fDirectory) {
759  fDirectory->Append(this,kTRUE);
760  }
761  }
762 }
763 
764 
765 ////////////////////////////////////////////////////////////////////////////////
766 /// Performs the operation: this = this + c1*f1
767 /// if errors are defined (see TH1::Sumw2), errors are also recalculated.
768 ///
769 /// By default, the function is computed at the centre of the bin.
770 /// if option "I" is specified (1-d histogram only), the integral of the
771 /// function in each bin is used instead of the value of the function at
772 /// the centre of the bin.
773 /// Only bins inside the function range are recomputed.
774 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
775 /// you should call Sumw2 before making this operation.
776 /// This is particularly important if you fit the histogram after TH1::Add
777 ///
778 /// The function return kFALSE if the Add operation failed
779 
781 {
782  if (!f1) {
783  Error("Add","Attempt to add a non-existing function");
784  return kFALSE;
785  }
786 
787  TString opt = option;
788  opt.ToLower();
789  Bool_t integral = kFALSE;
790  if (opt.Contains("i") && fDimension == 1) integral = kTRUE;
791 
792  Int_t ncellsx = GetNbinsX() + 2; // cells = normal bins + underflow bin + overflow bin
793  Int_t ncellsy = GetNbinsY() + 2;
794  Int_t ncellsz = GetNbinsZ() + 2;
795  if (fDimension < 2) ncellsy = 1;
796  if (fDimension < 3) ncellsz = 1;
797 
798  // delete buffer if it is there since it will become invalid
799  if (fBuffer) BufferEmpty(1);
800 
801  // - Add statistics
802  Double_t s1[10];
803  for (Int_t i = 0; i < 10; ++i) s1[i] = 0;
804  PutStats(s1);
805  SetMinimum();
806  SetMaximum();
807 
808  // - Loop on bins (including underflows/overflows)
809  Int_t bin, binx, biny, binz;
810  Double_t cu=0;
811  Double_t xx[3];
812  Double_t *params = 0;
813  f1->InitArgs(xx,params);
814  for (binz = 0; binz < ncellsz; ++binz) {
815  xx[2] = fZaxis.GetBinCenter(binz);
816  for (biny = 0; biny < ncellsy; ++biny) {
817  xx[1] = fYaxis.GetBinCenter(biny);
818  for (binx = 0; binx < ncellsx; ++binx) {
819  xx[0] = fXaxis.GetBinCenter(binx);
820  if (!f1->IsInside(xx)) continue;
822  bin = binx + ncellsx * (biny + ncellsy * binz);
823  if (integral) {
824  xx[0] = fXaxis.GetBinLowEdge(binx);
825  cu = c1*f1->EvalPar(xx);
826  cu += c1*f1->Integral(fXaxis.GetBinLowEdge(binx), fXaxis.GetBinUpEdge(binx)) * fXaxis.GetBinWidth(binx);
827  } else {
828  cu = c1*f1->EvalPar(xx);
829  }
830  if (TF1::RejectedPoint()) continue;
831  AddBinContent(bin,cu);
832  }
833  }
834  }
835 
836  return kTRUE;
837 }
838 
839 
840 ////////////////////////////////////////////////////////////////////////////////
841 /// Performs the operation: this = this + c1*h1
842 /// If errors are defined (see TH1::Sumw2), errors are also recalculated.
843 /// Note that if h1 has Sumw2 set, Sumw2 is automatically called for this
844 /// if not already set.
845 /// Note also that adding histogram with labels is not supported, histogram will be
846 /// added merging them by bin number independently of the labels.
847 /// For adding histogram with labels one should use TH1::Merge
848 ///
849 /// SPECIAL CASE (Average/Efficiency histograms)
850 /// For histograms representing averages or efficiencies, one should compute the average
851 /// of the two histograms and not the sum. One can mark a histogram to be an average
852 /// histogram by setting its bit kIsAverage with
853 /// myhist.SetBit(TH1::kIsAverage);
854 /// Note that the two histograms must have their kIsAverage bit set
855 ///
856 /// IMPORTANT NOTE1: If you intend to use the errors of this histogram later
857 /// you should call Sumw2 before making this operation.
858 /// This is particularly important if you fit the histogram after TH1::Add
859 ///
860 /// IMPORTANT NOTE2: if h1 has a normalisation factor, the normalisation factor
861 /// is used , ie this = this + c1*factor*h1
862 /// Use the other TH1::Add function if you do not want this feature
863 ///
864 /// The function return kFALSE if the Add operation failed
865 
867 {
868  if (!h1) {
869  Error("Add","Attempt to add a non-existing histogram");
870  return kFALSE;
871  }
872 
873  // delete buffer if it is there since it will become invalid
874  if (fBuffer) BufferEmpty(1);
875 
876  bool useMerge = (c1 == 1. && !this->TestBit(kIsAverage) && !h1->TestBit(kIsAverage) );
877  try {
878  CheckConsistency(this,h1);
879  useMerge = kFALSE;
880  } catch(DifferentNumberOfBins&) {
881  if (useMerge)
882  Info("Add","Attempt to add histograms with different number of bins - trying to use TH1::Merge");
883  else {
884  Error("Add","Attempt to add histograms with different number of bins : nbins h1 = %d , nbins h2 = %d",GetNbinsX(), h1->GetNbinsX());
885  return kFALSE;
886  }
887  } catch(DifferentAxisLimits&) {
888  if (useMerge)
889  Info("Add","Attempt to add histograms with different axis limits - trying to use TH1::Merge");
890  else
891  Warning("Add","Attempt to add histograms with different axis limits");
892  } catch(DifferentBinLimits&) {
893  if (useMerge)
894  Info("Add","Attempt to add histograms with different bin limits - trying to use TH1::Merge");
895  else
896  Warning("Add","Attempt to add histograms with different bin limits");
897  } catch(DifferentLabels&) {
898  // in case of different labels -
899  if (useMerge)
900  Info("Add","Attempt to add histograms with different labels - trying to use TH1::Merge");
901  else
902  Info("Warning","Attempt to add histograms with different labels");
903  }
904 
905  if (useMerge) {
906  TList l;
907  l.Add(const_cast<TH1*>(h1));
908  auto iret = Merge(&l);
909  return (iret >= 0);
910  }
911 
912  // Create Sumw2 if h1 has Sumw2 set
913  if (fSumw2.fN == 0 && h1->GetSumw2N() != 0) Sumw2();
914 
915  // - Add statistics
916  Double_t entries = TMath::Abs( GetEntries() + c1 * h1->GetEntries() );
917 
918  // statistics can be preserbed only in case of positive coefficients
919  // otherwise with negative c1 (histogram subtraction) one risks to get negative variances
920  Bool_t resetStats = (c1 < 0);
921  Double_t s1[kNstat] = {0};
922  Double_t s2[kNstat] = {0};
923  if (!resetStats) {
924  // need to initialize to zero s1 and s2 since
925  // GetStats fills only used elements depending on dimension and type
926  GetStats(s1);
927  h1->GetStats(s2);
928  }
929 
930  SetMinimum();
931  SetMaximum();
932 
933  // - Loop on bins (including underflows/overflows)
934  Double_t factor = 1;
935  if (h1->GetNormFactor() != 0) factor = h1->GetNormFactor()/h1->GetSumOfWeights();;
936  Double_t c1sq = c1 * c1;
937  Double_t factsq = factor * factor;
938 
939  for (Int_t bin = 0; bin < fNcells; ++bin) {
940  //special case where histograms have the kIsAverage bit set
941  if (this->TestBit(kIsAverage) && h1->TestBit(kIsAverage)) {
942  Double_t y1 = h1->RetrieveBinContent(bin);
943  Double_t y2 = this->RetrieveBinContent(bin);
944  Double_t e1sq = h1->GetBinErrorSqUnchecked(bin);
945  Double_t e2sq = this->GetBinErrorSqUnchecked(bin);
946  Double_t w1 = 1., w2 = 1.;
947 
948  // consider all special cases when bin errors are zero
949  // see http://root.cern.ch/phpBB3//viewtopic.php?f=3&t=13299
950  if (e1sq) w1 = 1. / e1sq;
951  else if (h1->fSumw2.fN) {
952  w1 = 1.E200; // use an arbitrary huge value
953  if (y1 == 0) {
954  // use an estimated error from the global histogram scale
955  double sf = (s2[0] != 0) ? s2[1]/s2[0] : 1;
956  w1 = 1./(sf*sf);
957  }
958  }
959  if (e2sq) w2 = 1. / e2sq;
960  else if (fSumw2.fN) {
961  w2 = 1.E200; // use an arbitrary huge value
962  if (y2 == 0) {
963  // use an estimated error from the global histogram scale
964  double sf = (s1[0] != 0) ? s1[1]/s1[0] : 1;
965  w2 = 1./(sf*sf);
966  }
967  }
968 
969  double y = (w1*y1 + w2*y2)/(w1 + w2);
970  UpdateBinContent(bin, y);
971  if (fSumw2.fN) {
972  double err2 = 1./(w1 + w2);
973  if (err2 < 1.E-200) err2 = 0; // to remove arbitrary value when e1=0 AND e2=0
974  fSumw2.fArray[bin] = err2;
975  }
976  } else { // normal case of addition between histograms
977  AddBinContent(bin, c1 * factor * h1->RetrieveBinContent(bin));
978  if (fSumw2.fN) fSumw2.fArray[bin] += c1sq * factsq * h1->GetBinErrorSqUnchecked(bin);
979  }
980  }
981 
982  // update statistics (do here to avoid changes by SetBinContent)
983  if (resetStats) {
984  // statistics need to be reset in case coefficient are negative
985  ResetStats();
986  }
987  else {
988  for (Int_t i=0;i<kNstat;i++) {
989  if (i == 1) s1[i] += c1*c1*s2[i];
990  else s1[i] += c1*s2[i];
991  }
992  PutStats(s1);
993  SetEntries(entries);
994  }
995  return kTRUE;
996 }
997 
998 
999 ////////////////////////////////////////////////////////////////////////////////
1000 /// Replace contents of this histogram by the addition of h1 and h2.
1001 ///
1002 ///this = c1*h1 + c2*h2
1003 ///if errors are defined (see TH1::Sumw2), errors are also recalculated
1004 ///Note that if h1 or h2 have Sumw2 set, Sumw2 is automatically called for this
1005 ///if not already set.
1006 ///Note also that adding histogram with labels is not supported, histogram will be
1007 ///added merging them by bin number independently of the labels.
1008 ///For adding histogram ith labels one should use TH1::Merge
1009 ///
1010 /// SPECIAL CASE (Average/Efficiency histograms)
1011 /// For histograms representing averages or efficiencies, one should compute the average
1012 /// of the two histograms and not the sum. One can mark a histogram to be an average
1013 /// histogram by setting its bit kIsAverage with
1014 /// myhist.SetBit(TH1::kIsAverage);
1015 /// Note that the two histograms must have their kIsAverage bit set
1016 ///
1017 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
1018 /// you should call Sumw2 before making this operation.
1019 /// This is particularly important if you fit the histogram after TH1::Add
1020 ///
1021 /// ANOTHER SPECIAL CASE : h1 = h2 and c2 < 0
1022 /// do a scaling this = c1 * h1 / (bin Volume)
1023 ///
1024 /// The function returns kFALSE if the Add operation failed
1025 
1027 {
1028 
1029  if (!h1 || !h2) {
1030  Error("Add","Attempt to add a non-existing histogram");
1031  return kFALSE;
1032  }
1033 
1034  // delete buffer if it is there since it will become invalid
1035  if (fBuffer) BufferEmpty(1);
1036 
1037  Bool_t normWidth = kFALSE;
1038  if (h1 == h2 && c2 < 0) {c2 = 0; normWidth = kTRUE;}
1039 
1040  if (h1 != h2) {
1041  bool useMerge = (c1 == 1. && c2 == 1. && !this->TestBit(kIsAverage) && !h1->TestBit(kIsAverage) );
1042 
1043  try {
1044  CheckConsistency(h1,h2);
1045  CheckConsistency(this,h1);
1046  useMerge = kFALSE;
1047  } catch(DifferentNumberOfBins&) {
1048  if (useMerge)
1049  Info("Add","Attempt to add histograms with different number of bins - trying to use TH1::Merge");
1050  else {
1051  Error("Add","Attempt to add histograms with different number of bins : nbins h1 = %d , nbins h2 = %d",GetNbinsX(), h1->GetNbinsX());
1052  return kFALSE;
1053  }
1054  } catch(DifferentAxisLimits&) {
1055  if (useMerge)
1056  Info("Add","Attempt to add histograms with different axis limits - trying to use TH1::Merge");
1057  else
1058  Warning("Add","Attempt to add histograms with different axis limits");
1059  } catch(DifferentBinLimits&) {
1060  if (useMerge)
1061  Info("Add","Attempt to add histograms with different bin limits - trying to use TH1::Merge");
1062  else
1063  Warning("Add","Attempt to add histograms with different bin limits");
1064  } catch(DifferentLabels&) {
1065  // in case of different labels -
1066  if (useMerge)
1067  Info("Add","Attempt to add histograms with different labels - trying to use TH1::Merge");
1068  else
1069  Info("Warning","Attempt to add histograms with different labels");
1070  }
1071 
1072  if (useMerge) {
1073  TList l;
1074  // why TList takes non-const pointers ????
1075  l.Add(const_cast<TH1*>(h1));
1076  l.Add(const_cast<TH1*>(h2));
1077  Reset("ICE");
1078  auto iret = Merge(&l);
1079  return (iret >= 0);
1080  }
1081  }
1082 
1083  // Create Sumw2 if h1 or h2 have Sumw2 set
1084  if (fSumw2.fN == 0 && (h1->GetSumw2N() != 0 || h2->GetSumw2N() != 0)) Sumw2();
1085 
1086  // - Add statistics
1087  Double_t nEntries = TMath::Abs( c1*h1->GetEntries() + c2*h2->GetEntries() );
1088 
1089  // TODO remove
1090  // statistics can be preserved only in case of positive coefficients
1091  // otherwise with negative c1 (histogram subtraction) one risks to get negative variances
1092  // also in case of scaling with the width we cannot preserve the statistics
1093  Double_t s1[kNstat] = {0};
1094  Double_t s2[kNstat] = {0};
1095  Double_t s3[kNstat];
1096 
1097 
1098  Bool_t resetStats = (c1*c2 < 0) || normWidth;
1099  if (!resetStats) {
1100  // need to initialize to zero s1 and s2 since
1101  // GetStats fills only used elements depending on dimension and type
1102  h1->GetStats(s1);
1103  h2->GetStats(s2);
1104  for (Int_t i=0;i<kNstat;i++) {
1105  if (i == 1) s3[i] = c1*c1*s1[i] + c2*c2*s2[i];
1106  //else s3[i] = TMath::Abs(c1)*s1[i] + TMath::Abs(c2)*s2[i];
1107  else s3[i] = c1*s1[i] + c2*s2[i];
1108  }
1109  }
1110 
1111  SetMinimum();
1112  SetMaximum();
1113 
1114  if (normWidth) { // DEPRECATED CASE: belongs to fitting / drawing modules
1115 
1116  Int_t nbinsx = GetNbinsX() + 2; // normal bins + underflow, overflow
1117  Int_t nbinsy = GetNbinsY() + 2;
1118  Int_t nbinsz = GetNbinsZ() + 2;
1119 
1120  if (fDimension < 2) nbinsy = 1;
1121  if (fDimension < 3) nbinsz = 1;
1122 
1123  Int_t bin, binx, biny, binz;
1124  for (binz = 0; binz < nbinsz; ++binz) {
1125  Double_t wz = h1->GetZaxis()->GetBinWidth(binz);
1126  for (biny = 0; biny < nbinsy; ++biny) {
1127  Double_t wy = h1->GetYaxis()->GetBinWidth(biny);
1128  for (binx = 0; binx < nbinsx; ++binx) {
1129  Double_t wx = h1->GetXaxis()->GetBinWidth(binx);
1130  bin = GetBin(binx, biny, binz);
1131  Double_t w = wx*wy*wz;
1132  UpdateBinContent(bin, c1 * h1->RetrieveBinContent(bin) / w);
1133  if (fSumw2.fN) {
1134  Double_t e1 = h1->GetBinError(bin)/w;
1135  fSumw2.fArray[bin] = c1*c1*e1*e1;
1136  }
1137  }
1138  }
1139  }
1140  } else if (h1->TestBit(kIsAverage) && h2->TestBit(kIsAverage)) {
1141  for (Int_t i = 0; i < fNcells; ++i) { // loop on cells (bins including underflow / overflow)
1142  // special case where histograms have the kIsAverage bit set
1143  Double_t y1 = h1->RetrieveBinContent(i);
1144  Double_t y2 = h2->RetrieveBinContent(i);
1145  Double_t e1sq = h1->GetBinErrorSqUnchecked(i);
1146  Double_t e2sq = h2->GetBinErrorSqUnchecked(i);
1147  Double_t w1 = 1., w2 = 1.;
1148 
1149  // consider all special cases when bin errors are zero
1150  // see http://root.cern.ch/phpBB3//viewtopic.php?f=3&t=13299
1151  if (e1sq) w1 = 1./ e1sq;
1152  else if (h1->fSumw2.fN) {
1153  w1 = 1.E200; // use an arbitrary huge value
1154  if (y1 == 0 ) { // use an estimated error from the global histogram scale
1155  double sf = (s1[0] != 0) ? s1[1]/s1[0] : 1;
1156  w1 = 1./(sf*sf);
1157  }
1158  }
1159  if (e2sq) w2 = 1./ e2sq;
1160  else if (h2->fSumw2.fN) {
1161  w2 = 1.E200; // use an arbitrary huge value
1162  if (y2 == 0) { // use an estimated error from the global histogram scale
1163  double sf = (s2[0] != 0) ? s2[1]/s2[0] : 1;
1164  w2 = 1./(sf*sf);
1165  }
1166  }
1167 
1168  double y = (w1*y1 + w2*y2)/(w1 + w2);
1169  UpdateBinContent(i, y);
1170  if (fSumw2.fN) {
1171  double err2 = 1./(w1 + w2);
1172  if (err2 < 1.E-200) err2 = 0; // to remove arbitrary value when e1=0 AND e2=0
1173  fSumw2.fArray[i] = err2;
1174  }
1175  }
1176  } else { // case of simple histogram addition
1177  Double_t c1sq = c1 * c1;
1178  Double_t c2sq = c2 * c2;
1179  for (Int_t i = 0; i < fNcells; ++i) { // Loop on cells (bins including underflows/overflows)
1180  UpdateBinContent(i, c1 * h1->RetrieveBinContent(i) + c2 * h2->RetrieveBinContent(i));
1181  if (fSumw2.fN) {
1182  fSumw2.fArray[i] = c1sq * h1->GetBinErrorSqUnchecked(i) + c2sq * h2->GetBinErrorSqUnchecked(i);
1183  }
1184  }
1185  }
1186 
1187  if (resetStats) {
1188  // statistics need to be reset in case coefficient are negative
1189  ResetStats();
1190  }
1191  else {
1192  // update statistics (do here to avoid changes by SetBinContent) FIXME remove???
1193  PutStats(s3);
1194  SetEntries(nEntries);
1195  }
1196 
1197  return kTRUE;
1198 }
1199 
1200 
1201 ////////////////////////////////////////////////////////////////////////////////
1202 /// Increment bin content by 1.
1203 
1205 {
1206  AbstractMethod("AddBinContent");
1207 }
1208 
1209 
1210 ////////////////////////////////////////////////////////////////////////////////
1211 /// Increment bin content by a weight w.
1212 
1214 {
1215  AbstractMethod("AddBinContent");
1216 }
1217 
1218 
1219 ////////////////////////////////////////////////////////////////////////////////
1220 /// Sets the flag controlling the automatic add of histograms in memory
1221 ///
1222 /// By default (fAddDirectory = kTRUE), histograms are automatically added
1223 /// to the list of objects in memory.
1224 /// Note that one histogram can be removed from its support directory
1225 /// by calling h->SetDirectory(0) or h->SetDirectory(dir) to add it
1226 /// to the list of objects in the directory dir.
1227 ///
1228 /// NOTE that this is a static function. To call it, use;
1229 /// TH1::AddDirectory
1230 
1232 {
1233  fgAddDirectory = add;
1234 }
1235 
1236 
1237 ////////////////////////////////////////////////////////////////////////////////
1238 /// Fill histogram with all entries in the buffer.
1239 /// action = -1 histogram is reset and refilled from the buffer (called by THistPainter::Paint)
1240 /// action = 0 histogram is reset and filled from the buffer. When the histogram is filled from the
1241 /// buffer the value fBuffer[0] is set to a negative number (= - number of entries)
1242 /// When calling with action == 0 the histogram is NOT refilled when fBuffer[0] is < 0
1243 /// While when calling with action = -1 the histogram is reset and ALWAYS refilled independently if
1244 /// the histogram was filled before. This is needed when drawing the histogram
1245 ///
1246 /// action = 1 histogram is filled and buffer is deleted
1247 /// The buffer is automatically deleted when filling the histogram and the entries is
1248 /// larger than the buffer size
1249 ///
1250 
1252 {
1253  // do we need to compute the bin size?
1254  if (!fBuffer) return 0;
1255  Int_t nbentries = (Int_t)fBuffer[0];
1256 
1257  // nbentries correspond to the number of entries of histogram
1258 
1259  if (nbentries == 0) {
1260  // if action is 1 we delete the buffer
1261  // this will avoid infinite recursion
1262  if (action > 0) {
1263  delete [] fBuffer;
1264  fBuffer = 0;
1265  fBufferSize = 0;
1266  }
1267  return 0;
1268  }
1269  if (nbentries < 0 && action == 0) return 0; // case histogram has been already filled from the buffer
1270 
1271  Double_t *buffer = fBuffer;
1272  if (nbentries < 0) {
1273  nbentries = -nbentries;
1274  // a reset might call BufferEmpty() giving an infinite recursion
1275  // Protect it by setting fBuffer = 0
1276  fBuffer=0;
1277  //do not reset the list of functions
1278  Reset("ICES");
1279  fBuffer = buffer;
1280  }
1281  if (CanExtendAllAxes() || (fXaxis.GetXmax() <= fXaxis.GetXmin())) {
1282  //find min, max of entries in buffer
1283  Double_t xmin = fBuffer[2];
1284  Double_t xmax = xmin;
1285  for (Int_t i=1;i<nbentries;i++) {
1286  Double_t x = fBuffer[2*i+2];
1287  if (x < xmin) xmin = x;
1288  if (x > xmax) xmax = x;
1289  }
1290  if (fXaxis.GetXmax() <= fXaxis.GetXmin()) {
1292  } else {
1293  fBuffer = 0;
1294  Int_t keep = fBufferSize; fBufferSize = 0;
1295  if (xmin < fXaxis.GetXmin()) ExtendAxis(xmin,&fXaxis);
1296  if (xmax >= fXaxis.GetXmax()) ExtendAxis(xmax,&fXaxis);
1297  fBuffer = buffer;
1298  fBufferSize = keep;
1299  }
1300  }
1301 
1302  // call DoFillN which will not put entries in the buffer as FillN does
1303  // set fBuffer to zero to avoid re-emptying the buffer from functions called
1304  // by DoFillN (e.g Sumw2)
1305  buffer = fBuffer; fBuffer = 0;
1306  DoFillN(nbentries,&buffer[2],&buffer[1],2);
1307  fBuffer = buffer;
1308 
1309  // if action == 1 - delete the buffer
1310  if (action > 0) {
1311  delete [] fBuffer;
1312  fBuffer = 0;
1313  fBufferSize = 0;}
1314  else {
1315  // if number of entries is consistent with buffer - set it negative to avoid
1316  // refilling the histogram every time BufferEmpty(0) is called
1317  // In case it is not consistent, by setting fBuffer[0]=0 is like resetting the buffer
1318  // (it will not be used anymore the next time BufferEmpty is called)
1319  if (nbentries == (Int_t)fEntries)
1320  fBuffer[0] = -nbentries;
1321  else
1322  fBuffer[0] = 0;
1323  }
1324  return nbentries;
1325 }
1326 
1327 
1328 ////////////////////////////////////////////////////////////////////////////////
1329 /// accumulate arguments in buffer. When buffer is full, empty the buffer
1330 /// fBuffer[0] = number of entries in buffer
1331 /// fBuffer[1] = w of first entry
1332 /// fBuffer[2] = x of first entry
1333 
1335 {
1336  if (!fBuffer) return -2;
1337  Int_t nbentries = (Int_t)fBuffer[0];
1338 
1339 
1340  if (nbentries < 0) {
1341  // reset nbentries to a positive value so next time BufferEmpty() is called
1342  // the histogram will be refilled
1343  nbentries = -nbentries;
1344  fBuffer[0] = nbentries;
1345  if (fEntries > 0) {
1346  // set fBuffer to zero to avoid calling BufferEmpty in Reset
1348  Reset("ICES"); // do not reset list of functions
1349  fBuffer = buffer;
1350  }
1351  }
1352  if (2*nbentries+2 >= fBufferSize) {
1353  BufferEmpty(1);
1354  if (!fBuffer)
1355  // to avoid infinite recursion Fill->BufferFill->Fill
1356  return Fill(x,w);
1357  // this cannot happen
1358  R__ASSERT(0);
1359  }
1360  fBuffer[2*nbentries+1] = w;
1361  fBuffer[2*nbentries+2] = x;
1362  fBuffer[0] += 1;
1363  return -2;
1364 }
1365 
1366 
1367 ////////////////////////////////////////////////////////////////////////////////
1368 
1369 bool TH1::CheckBinLimits(const TAxis* a1, const TAxis * a2)
1370 {
1371  const TArrayD * h1Array = a1->GetXbins();
1372  const TArrayD * h2Array = a2->GetXbins();
1373  Int_t fN = h1Array->fN;
1374  if ( fN != 0 ) {
1375  if ( h2Array->fN != fN ) {
1376  throw DifferentBinLimits();
1377  return false;
1378  }
1379  else {
1380  for ( int i = 0; i < fN; ++i ) {
1381  if ( ! TMath::AreEqualRel( h1Array->GetAt(i), h2Array->GetAt(i), 1E-10 ) ) {
1382  throw DifferentBinLimits();
1383  return false;
1384  }
1385  }
1386  }
1387  }
1388 
1389  return true;
1390 }
1391 
1392 
1393 ////////////////////////////////////////////////////////////////////////////////
1394 /// check that axis have same labels
1395 
1396 bool TH1::CheckBinLabels(const TAxis* a1, const TAxis * a2)
1397 {
1398  THashList *l1 = a1->GetLabels();
1399  THashList *l2 = a2->GetLabels();
1400 
1401  if (!l1 && !l2 )
1402  return true;
1403  if (!l1 || !l2 ) {
1404  throw DifferentLabels();
1405  return false;
1406  }
1407  // check now labels sizes are the same
1408  if (l1->GetSize() != l2->GetSize() ) {
1409  throw DifferentLabels();
1410  return false;
1411  }
1412  for (int i = 1; i <= a1->GetNbins(); ++i) {
1413  TString label1 = a1->GetBinLabel(i);
1414  TString label2 = a2->GetBinLabel(i);
1415  if (label1 != label2) {
1416  throw DifferentLabels();
1417  return false;
1418  }
1419  }
1420 
1421  return true;
1422 }
1423 
1424 
1425 ////////////////////////////////////////////////////////////////////////////////
1426 /// Check that the axis limits of the histograms are the same
1427 /// if a first and last bin is passed the axis is compared between the given range
1428 
1429 bool TH1::CheckAxisLimits(const TAxis *a1, const TAxis *a2 )
1430 {
1431  if ( ! TMath::AreEqualRel(a1->GetXmin(), a2->GetXmin(),1.E-12) ||
1432  ! TMath::AreEqualRel(a1->GetXmax(), a2->GetXmax(),1.E-12) ) {
1433  throw DifferentAxisLimits();
1434  return false;
1435  }
1436  return true;
1437 }
1438 
1439 
1440 ////////////////////////////////////////////////////////////////////////////////
1441 /// Check that the axis are the same
1442 
1443 bool TH1::CheckEqualAxes(const TAxis *a1, const TAxis *a2 )
1444 {
1445  if (a1->GetNbins() != a2->GetNbins() ) {
1446  //throw DifferentNumberOfBins();
1447  ::Info("CheckEqualAxes","Axes have different number of bins : nbin1 = %d nbin2 = %d",a1->GetNbins(),a2->GetNbins() );
1448  return false;
1449  }
1450  try {
1451  CheckAxisLimits(a1,a2);
1452  } catch (DifferentAxisLimits&) {
1453  ::Info("CheckEqualAxes","Axes have different limits");
1454  return false;
1455  }
1456  try {
1457  CheckBinLimits(a1,a2);
1458  } catch (DifferentBinLimits&) {
1459  ::Info("CheckEqualAxes","Axes have different bin limits");
1460  return false;
1461  }
1462 
1463  // check labels
1464  try {
1465  CheckBinLabels(a1,a2);
1466  } catch (DifferentLabels&) {
1467  ::Info("CheckEqualAxes","Axes have different labels");
1468  return false;
1469  }
1470 
1471  return true;
1472 }
1473 
1474 
1475 ////////////////////////////////////////////////////////////////////////////////
1476 /// Check that two sub axis are the same
1477 /// the limits are defined by first bin and last bin
1478 /// N.B. no check is done in this case for variable bins
1479 
1480 bool TH1::CheckConsistentSubAxes(const TAxis *a1, Int_t firstBin1, Int_t lastBin1, const TAxis * a2, Int_t firstBin2, Int_t lastBin2 )
1481 {
1482  // By default is assumed that no bins are given for the second axis
1483  Int_t nbins1 = lastBin1-firstBin1 + 1;
1484  Double_t xmin1 = a1->GetBinLowEdge(firstBin1);
1485  Double_t xmax1 = a1->GetBinUpEdge(lastBin1);
1486 
1487  Int_t nbins2 = a2->GetNbins();
1488  Double_t xmin2 = a2->GetXmin();
1489  Double_t xmax2 = a2->GetXmax();
1490 
1491  if (firstBin2 < lastBin2) {
1492  // in this case assume no bins are given for the second axis
1493  nbins2 = lastBin1-firstBin1 + 1;
1494  xmin2 = a1->GetBinLowEdge(firstBin1);
1495  xmax2 = a1->GetBinUpEdge(lastBin1);
1496  }
1497 
1498  if (nbins1 != nbins2 ) {
1499  ::Info("CheckConsistentSubAxes","Axes have different number of bins");
1500  return false;
1501  }
1502 
1503  if ( ! TMath::AreEqualRel(xmin1,xmin2,1.E-12) ||
1504  ! TMath::AreEqualRel(xmax1,xmax2,1.E-12) ) {
1505  ::Info("CheckConsistentSubAxes","Axes have different limits");
1506  return false;
1507  }
1508 
1509  return true;
1510 }
1511 
1512 
1513 ////////////////////////////////////////////////////////////////////////////////
1514 /// Check histogram compatibility
1515 
1516 bool TH1::CheckConsistency(const TH1* h1, const TH1* h2)
1517 {
1518  if (h1 == h2) return true;
1519 
1520  if (h1->GetDimension() != h2->GetDimension() ) {
1521  throw DifferentDimension();
1522  return false;
1523  }
1524  Int_t dim = h1->GetDimension();
1525 
1526  // returns kTRUE if number of bins and bin limits are identical
1527  Int_t nbinsx = h1->GetNbinsX();
1528  Int_t nbinsy = h1->GetNbinsY();
1529  Int_t nbinsz = h1->GetNbinsZ();
1530 
1531  // Check whether the histograms have the same number of bins.
1532  if (nbinsx != h2->GetNbinsX() ||
1533  (dim > 1 && nbinsy != h2->GetNbinsY()) ||
1534  (dim > 2 && nbinsz != h2->GetNbinsZ()) ) {
1535  throw DifferentNumberOfBins();
1536  return false;
1537  }
1538 
1539  bool ret = true;
1540 
1541  // check axis limits
1542  ret &= CheckAxisLimits(h1->GetXaxis(), h2->GetXaxis());
1543  if (dim > 1) ret &= CheckAxisLimits(h1->GetYaxis(), h2->GetYaxis());
1544  if (dim > 2) ret &= CheckAxisLimits(h1->GetZaxis(), h2->GetZaxis());
1545 
1546  // check bin limits
1547  ret &= CheckBinLimits(h1->GetXaxis(), h2->GetXaxis());
1548  if (dim > 1) ret &= CheckBinLimits(h1->GetYaxis(), h2->GetYaxis());
1549  if (dim > 2) ret &= CheckBinLimits(h1->GetZaxis(), h2->GetZaxis());
1550 
1551  // check labels if histograms are both not empty
1552  if ( (h1->fTsumw != 0 || h1->GetEntries() != 0) &&
1553  (h2->fTsumw != 0 || h2->GetEntries() != 0) ) {
1554  ret &= CheckBinLabels(h1->GetXaxis(), h2->GetXaxis());
1555  if (dim > 1) ret &= CheckBinLabels(h1->GetYaxis(), h2->GetYaxis());
1556  if (dim > 2) ret &= CheckBinLabels(h1->GetZaxis(), h2->GetZaxis());
1557  }
1558 
1559  return ret;
1560 }
1561 
1562 
1563 ////////////////////////////////////////////////////////////////////////////////
1564 /// chi^{2} test for comparing weighted and unweighted histograms
1565 ///
1566 /// Function: Returns p-value. Other return values are specified by the 3rd parameter
1567 ///
1568 /// \param[in] h2 the second histogram
1569 /// \param[in] option
1570 /// - "UU" = experiment experiment comparison (unweighted-unweighted)
1571 /// - "UW" = experiment MC comparison (unweighted-weighted). Note that
1572 /// the first histogram should be unweighted
1573 /// - "WW" = MC MC comparison (weighted-weighted)
1574 /// - "NORM" = to be used when one or both of the histograms is scaled
1575 /// but the histogram originally was unweighted
1576 /// - by default underflows and overlows are not included:
1577 /// * "OF" = overflows included
1578 /// * "UF" = underflows included
1579 /// - "P" = print chi2, ndf, p_value, igood
1580 /// - "CHI2" = returns chi2 instead of p-value
1581 /// - "CHI2/NDF" = returns #chi^{2}/ndf
1582 /// \param[in] res not empty - computes normalized residuals and returns them in this array
1583 ///
1584 /// The current implementation is based on the papers chi^{2} test for comparison
1585 /// of weighted and unweighted histograms" in Proceedings of PHYSTAT05 and
1586 /// "Comparison weighted and unweighted histograms", arXiv:physics/0605123
1587 /// by N.Gagunashvili. This function has been implemented by Daniel Haertl in August 2006.
1588 ///
1589 /// Introduction:
1590 ///
1591 /// A frequently used technique in data analysis is the comparison of
1592 /// histograms. First suggested by Pearson [1] the #chi^{2} test of
1593 /// homogeneity is used widely for comparing usual (unweighted) histograms.
1594 /// This paper describes the implementation modified #chi^{2} tests
1595 /// for comparison of weighted and unweighted histograms and two weighted
1596 /// histograms [2] as well as usual Pearson's #chi^{2} test for
1597 /// comparison two usual (unweighted) histograms.
1598 ///
1599 /// Overview:
1600 ///
1601 /// Comparison of two histograms expect hypotheses that two histograms
1602 /// represent identical distributions. To make a decision p-value should
1603 /// be calculated. The hypotheses of identity is rejected if the p-value is
1604 /// lower then some significance level. Traditionally significance levels
1605 /// 0.1, 0.05 and 0.01 are used. The comparison procedure should include an
1606 /// analysis of the residuals which is often helpful in identifying the
1607 /// bins of histograms responsible for a significant overall #chi^{2} value.
1608 /// Residuals are the difference between bin contents and expected bin
1609 /// contents. Most convenient for analysis are the normalized residuals. If
1610 /// hypotheses of identity are valid then normalized residuals are
1611 /// approximately independent and identically distributed random variables
1612 /// having N(0,1) distribution. Analysis of residuals expect test of above
1613 /// mentioned properties of residuals. Notice that indirectly the analysis
1614 /// of residuals increase the power of #chi^{2} test.
1615 ///
1616 /// Methods of comparison:
1617 ///
1618 /// #chi^{2} test for comparison two (unweighted) histograms:
1619 /// Let us consider two histograms with the same binning and the number
1620 /// of bins equal to r. Let us denote the number of events in the ith bin
1621 /// in the first histogram as ni and as mi in the second one. The total
1622 /// number of events in the first histogram is equal to:
1623 /// \f[
1624 /// N = \sum_{i=1}^{r} n_{i}
1625 /// \f]
1626 /// and
1627 /// \f[
1628 /// M = \sum_{i=1}^{r} m_{i}
1629 /// \f]
1630 /// in the second histogram. The hypothesis of identity (homogeneity) [3]
1631 /// is that the two histograms represent random values with identical
1632 /// distributions. It is equivalent that there exist r constants p1,...,pr,
1633 /// such that
1634 /// \f[
1635 ///\sum_{i=1}^{r} p_{i}=1
1636 /// \f]
1637 /// and the probability of belonging to the ith bin for some measured value
1638 /// in both experiments is equal to pi. The number of events in the ith
1639 /// bin is a random variable with a distribution approximated by a Poisson
1640 /// probability distribution
1641 /// \f[
1642 ///\frac{e^{-Np_{i}}(Np_{i})^{n_{i}}}{n_{i}!}
1643 /// \f]
1644 ///for the first histogram and with distribution
1645 /// \f[
1646 ///\frac{e^{-Mp_{i}}(Mp_{i})^{m_{i}}}{m_{i}!}
1647 /// \f]
1648 /// for the second histogram. If the hypothesis of homogeneity is valid,
1649 /// then the maximum likelihood estimator of pi, i=1,...,r, is
1650 /// \f[
1651 ///\hat{p}_{i}= \frac{n_{i}+m_{i}}{N+M}
1652 /// \f]
1653 /// and then
1654 /// \f[
1655 /// 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}}
1656 /// \f]
1657 /// has approximately a \f$ \chi^{2}_{(r-1)} \f$ distribution [3].
1658 /// The comparison procedure can include an analysis of the residuals which
1659 /// is often helpful in identifying the bins of histograms responsible for
1660 /// a significant overall #chi^{2} value. Most convenient for
1661 /// analysis are the adjusted (normalized) residuals [4]
1662 /// \f[
1663 /// 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))}}
1664 /// \f]
1665 /// If hypotheses of homogeneity are valid then residuals ri are
1666 /// approximately independent and identically distributed random variables
1667 /// having N(0,1) distribution. The application of the #chi^{2} test has
1668 /// restrictions related to the value of the expected frequencies Npi,
1669 /// Mpi, i=1,...,r. A conservative rule formulated in [5] is that all the
1670 /// expectations must be 1 or greater for both histograms. In practical
1671 /// cases when expected frequencies are not known the estimated expected
1672 /// frequencies \f$ M\hat{p}_{i}, N\hat{p}_{i}, i=1,...,r \f$ can be used.
1673 ///
1674 /// Unweighted and weighted histograms comparison:
1675 ///
1676 /// A simple modification of the ideas described above can be used for the
1677 /// comparison of the usual (unweighted) and weighted histograms. Let us
1678 /// denote the number of events in the ith bin in the unweighted
1679 /// histogram as ni and the common weight of events in the ith bin of the
1680 /// weighted histogram as wi. The total number of events in the
1681 /// unweighted histogram is equal to
1682 ///\f[
1683 /// N = \sum_{i=1}^{r} n_{i}
1684 ///\f]
1685 /// and the total weight of events in the weighted histogram is equal to
1686 ///\f[
1687 /// W = \sum_{i=1}^{r} w_{i}
1688 ///\f]
1689 /// Let us formulate the hypothesis of identity of an unweighted histogram
1690 /// to a weighted histogram so that there exist r constants p1,...,pr, such
1691 /// that
1692 ///\f[
1693 /// \sum_{i=1}^{r} p_{i} = 1
1694 ///\f]
1695 /// for the unweighted histogram. The weight wi is a random variable with a
1696 /// distribution approximated by the normal probability distribution
1697 /// \f$ N(Wp_{i},\sigma_{i}^{2}) \f$ where \f$ \sigma_{i}^{2} \f$ is the variance of the weight wi.
1698 /// If we replace the variance \f$ \sigma_{i}^{2} \f$
1699 /// with estimate \f$ s_{i}^{2} \f$ (sum of squares of weights of
1700 /// events in the ith bin) and the hypothesis of identity is valid, then the
1701 /// maximum likelihood estimator of pi,i=1,...,r, is
1702 ///\f[
1703 /// \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}}
1704 ///\f]
1705 /// We may then use the test statistic
1706 ///\f[
1707 /// 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}}
1708 ///\f]
1709 /// and it has approximately a \f$ \sigma^{2}_{(r-1)} \f$ distribution [2]. This test, as well
1710 /// as the original one [3], has a restriction on the expected frequencies. The
1711 /// expected frequencies recommended for the weighted histogram is more than 25.
1712 /// The value of the minimal expected frequency can be decreased down to 10 for
1713 /// the case when the weights of the events are close to constant. In the case
1714 /// of a weighted histogram if the number of events is unknown, then we can
1715 /// apply this recommendation for the equivalent number of events as
1716 ///\f[
1717 /// n_{i}^{equiv} = \frac{ w_{i}^{2} }{ s_{i}^{2} }
1718 ///\f]
1719 /// The minimal expected frequency for an unweighted histogram must be 1. Notice
1720 /// that any usual (unweighted) histogram can be considered as a weighted
1721 /// histogram with events that have constant weights equal to 1.
1722 /// The variance \f$ z_{i}^{2} \f$ of the difference between the weight wi
1723 /// and the estimated expectation value of the weight is approximately equal to:
1724 ///\f[
1725 /// 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}
1726 ///\f]
1727 /// The residuals
1728 ///\f[
1729 /// r_{i} = \frac{w_{i}-W\hat{p}_{i}}{z_{i}}
1730 ///\f]
1731 /// have approximately a normal distribution with mean equal to 0 and standard
1732 /// deviation equal to 1.
1733 ///
1734 /// Two weighted histograms comparison:
1735 ///
1736 /// Let us denote the common weight of events of the ith bin in the first
1737 /// histogram as w1i and as w2i in the second one. The total weight of events
1738 /// in the first histogram is equal to
1739 ///\f[
1740 /// W_{1} = \sum_{i=1}^{r} w_{1i}
1741 ///\f]
1742 /// and
1743 ///\f[
1744 /// W_{2} = \sum_{i=1}^{r} w_{2i}
1745 ///\f]
1746 /// in the second histogram. Let us formulate the hypothesis of identity of
1747 /// weighted histograms so that there exist r constants p1,...,pr, such that
1748 ///\f[
1749 /// \sum_{i=1}^{r} p_{i} = 1
1750 ///\f]
1751 /// and also expectation value of weight w1i equal to W1pi and expectation value
1752 /// of weight w2i equal to W2pi. Weights in both the histograms are random
1753 /// variables with distributions which can be approximated by a normal
1754 /// probability distribution \f$ N(W_{1}p_{i},\sigma_{1i}^{2}) \f$ for the first histogram
1755 /// and by a distribution \f$ N(W_{2}p_{i},\sigma_{2i}^{2}) \f$ for the second.
1756 /// Here \f$ \sigma_{1i}^{2} \f$ and \f$ \sigma_{2i}^{2} \f$ are the variances
1757 /// of w1i and w2i with estimators \f$ s_{1i}^{2} \f$ and \f$ s_{2i}^{2} \f$ respectively.
1758 /// If the hypothesis of identity is valid, then the maximum likelihood and
1759 /// Least Square Method estimator of pi,i=1,...,r, is
1760 ///\f[
1761 /// \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}}
1762 ///\f]
1763 /// We may then use the test statistic
1764 ///\f[
1765 /// 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}}
1766 ///\f]
1767 /// and it has approximately a \f$ \chi^{2}_{(r-1)} \f$ distribution [2].
1768 /// The normalized or studentised residuals [6]
1769 ///\f[
1770 /// 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})}}}
1771 ///\f]
1772 /// have approximately a normal distribution with mean equal to 0 and standard
1773 /// deviation 1. A recommended minimal expected frequency is equal to 10 for
1774 /// the proposed test.
1775 ///
1776 /// Numerical examples:
1777 ///
1778 /// The method described herein is now illustrated with an example.
1779 /// We take a distribution
1780 ///\f[
1781 /// \phi(x) = \frac{2}{(x-10)^{2}+1} + \frac{1}{(x-14)^{2}+1} (1)
1782 ///\f]
1783 /// defined on the interval [4,16]. Events distributed according to the formula
1784 /// (1) are simulated to create the unweighted histogram. Uniformly distributed
1785 /// events are simulated for the weighted histogram with weights calculated by
1786 /// formula (1). Each histogram has the same number of bins: 20. Fig.1 shows
1787 /// the result of comparison of the unweighted histogram with 200 events
1788 /// (minimal expected frequency equal to one) and the weighted histogram with
1789 /// 500 events (minimal expected frequency equal to 25)
1790 /// Begin_Macro
1791 /// ../../../tutorials/math/chi2test.C
1792 /// End_Macro
1793 /// Fig 1. An example of comparison of the unweighted histogram with 200 events
1794 /// and the weighted histogram with 500 events:
1795 /// a) unweighted histogram;
1796 /// b) weighted histogram;
1797 /// c) normalized residuals plot;
1798 /// d) normal Q-Q plot of residuals.
1799 ///
1800 /// The value of the test statistic \f$ \chi^{2} \f$ is equal to
1801 /// 21.09 with p-value equal to 0.33, therefore the hypothesis of identity of
1802 /// the two histograms can be accepted for 0.05 significant level. The behavior
1803 /// of the normalized residuals plot (see Fig. 1c) and the normal Q-Q plot
1804 /// (see Fig. 1d) of residuals are regular and we cannot identify the outliers
1805 /// or bins with a big influence on \f$ \chi^{2} \f$.
1806 ///
1807 /// The second example presents the same two histograms but 17 events was added
1808 /// to content of bin number 15 in unweighted histogram. Fig.2 shows the result
1809 /// of comparison of the unweighted histogram with 217 events (minimal expected
1810 /// frequency equal to one) and the weighted histogram with 500 events (minimal
1811 /// expected frequency equal to 25)
1812 ///Begin_Macro
1813 /// ../../../tutorials/math/chi2test.C(17)
1814 ///End_Macro
1815 /// Fig 2. An example of comparison of the unweighted histogram with 217 events
1816 /// and the weighted histogram with 500 events:
1817 /// a) unweighted histogram;
1818 /// b) weighted histogram;
1819 /// c) normalized residuals plot;
1820 /// d) normal Q-Q plot of residuals.
1821 ///
1822 /// The value of the test statistic \f$ \chi^{2} \f$ is equal to
1823 /// 32.33 with p-value equal to 0.029, therefore the hypothesis of identity of
1824 /// the two histograms is rejected for 0.05 significant level. The behavior of
1825 /// the normalized residuals plot (see Fig. 2c) and the normal Q-Q plot (see
1826 /// Fig. 2d) of residuals are not regular and we can identify the outlier or
1827 /// bin with a big influence on \f$ \chi^{2} \f$.
1828 ///
1829 /// References:
1830 ///
1831 /// [1] Pearson, K., 1904. On the Theory of Contingency and Its Relation to
1832 /// Association and Normal Correlation. Drapers' Co. Memoirs, Biometric
1833 /// Series No. 1, London.
1834 /// [2] Gagunashvili, N., 2006. \f$ \sigma^{2} \f$ test for comparison
1835 /// of weighted and unweighted histograms. Statistical Problems in Particle
1836 /// Physics, Astrophysics and Cosmology, Proceedings of PHYSTAT05,
1837 /// Oxford, UK, 12-15 September 2005, Imperial College Press, London, 43-44.
1838 /// Gagunashvili,N., Comparison of weighted and unweighted histograms,
1839 /// arXiv:physics/0605123, 2006.
1840 /// [3] Cramer, H., 1946. Mathematical methods of statistics.
1841 /// Princeton University Press, Princeton.
1842 /// [4] Haberman, S.J., 1973. The analysis of residuals in cross-classified tables.
1843 /// Biometrics 29, 205-220.
1844 /// [5] Lewontin, R.C. and Felsenstein, J., 1965. The robustness of homogeneity
1845 /// test in 2xN tables. Biometrics 21, 19-33.
1846 /// [6] Seber, G.A.F., Lee, A.J., 2003, Linear Regression Analysis.
1847 /// John Wiley & Sons Inc., New York.
1848 
1849 Double_t TH1::Chi2Test(const TH1* h2, Option_t *option, Double_t *res) const
1851  Double_t chi2 = 0;
1852  Int_t ndf = 0, igood = 0;
1853 
1854  TString opt = option;
1855  opt.ToUpper();
1856 
1857  Double_t prob = Chi2TestX(h2,chi2,ndf,igood,option,res);
1858 
1859  if(opt.Contains("P")) {
1860  printf("Chi2 = %f, Prob = %g, NDF = %d, igood = %d\n", chi2,prob,ndf,igood);
1861  }
1862  if(opt.Contains("CHI2/NDF")) {
1863  if (ndf == 0) return 0;
1864  return chi2/ndf;
1865  }
1866  if(opt.Contains("CHI2")) {
1867  return chi2;
1868  }
1869 
1870  return prob;
1871 }
1872 
1873 
1874 ////////////////////////////////////////////////////////////////////////////////
1875 /// The computation routine of the Chisquare test. For the method description,
1876 /// see Chi2Test() function.
1877 /// \return p-value
1878 /// \param[in] h2 the second histogram
1879 /// \param[in] option
1880 /// - "UU" = experiment experiment comparison (unweighted-unweighted)
1881 /// - "UW" = experiment MC comparison (unweighted-weighted). Note that the first
1882 /// histogram should be unweighted
1883 /// - "WW" = MC MC comparison (weighted-weighted)
1884 /// - "NORM" = if one or both histograms is scaled
1885 /// - "OF" = overflows included
1886 /// - "UF" = underflows included
1887 /// by default underflows and overflows are not included
1888 /// \param[out] igood test output
1889 /// - igood=0 - no problems
1890 /// - For unweighted unweighted comparison
1891 /// - igood=1'There is a bin in the 1st histogram with less than 1 event'
1892 /// - igood=2'There is a bin in the 2nd histogram with less than 1 event'
1893 /// - igood=3'when the conditions for igood=1 and igood=2 are satisfied'
1894 /// - For unweighted weighted comparison
1895 /// - igood=1'There is a bin in the 1st histogram with less then 1 event'
1896 /// - igood=2'There is a bin in the 2nd histogram with less then 10 effective number of events'
1897 /// - igood=3'when the conditions for igood=1 and igood=2 are satisfied'
1898 /// - For weighted weighted comparison
1899 /// - igood=1'There is a bin in the 1st histogram with less then 10 effective
1900 /// number of events'
1901 /// - igood=2'There is a bin in the 2nd histogram with less then 10 effective
1902 /// number of events'
1903 /// - igood=3'when the conditions for igood=1 and igood=2 are satisfied'
1904 /// \param[out] chi2 chisquare of the test
1905 /// \param[out] ndf number of degrees of freedom (important, when both histograms have the same empty bins)
1906 /// \param[out] res normalized residuals for further analysis
1907 
1908 Double_t TH1::Chi2TestX(const TH1* h2, Double_t &chi2, Int_t &ndf, Int_t &igood, Option_t *option, Double_t *res) const
1910 
1911  Int_t i_start, i_end;
1912  Int_t j_start, j_end;
1913  Int_t k_start, k_end;
1914 
1915  Double_t sum1 = 0.0, sumw1 = 0.0;
1916  Double_t sum2 = 0.0, sumw2 = 0.0;
1917 
1918  chi2 = 0.0;
1919  ndf = 0;
1920 
1921  TString opt = option;
1922  opt.ToUpper();
1923 
1924  if (fBuffer) const_cast<TH1*>(this)->BufferEmpty();
1925 
1926  const TAxis *xaxis1 = GetXaxis();
1927  const TAxis *xaxis2 = h2->GetXaxis();
1928  const TAxis *yaxis1 = GetYaxis();
1929  const TAxis *yaxis2 = h2->GetYaxis();
1930  const TAxis *zaxis1 = GetZaxis();
1931  const TAxis *zaxis2 = h2->GetZaxis();
1932 
1933  Int_t nbinx1 = xaxis1->GetNbins();
1934  Int_t nbinx2 = xaxis2->GetNbins();
1935  Int_t nbiny1 = yaxis1->GetNbins();
1936  Int_t nbiny2 = yaxis2->GetNbins();
1937  Int_t nbinz1 = zaxis1->GetNbins();
1938  Int_t nbinz2 = zaxis2->GetNbins();
1939 
1940  //check dimensions
1941  if (this->GetDimension() != h2->GetDimension() ){
1942  Error("Chi2TestX","Histograms have different dimensions.");
1943  return 0.0;
1944  }
1945 
1946  //check number of channels
1947  if (nbinx1 != nbinx2) {
1948  Error("Chi2TestX","different number of x channels");
1949  }
1950  if (nbiny1 != nbiny2) {
1951  Error("Chi2TestX","different number of y channels");
1952  }
1953  if (nbinz1 != nbinz2) {
1954  Error("Chi2TestX","different number of z channels");
1955  }
1956 
1957  //check for ranges
1958  i_start = j_start = k_start = 1;
1959  i_end = nbinx1;
1960  j_end = nbiny1;
1961  k_end = nbinz1;
1962 
1963  if (xaxis1->TestBit(TAxis::kAxisRange)) {
1964  i_start = xaxis1->GetFirst();
1965  i_end = xaxis1->GetLast();
1966  }
1967  if (yaxis1->TestBit(TAxis::kAxisRange)) {
1968  j_start = yaxis1->GetFirst();
1969  j_end = yaxis1->GetLast();
1970  }
1971  if (zaxis1->TestBit(TAxis::kAxisRange)) {
1972  k_start = zaxis1->GetFirst();
1973  k_end = zaxis1->GetLast();
1974  }
1975 
1976 
1977  if (opt.Contains("OF")) {
1978  if (GetDimension() == 3) k_end = ++nbinz1;
1979  if (GetDimension() >= 2) j_end = ++nbiny1;
1980  if (GetDimension() >= 1) i_end = ++nbinx1;
1981  }
1982 
1983  if (opt.Contains("UF")) {
1984  if (GetDimension() == 3) k_start = 0;
1985  if (GetDimension() >= 2) j_start = 0;
1986  if (GetDimension() >= 1) i_start = 0;
1987  }
1988 
1989  ndf = (i_end - i_start + 1) * (j_end - j_start + 1) * (k_end - k_start + 1) - 1;
1990 
1991  Bool_t comparisonUU = opt.Contains("UU");
1992  Bool_t comparisonUW = opt.Contains("UW");
1993  Bool_t comparisonWW = opt.Contains("WW");
1994  Bool_t scaledHistogram = opt.Contains("NORM");
1995 
1996  if (scaledHistogram && !comparisonUU) {
1997  Info("Chi2TestX", "NORM option should be used together with UU option. It is ignored");
1998  }
1999 
2000  // look at histo global bin content and effective entries
2001  Stat_t s[kNstat];
2002  GetStats(s);// s[1] sum of squares of weights, s[0] sum of weights
2003  Double_t sumBinContent1 = s[0];
2004  Double_t effEntries1 = (s[1] ? s[0] * s[0] / s[1] : 0.0);
2005 
2006  h2->GetStats(s);// s[1] sum of squares of weights, s[0] sum of weights
2007  Double_t sumBinContent2 = s[0];
2008  Double_t effEntries2 = (s[1] ? s[0] * s[0] / s[1] : 0.0);
2009 
2010  if (!comparisonUU && !comparisonUW && !comparisonWW ) {
2011  // deduce automatically from type of histogram
2012  if (TMath::Abs(sumBinContent1 - effEntries1) < 1) {
2013  if ( TMath::Abs(sumBinContent2 - effEntries2) < 1) comparisonUU = true;
2014  else comparisonUW = true;
2015  }
2016  else comparisonWW = true;
2017  }
2018  // check unweighted histogram
2019  if (comparisonUW) {
2020  if (TMath::Abs(sumBinContent1 - effEntries1) >= 1) {
2021  Warning("Chi2TestX","First histogram is not unweighted and option UW has been requested");
2022  }
2023  }
2024  if ( (!scaledHistogram && comparisonUU) ) {
2025  if ( ( TMath::Abs(sumBinContent1 - effEntries1) >= 1) || (TMath::Abs(sumBinContent2 - effEntries2) >= 1) ) {
2026  Warning("Chi2TestX","Both histograms are not unweighted and option UU has been requested");
2027  }
2028  }
2029 
2030 
2031  //get number of events in histogram
2032  if (comparisonUU && scaledHistogram) {
2033  for (Int_t i = i_start; i <= i_end; ++i) {
2034  for (Int_t j = j_start; j <= j_end; ++j) {
2035  for (Int_t k = k_start; k <= k_end; ++k) {
2036 
2037  Int_t bin = GetBin(i, j, k);
2038 
2039  Double_t cnt1 = RetrieveBinContent(bin);
2040  Double_t cnt2 = h2->RetrieveBinContent(bin);
2041  Double_t e1sq = GetBinErrorSqUnchecked(bin);
2042  Double_t e2sq = h2->GetBinErrorSqUnchecked(bin);
2043 
2044  if (e1sq > 0.0) cnt1 = TMath::Floor(cnt1 * cnt1 / e1sq + 0.5); // avoid rounding errors
2045  else cnt1 = 0.0;
2046 
2047  if (e2sq > 0.0) cnt2 = TMath::Floor(cnt2 * cnt2 / e2sq + 0.5); // avoid rounding errors
2048  else cnt2 = 0.0;
2049 
2050  // sum contents
2051  sum1 += cnt1;
2052  sum2 += cnt2;
2053  sumw1 += e1sq;
2054  sumw2 += e2sq;
2055  }
2056  }
2057  }
2058  if (sumw1 <= 0.0 || sumw2 <= 0.0) {
2059  Error("Chi2TestX", "Cannot use option NORM when one histogram has all zero errors");
2060  return 0.0;
2061  }
2062 
2063  } else {
2064  for (Int_t i = i_start; i <= i_end; ++i) {
2065  for (Int_t j = j_start; j <= j_end; ++j) {
2066  for (Int_t k = k_start; k <= k_end; ++k) {
2067 
2068  Int_t bin = GetBin(i, j, k);
2069 
2070  sum1 += RetrieveBinContent(bin);
2071  sum2 += h2->RetrieveBinContent(bin);
2072 
2073  if ( comparisonWW ) sumw1 += GetBinErrorSqUnchecked(bin);
2074  if ( comparisonUW || comparisonWW ) sumw2 += h2->GetBinErrorSqUnchecked(bin);
2075  }
2076  }
2077  }
2078  }
2079  //checks that the histograms are not empty
2080  if (sum1 == 0.0 || sum2 == 0.0) {
2081  Error("Chi2TestX","one histogram is empty");
2082  return 0.0;
2083  }
2084 
2085  if ( comparisonWW && ( sumw1 <= 0.0 && sumw2 <= 0.0 ) ){
2086  Error("Chi2TestX","Hist1 and Hist2 have both all zero errors\n");
2087  return 0.0;
2088  }
2089 
2090  //THE TEST
2091  Int_t m = 0, n = 0;
2092 
2093  //Experiment - experiment comparison
2094  if (comparisonUU) {
2095  Double_t sum = sum1 + sum2;
2096  for (Int_t i = i_start; i <= i_end; ++i) {
2097  for (Int_t j = j_start; j <= j_end; ++j) {
2098  for (Int_t k = k_start; k <= k_end; ++k) {
2099 
2100  Int_t bin = GetBin(i, j, k);
2101 
2102  Double_t cnt1 = RetrieveBinContent(bin);
2103  Double_t cnt2 = h2->RetrieveBinContent(bin);
2104 
2105  if (scaledHistogram) {
2106  // scale bin value to effective bin entries
2107  Double_t e1sq = GetBinErrorSqUnchecked(bin);
2108  Double_t e2sq = h2->GetBinErrorSqUnchecked(bin);
2109 
2110  if (e1sq > 0) cnt1 = TMath::Floor(cnt1 * cnt1 / e1sq + 0.5); // avoid rounding errors
2111  else cnt1 = 0;
2112 
2113  if (e2sq > 0) cnt2 = TMath::Floor(cnt2 * cnt2 / e2sq + 0.5); // avoid rounding errors
2114  else cnt2 = 0;
2115  }
2116 
2117  if (Int_t(cnt1) == 0 && Int_t(cnt2) == 0) --ndf; // no data means one degree of freedom less
2118  else {
2119 
2120  Double_t cntsum = cnt1 + cnt2;
2121  Double_t nexp1 = cntsum * sum1 / sum;
2122  //Double_t nexp2 = binsum*sum2/sum;
2123 
2124  if (res) res[i - i_start] = (cnt1 - nexp1) / TMath::Sqrt(nexp1);
2125 
2126  if (cnt1 < 1) ++m;
2127  if (cnt2 < 1) ++n;
2128 
2129  //Habermann correction for residuals
2130  Double_t correc = (1. - sum1 / sum) * (1. - cntsum / sum);
2131  if (res) res[i - i_start] /= TMath::Sqrt(correc);
2132 
2133  Double_t delta = sum2 * cnt1 - sum1 * cnt2;
2134  chi2 += delta * delta / cntsum;
2135  }
2136  }
2137  }
2138  }
2139  chi2 /= sum1 * sum2;
2140 
2141  // flag error only when of the two histogram is zero
2142  if (m) {
2143  igood += 1;
2144  Info("Chi2TestX","There is a bin in h1 with less than 1 event.\n");
2145  }
2146  if (n) {
2147  igood += 2;
2148  Info("Chi2TestX","There is a bin in h2 with less than 1 event.\n");
2149  }
2150 
2151  Double_t prob = TMath::Prob(chi2,ndf);
2152  return prob;
2153 
2154  }
2155 
2156  // unweighted - weighted comparison
2157  // case of error = 0 and content not zero is treated without problems by excluding second chi2 sum
2158  // and can be considered as a data-theory comparison
2159  if ( comparisonUW ) {
2160  for (Int_t i = i_start; i <= i_end; ++i) {
2161  for (Int_t j = j_start; j <= j_end; ++j) {
2162  for (Int_t k = k_start; k <= k_end; ++k) {
2163 
2164  Int_t bin = GetBin(i, j, k);
2165 
2166  Double_t cnt1 = RetrieveBinContent(bin);
2167  Double_t cnt2 = h2->RetrieveBinContent(bin);
2168  Double_t e2sq = h2->GetBinErrorSqUnchecked(bin);
2169 
2170  // case both histogram have zero bin contents
2171  if (cnt1 * cnt1 == 0 && cnt2 * cnt2 == 0) {
2172  --ndf; //no data means one degree of freedom less
2173  continue;
2174  }
2175 
2176  // case weighted histogram has zero bin content and error
2177  if (cnt2 * cnt2 == 0 && e2sq == 0) {
2178  if (sumw2 > 0) {
2179  // use as approximated error as 1 scaled by a scaling ratio
2180  // estimated from the total sum weight and sum weight squared
2181  e2sq = sumw2 / sum2;
2182  }
2183  else {
2184  // return error because infinite discrepancy here:
2185  // bin1 != 0 and bin2 =0 in a histogram with all errors zero
2186  Error("Chi2TestX","Hist2 has in bin (%d,%d,%d) zero content and zero errors\n", i, j, k);
2187  chi2 = 0; return 0;
2188  }
2189  }
2190 
2191  if (cnt1 < 1) m++;
2192  if (e2sq > 0 && cnt2 * cnt2 / e2sq < 10) n++;
2193 
2194  Double_t var1 = sum2 * cnt2 - sum1 * e2sq;
2195  Double_t var2 = var1 * var1 + 4. * sum2 * sum2 * cnt1 * e2sq;
2196 
2197  // if cnt1 is zero and cnt2 = 1 and sum1 = sum2 var1 = 0 && var2 == 0
2198  // approximate by incrementing cnt1
2199  // LM (this need to be fixed for numerical errors)
2200  while (var1 * var1 + cnt1 == 0 || var1 + var2 == 0) {
2201  sum1++;
2202  cnt1++;
2203  var1 = sum2 * cnt2 - sum1 * e2sq;
2204  var2 = var1 * var1 + 4. * sum2 * sum2 * cnt1 * e2sq;
2205  }
2206  var2 = TMath::Sqrt(var2);
2207 
2208  while (var1 + var2 == 0) {
2209  sum1++;
2210  cnt1++;
2211  var1 = sum2 * cnt2 - sum1 * e2sq;
2212  var2 = var1 * var1 + 4. * sum2 * sum2 * cnt1 * e2sq;
2213  while (var1 * var1 + cnt1 == 0 || var1 + var2 == 0) {
2214  sum1++;
2215  cnt1++;
2216  var1 = sum2 * cnt2 - sum1 * e2sq;
2217  var2 = var1 * var1 + 4. * sum2 * sum2 * cnt1 * e2sq;
2218  }
2219  var2 = TMath::Sqrt(var2);
2220  }
2221 
2222  Double_t probb = (var1 + var2) / (2. * sum2 * sum2);
2223 
2224  Double_t nexp1 = probb * sum1;
2225  Double_t nexp2 = probb * sum2;
2226 
2227  Double_t delta1 = cnt1 - nexp1;
2228  Double_t delta2 = cnt2 - nexp2;
2229 
2230  chi2 += delta1 * delta1 / nexp1;
2231 
2232  if (e2sq > 0) {
2233  chi2 += delta2 * delta2 / e2sq;
2234  }
2235 
2236  if (res) {
2237  if (e2sq > 0) {
2238  Double_t temp1 = sum2 * e2sq / var2;
2239  Double_t temp2 = 1.0 + (sum1 * e2sq - sum2 * cnt2) / var2;
2240  temp2 = temp1 * temp1 * sum1 * probb * (1.0 - probb) + temp2 * temp2 * e2sq / 4.0;
2241  // invert sign here
2242  res[i - i_start] = - delta2 / TMath::Sqrt(temp2);
2243  }
2244  else
2245  res[i - i_start] = delta1 / TMath::Sqrt(nexp1);
2246  }
2247  }
2248  }
2249  }
2250 
2251  if (m) {
2252  igood += 1;
2253  Info("Chi2TestX","There is a bin in h1 with less than 1 event.\n");
2254  }
2255  if (n) {
2256  igood += 2;
2257  Info("Chi2TestX","There is a bin in h2 with less than 10 effective events.\n");
2258  }
2259 
2260  Double_t prob = TMath::Prob(chi2, ndf);
2261 
2262  return prob;
2263  }
2264 
2265  // weighted - weighted comparison
2266  if (comparisonWW) {
2267  for (Int_t i = i_start; i <= i_end; ++i) {
2268  for (Int_t j = j_start; j <= j_end; ++j) {
2269  for (Int_t k = k_start; k <= k_end; ++k) {
2270 
2271  Int_t bin = GetBin(i, j, k);
2272  Double_t cnt1 = RetrieveBinContent(bin);
2273  Double_t cnt2 = h2->RetrieveBinContent(bin);
2274  Double_t e1sq = GetBinErrorSqUnchecked(bin);
2275  Double_t e2sq = h2->GetBinErrorSqUnchecked(bin);
2276 
2277  // case both histogram have zero bin contents
2278  // (use square of content to avoid numerical errors)
2279  if (cnt1 * cnt1 == 0 && cnt2 * cnt2 == 0) {
2280  --ndf; //no data means one degree of freedom less
2281  continue;
2282  }
2283 
2284  if (e1sq == 0 && e2sq == 0) {
2285  // cannot treat case of booth histogram have zero zero errors
2286  Error("Chi2TestX","h1 and h2 both have bin %d,%d,%d with all zero errors\n", i,j,k);
2287  chi2 = 0; return 0;
2288  }
2289 
2290  Double_t sigma = sum1 * sum1 * e2sq + sum2 * sum2 * e1sq;
2291  Double_t delta = sum2 * cnt1 - sum1 * cnt2;
2292  chi2 += delta * delta / sigma;
2293 
2294  if (res) {
2295  Double_t temp = cnt1 * sum1 * e2sq + cnt2 * sum2 * e1sq;
2296  Double_t probb = temp / sigma;
2297  Double_t z = 0;
2298  if (e1sq > e2sq) {
2299  Double_t d1 = cnt1 - sum1 * probb;
2300  Double_t s1 = e1sq * ( 1. - e2sq * sum1 * sum1 / sigma );
2301  z = d1 / TMath::Sqrt(s1);
2302  }
2303  else {
2304  Double_t d2 = cnt2 - sum2 * probb;
2305  Double_t s2 = e2sq * ( 1. - e1sq * sum2 * sum2 / sigma );
2306  z = -d2 / TMath::Sqrt(s2);
2307  }
2308  res[i - i_start] = z;
2309  }
2310 
2311  if (e1sq > 0 && cnt1 * cnt1 / e1sq < 10) m++;
2312  if (e2sq > 0 && cnt2 * cnt2 / e2sq < 10) n++;
2313  }
2314  }
2315  }
2316  if (m) {
2317  igood += 1;
2318  Info("Chi2TestX","There is a bin in h1 with less than 10 effective events.\n");
2319  }
2320  if (n) {
2321  igood += 2;
2322  Info("Chi2TestX","There is a bin in h2 with less than 10 effective events.\n");
2323  }
2324  Double_t prob = TMath::Prob(chi2, ndf);
2325  return prob;
2326  }
2327  return 0;
2328 }
2329 ////////////////////////////////////////////////////////////////////////////////
2330 /// Compute and return the chisquare of this histogram with respect to a function
2331 /// The chisquare is computed by weighting each histogram point by the bin error
2332 /// By default the full range of the histogram is used.
2333 /// Use option "R" for restricting the chisquare calculation to the given range of the function
2334 
2335 Double_t TH1::Chisquare(TF1 * func, Option_t *option) const
2337  if (!func) {
2338  Error("Chisquare","Function pointer is Null - return -1");
2339  return -1;
2340  }
2341 
2342  TString opt(option); opt.ToUpper();
2343  bool useRange = opt.Contains("R");
2344 
2345  return ROOT::Fit::Chisquare(*this, *func, useRange);
2346 }
2347 
2348 ////////////////////////////////////////////////////////////////////////////////
2349 /// Remove all the content from the underflow and overflow bins, without changing the number of entries
2350 /// After calling this method, every undeflow and overflow bins will have content 0.0
2351 /// The Sumw2 is also cleared, since there is no more content in the bins
2352 
2355  for (Int_t bin = 0; bin < fNcells; ++bin)
2356  if (IsBinUnderflow(bin) || IsBinOverflow(bin)) {
2357  UpdateBinContent(bin, 0.0);
2358  if (fSumw2.fN) fSumw2.fArray[bin] = 0.0;
2359  }
2360 }
2361 
2362 ////////////////////////////////////////////////////////////////////////////////
2363 /// Compute integral (cumulative sum of bins)
2364 /// The result stored in fIntegral is used by the GetRandom functions.
2365 /// This function is automatically called by GetRandom when the fIntegral
2366 /// array does not exist or when the number of entries in the histogram
2367 /// has changed since the previous call to GetRandom.
2368 /// The resulting integral is normalized to 1
2369 /// If the routine is called with the onlyPositive flag set an error will
2370 /// be produced in case of negative bin content and a NaN value returned
2371 
2372 Double_t TH1::ComputeIntegral(Bool_t onlyPositive)
2374  if (fBuffer) BufferEmpty();
2375 
2376  // delete previously computed integral (if any)
2377  if (fIntegral) delete [] fIntegral;
2378 
2379  // - Allocate space to store the integral and compute integral
2380  Int_t nbinsx = GetNbinsX();
2381  Int_t nbinsy = GetNbinsY();
2382  Int_t nbinsz = GetNbinsZ();
2383  Int_t nbins = nbinsx * nbinsy * nbinsz;
2384 
2385  fIntegral = new Double_t[nbins + 2];
2386  Int_t ibin = 0; fIntegral[ibin] = 0;
2387 
2388  for (Int_t binz=1; binz <= nbinsz; ++binz) {
2389  for (Int_t biny=1; biny <= nbinsy; ++biny) {
2390  for (Int_t binx=1; binx <= nbinsx; ++binx) {
2391  ++ibin;
2392  Double_t y = RetrieveBinContent(GetBin(binx, biny, binz));
2393  if (onlyPositive && y < 0) {
2394  Error("ComputeIntegral","Bin content is negative - return a NaN value");
2396  break;
2397  }
2398  fIntegral[ibin] = fIntegral[ibin - 1] + y;
2399  }
2400  }
2401  }
2402 
2403  // - Normalize integral to 1
2404  if (fIntegral[nbins] == 0 ) {
2405  Error("ComputeIntegral", "Integral = zero"); return 0;
2406  }
2407  for (Int_t bin=1; bin <= nbins; ++bin) fIntegral[bin] /= fIntegral[nbins];
2408  fIntegral[nbins+1] = fEntries;
2409  return fIntegral[nbins];
2410 }
2411 
2412 
2413 ////////////////////////////////////////////////////////////////////////////////
2414 /// Return a pointer to the array of bins integral.
2415 /// if the pointer fIntegral is null, TH1::ComputeIntegral is called
2416 /// The array dimension is the number of bins in the histograms
2417 /// including underflow and overflow (fNCells)
2418 /// the last value integral[fNCells] is set to the number of entries of
2419 /// the histogram
2420 
2423  if (!fIntegral) ComputeIntegral();
2424  return fIntegral;
2425 }
2426 
2427 
2428 ////////////////////////////////////////////////////////////////////////////////
2429 /// Return a pointer to an histogram containing the cumulative The
2430 /// cumulative can be computed both in the forward (default) or backward
2431 /// direction; the name of the new histogram is constructed from
2432 /// the name of this histogram with the suffix suffix appended.
2433 ///
2434 /// The cumulative distribution is formed by filling each bin of the
2435 /// resulting histogram with the sum of that bin and all previous
2436 /// (forward == kTRUE) or following (forward = kFALSE) bins.
2437 ///
2438 /// note: while cumulative distributions make sense in one dimension, you
2439 /// may not be getting what you expect in more than 1D because the concept
2440 /// of a cumulative distribution is much trickier to define; make sure you
2441 /// understand the order of summation before you use this method with
2442 /// histograms of dimension >= 2.
2443 
2444 TH1 *TH1::GetCumulative(Bool_t forward, const char* suffix) const
2446  const Int_t nbinsx = GetNbinsX();
2447  const Int_t nbinsy = GetNbinsY();
2448  const Int_t nbinsz = GetNbinsZ();
2449  TH1* hintegrated = (TH1*) Clone(fName + suffix);
2450  hintegrated->Reset();
2451  if (forward) { // Forward computation
2452  Double_t sum = 0.;
2453  for (Int_t binz = 1; binz <= nbinsz; ++binz) {
2454  for (Int_t biny = 1; biny <= nbinsy; ++biny) {
2455  for (Int_t binx = 1; binx <= nbinsx; ++binx) {
2456  const Int_t bin = hintegrated->GetBin(binx, biny, binz);
2457  sum += GetBinContent(bin);
2458  hintegrated->SetBinContent(bin, sum);
2459  }
2460  }
2461  }
2462  } else { // Backward computation
2463  Double_t sum = 0.;
2464  for (Int_t binz = nbinsz; binz >= 1; --binz) {
2465  for (Int_t biny = nbinsy; biny >= 1; --biny) {
2466  for (Int_t binx = nbinsx; binx >= 1; --binx) {
2467  const Int_t bin = hintegrated->GetBin(binx, biny, binz);
2468  sum += GetBinContent(bin);
2469  hintegrated->SetBinContent(bin, sum);
2470  }
2471  }
2472  }
2473  }
2474  return hintegrated;
2475 }
2476 
2477 ////////////////////////////////////////////////////////////////////////////////
2478 /// Copy this histogram structure to newth1.
2479 ///
2480 /// Note that this function does not copy the list of associated functions.
2481 /// Use TObject::Clone to make a full copy of an histogram.
2482 ///
2483 /// Note also that the histogram it will be created in gDirectory (if AddDirectoryStatus()=true)
2484 /// or will not be added to any directory if AddDirectoryStatus()=false
2485 /// independently of the current directory stored in the original histogram
2486 
2487 void TH1::Copy(TObject &obj) const
2489  if (((TH1&)obj).fDirectory) {
2490  // We are likely to change the hash value of this object
2491  // with TNamed::Copy, to keep things correct, we need to
2492  // clean up its existing entries.
2493  ((TH1&)obj).fDirectory->Remove(&obj);
2494  ((TH1&)obj).fDirectory = 0;
2495  }
2496  TNamed::Copy(obj);
2497  ((TH1&)obj).fDimension = fDimension;
2498  ((TH1&)obj).fNormFactor= fNormFactor;
2499  ((TH1&)obj).fNcells = fNcells;
2500  ((TH1&)obj).fBarOffset = fBarOffset;
2501  ((TH1&)obj).fBarWidth = fBarWidth;
2502  ((TH1&)obj).fOption = fOption;
2503  ((TH1&)obj).fBinStatErrOpt = fBinStatErrOpt;
2504  ((TH1&)obj).fBufferSize= fBufferSize;
2505  // copy the Buffer
2506  // delete first a previously existing buffer
2507  if (((TH1&)obj).fBuffer != 0) {
2508  delete [] ((TH1&)obj).fBuffer;
2509  ((TH1&)obj).fBuffer = 0;
2510  }
2511  if (fBuffer) {
2512  Double_t *buf = new Double_t[fBufferSize];
2513  for (Int_t i=0;i<fBufferSize;i++) buf[i] = fBuffer[i];
2514  // obj.fBuffer has been deleted before
2515  ((TH1&)obj).fBuffer = buf;
2516  }
2517 
2518 
2519  TArray* a = dynamic_cast<TArray*>(&obj);
2520  if (a) a->Set(fNcells);
2521  for (Int_t i = 0; i < fNcells; i++) ((TH1&)obj).UpdateBinContent(i, RetrieveBinContent(i));
2522 
2523  ((TH1&)obj).fEntries = fEntries;
2524 
2525  // which will call BufferEmpty(0) and set fBuffer[0] to a Maybe one should call
2526  // assignment operator on the TArrayD
2527 
2528  ((TH1&)obj).fTsumw = fTsumw;
2529  ((TH1&)obj).fTsumw2 = fTsumw2;
2530  ((TH1&)obj).fTsumwx = fTsumwx;
2531  ((TH1&)obj).fTsumwx2 = fTsumwx2;
2532  ((TH1&)obj).fMaximum = fMaximum;
2533  ((TH1&)obj).fMinimum = fMinimum;
2534 
2535  TAttLine::Copy(((TH1&)obj));
2536  TAttFill::Copy(((TH1&)obj));
2537  TAttMarker::Copy(((TH1&)obj));
2538  fXaxis.Copy(((TH1&)obj).fXaxis);
2539  fYaxis.Copy(((TH1&)obj).fYaxis);
2540  fZaxis.Copy(((TH1&)obj).fZaxis);
2541  ((TH1&)obj).fXaxis.SetParent(&obj);
2542  ((TH1&)obj).fYaxis.SetParent(&obj);
2543  ((TH1&)obj).fZaxis.SetParent(&obj);
2544  fContour.Copy(((TH1&)obj).fContour);
2545  fSumw2.Copy(((TH1&)obj).fSumw2);
2546  // fFunctions->Copy(((TH1&)obj).fFunctions);
2547  // when copying an histogram if the AddDirectoryStatus() is true it
2548  // will be added to gDirectory independently of the fDirectory stored.
2549  // and if the AddDirectoryStatus() is false it will not be added to
2550  // any directory (fDirectory = 0)
2551  if (fgAddDirectory && gDirectory) {
2552  gDirectory->Append(&obj);
2553  ((TH1&)obj).fDirectory = gDirectory;
2554  } else
2555  ((TH1&)obj).fDirectory = 0;
2556 
2557 }
2558 
2559 
2560 ////////////////////////////////////////////////////////////////////////////////
2561 /// Make a complete copy of the underlying object. If 'newname' is set,
2562 /// the copy's name will be set to that name.
2563 
2564 TObject* TH1::Clone(const char* newname) const
2566  TH1* obj = (TH1*)IsA()->GetNew()(0);
2567  Copy(*obj);
2568 
2569  //Now handle the parts that Copy doesn't do
2570  if(fFunctions) {
2571  if (obj->fFunctions) delete obj->fFunctions;
2572  obj->fFunctions = (TList*)fFunctions->Clone();
2573  }
2574  if(newname && strlen(newname) ) {
2575  obj->SetName(newname);
2576  }
2577  return obj;
2578 }
2579 
2580 ////////////////////////////////////////////////////////////////////////////////
2581 /// Perform the automatic addition of the histogram to the given directory
2582 ///
2583 /// Note this function is called in place when the semantic requires
2584 /// this object to be added to a directory (I.e. when being read from
2585 /// a TKey or being Cloned)
2586 ///
2587 
2590  Bool_t addStatus = TH1::AddDirectoryStatus();
2591  if (addStatus) {
2592  SetDirectory(dir);
2593  if (dir) {
2595  }
2596  }
2597 }
2598 
2599 
2600 ////////////////////////////////////////////////////////////////////////////////
2601 /// Compute distance from point px,py to a line.
2602 ///
2603 /// Compute the closest distance of approach from point px,py to elements
2604 /// of an histogram.
2605 /// The distance is computed in pixels units.
2606 ///
2607 /// Algorithm:
2608 /// Currently, this simple model computes the distance from the mouse
2609 /// to the histogram contour only.
2610 
2613  if (!fPainter) return 9999;
2614  return fPainter->DistancetoPrimitive(px,py);
2615 }
2616 
2617 
2618 ////////////////////////////////////////////////////////////////////////////////
2619 /// Performs the operation: this = this/(c1*f1)
2620 /// if errors are defined (see TH1::Sumw2), errors are also recalculated.
2621 ///
2622 /// Only bins inside the function range are recomputed.
2623 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
2624 /// you should call Sumw2 before making this operation.
2625 /// This is particularly important if you fit the histogram after TH1::Divide
2626 ///
2627 /// The function return kFALSE if the divide operation failed
2628 
2631  if (!f1) {
2632  Error("Add","Attempt to divide by a non-existing function");
2633  return kFALSE;
2634  }
2635 
2636  // delete buffer if it is there since it will become invalid
2637  if (fBuffer) BufferEmpty(1);
2638 
2639  Int_t nx = GetNbinsX() + 2; // normal bins + uf / of
2640  Int_t ny = GetNbinsY() + 2;
2641  Int_t nz = GetNbinsZ() + 2;
2642  if (fDimension < 2) ny = 1;
2643  if (fDimension < 3) nz = 1;
2644 
2645 
2646  SetMinimum();
2647  SetMaximum();
2648 
2649  // - Loop on bins (including underflows/overflows)
2650  Int_t bin, binx, biny, binz;
2651  Double_t cu, w;
2652  Double_t xx[3];
2653  Double_t *params = 0;
2654  f1->InitArgs(xx,params);
2655  for (binz = 0; binz < nz; ++binz) {
2656  xx[2] = fZaxis.GetBinCenter(binz);
2657  for (biny = 0; biny < ny; ++biny) {
2658  xx[1] = fYaxis.GetBinCenter(biny);
2659  for (binx = 0; binx < nx; ++binx) {
2660  xx[0] = fXaxis.GetBinCenter(binx);
2661  if (!f1->IsInside(xx)) continue;
2663  bin = binx + nx * (biny + ny * binz);
2664  cu = c1 * f1->EvalPar(xx);
2665  if (TF1::RejectedPoint()) continue;
2666  if (cu) w = RetrieveBinContent(bin) / cu;
2667  else w = 0;
2668  UpdateBinContent(bin, w);
2669  if (fSumw2.fN) {
2670  if (cu != 0) fSumw2.fArray[bin] = GetBinErrorSqUnchecked(bin) / (cu * cu);
2671  else fSumw2.fArray[bin] = 0;
2672  }
2673  }
2674  }
2675  }
2676  ResetStats();
2677  return kTRUE;
2678 }
2679 
2680 
2681 ////////////////////////////////////////////////////////////////////////////////
2682 /// Divide this histogram by h1.
2683 ///
2684 /// this = this/h1
2685 /// if errors are defined (see TH1::Sumw2), errors are also recalculated.
2686 /// Note that if h1 has Sumw2 set, Sumw2 is automatically called for this
2687 /// if not already set.
2688 /// The resulting errors are calculated assuming uncorrelated histograms.
2689 /// See the other TH1::Divide that gives the possibility to optionally
2690 /// compute binomial errors.
2691 ///
2692 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
2693 /// you should call Sumw2 before making this operation.
2694 /// This is particularly important if you fit the histogram after TH1::Scale
2695 ///
2696 /// The function return kFALSE if the divide operation failed
2697 
2698 Bool_t TH1::Divide(const TH1 *h1)
2700  if (!h1) {
2701  Error("Divide", "Input histogram passed does not exist (NULL).");
2702  return kFALSE;
2703  }
2704 
2705  // delete buffer if it is there since it will become invalid
2706  if (fBuffer) BufferEmpty(1);
2707 
2708  try {
2709  CheckConsistency(this,h1);
2710  } catch(DifferentNumberOfBins&) {
2711  Error("Divide","Cannot divide histograms with different number of bins");
2712  return kFALSE;
2713  } catch(DifferentAxisLimits&) {
2714  Warning("Divide","Dividing histograms with different axis limits");
2715  } catch(DifferentBinLimits&) {
2716  Warning("Divide","Dividing histograms with different bin limits");
2717  } catch(DifferentLabels&) {
2718  Warning("Divide","Dividing histograms with different labels");
2719  }
2720 
2721  // Create Sumw2 if h1 has Sumw2 set
2722  if (fSumw2.fN == 0 && h1->GetSumw2N() != 0) Sumw2();
2723 
2724  // - Loop on bins (including underflows/overflows)
2725  for (Int_t i = 0; i < fNcells; ++i) {
2726  Double_t c0 = RetrieveBinContent(i);
2727  Double_t c1 = h1->RetrieveBinContent(i);
2728  if (c1) UpdateBinContent(i, c0 / c1);
2729  else UpdateBinContent(i, 0);
2730 
2731  if(fSumw2.fN) {
2732  if (c1 == 0) { fSumw2.fArray[i] = 0; continue; }
2733  Double_t c1sq = c1 * c1;
2734  fSumw2.fArray[i] = (GetBinErrorSqUnchecked(i) * c1sq + h1->GetBinErrorSqUnchecked(i) * c0 * c0) / (c1sq * c1sq);
2735  }
2736  }
2737  ResetStats();
2738  return kTRUE;
2739 }
2740 
2741 
2742 ////////////////////////////////////////////////////////////////////////////////
2743 /// Replace contents of this histogram by the division of h1 by h2.
2744 ///
2745 /// this = c1*h1/(c2*h2)
2746 ///
2747 /// If errors are defined (see TH1::Sumw2), errors are also recalculated
2748 /// Note that if h1 or h2 have Sumw2 set, Sumw2 is automatically called for this
2749 /// if not already set.
2750 /// The resulting errors are calculated assuming uncorrelated histograms.
2751 /// However, if option ="B" is specified, Binomial errors are computed.
2752 /// In this case c1 and c2 do not make real sense and they are ignored.
2753 ///
2754 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
2755 /// you should call Sumw2 before making this operation.
2756 /// This is particularly important if you fit the histogram after TH1::Divide
2757 ///
2758 /// Please note also that in the binomial case errors are calculated using standard
2759 /// binomial statistics, which means when b1 = b2, the error is zero.
2760 /// If you prefer to have efficiency errors not going to zero when the efficiency is 1, you must
2761 /// use the function TGraphAsymmErrors::BayesDivide, which will return an asymmetric and non-zero lower
2762 /// error for the case b1=b2.
2763 ///
2764 /// The function return kFALSE if the divide operation failed
2765 
2766 Bool_t TH1::Divide(const TH1 *h1, const TH1 *h2, Double_t c1, Double_t c2, Option_t *option)
2768 
2769  TString opt = option;
2770  opt.ToLower();
2771  Bool_t binomial = kFALSE;
2772  if (opt.Contains("b")) binomial = kTRUE;
2773  if (!h1 || !h2) {
2774  Error("Divide", "At least one of the input histograms passed does not exist (NULL).");
2775  return kFALSE;
2776  }
2777 
2778  // delete buffer if it is there since it will become invalid
2779  if (fBuffer) BufferEmpty(1);
2780 
2781  try {
2782  CheckConsistency(h1,h2);
2783  CheckConsistency(this,h1);
2784  } catch(DifferentNumberOfBins&) {
2785  Error("Divide","Cannot divide histograms with different number of bins");
2786  return kFALSE;
2787  } catch(DifferentAxisLimits&) {
2788  Warning("Divide","Dividing histograms with different axis limits");
2789  } catch(DifferentBinLimits&) {
2790  Warning("Divide","Dividing histograms with different bin limits");
2791  } catch(DifferentLabels&) {
2792  Warning("Divide","Dividing histograms with different labels");
2793  }
2794 
2795 
2796  if (!c2) {
2797  Error("Divide","Coefficient of dividing histogram cannot be zero");
2798  return kFALSE;
2799  }
2800 
2801  // Create Sumw2 if h1 or h2 have Sumw2 set
2802  if (fSumw2.fN == 0 && (h1->GetSumw2N() != 0 || h2->GetSumw2N() != 0)) Sumw2();
2803 
2804  SetMinimum();
2805  SetMaximum();
2806 
2807  // - Loop on bins (including underflows/overflows)
2808  for (Int_t i = 0; i < fNcells; ++i) {
2809  Double_t b1 = h1->RetrieveBinContent(i);
2810  Double_t b2 = h2->RetrieveBinContent(i);
2811  if (b2) UpdateBinContent(i, c1 * b1 / (c2 * b2));
2812  else UpdateBinContent(i, 0);
2813 
2814  if (fSumw2.fN) {
2815  if (b2 == 0) { fSumw2.fArray[i] = 0; continue; }
2816  Double_t b1sq = b1 * b1; Double_t b2sq = b2 * b2;
2817  Double_t c1sq = c1 * c1; Double_t c2sq = c2 * c2;
2818  Double_t e1sq = h1->GetBinErrorSqUnchecked(i);
2819  Double_t e2sq = h2->GetBinErrorSqUnchecked(i);
2820  if (binomial) {
2821  if (b1 != b2) {
2822  // in the case of binomial statistics c1 and c2 must be 1 otherwise it does not make sense
2823  // c1 and c2 are ignored
2824  //fSumw2.fArray[bin] = TMath::Abs(w*(1-w)/(c2*b2));//this is the formula in Hbook/Hoper1
2825  //fSumw2.fArray[bin] = TMath::Abs(w*(1-w)/b2); // old formula from G. Flucke
2826  // formula which works also for weighted histogram (see http://root.cern.ch/phpBB2/viewtopic.php?t=3753 )
2827  fSumw2.fArray[i] = TMath::Abs( ( (1. - 2.* b1 / b2) * e1sq + b1sq * e2sq / b2sq ) / b2sq );
2828  } else {
2829  //in case b1=b2 error is zero
2830  //use TGraphAsymmErrors::BayesDivide for getting the asymmetric error not equal to zero
2831  fSumw2.fArray[i] = 0;
2832  }
2833  } else {
2834  fSumw2.fArray[i] = c1sq * c2sq * (e1sq * b2sq + e2sq * b1sq) / (c2sq * c2sq * b2sq * b2sq);
2835  }
2836  }
2837  }
2838  ResetStats();
2839  if (binomial)
2840  // in case of binomial division use denominator for number of entries
2841  SetEntries ( h2->GetEntries() );
2842 
2843  return kTRUE;
2844 }
2845 
2846 
2847 ////////////////////////////////////////////////////////////////////////////////
2848 /// Draw this histogram with options.
2849 ///
2850 /// Histograms are drawn via the THistPainter class. Each histogram has
2851 /// a pointer to its own painter (to be usable in a multithreaded program).
2852 /// The same histogram can be drawn with different options in different pads.
2853 /// When an histogram drawn in a pad is deleted, the histogram is
2854 /// automatically removed from the pad or pads where it was drawn.
2855 /// If an histogram is drawn in a pad, then filled again, the new status
2856 /// of the histogram will be automatically shown in the pad next time
2857 /// the pad is updated. One does not need to redraw the histogram.
2858 /// To draw the current version of an histogram in a pad, one can use
2859 /// h->DrawCopy();
2860 /// This makes a clone of the histogram. Once the clone is drawn, the original
2861 /// histogram may be modified or deleted without affecting the aspect of the
2862 /// clone.
2863 /// By default, TH1::Draw clears the current pad.
2864 ///
2865 /// One can use TH1::SetMaximum and TH1::SetMinimum to force a particular
2866 /// value for the maximum or the minimum scale on the plot.
2867 ///
2868 /// TH1::UseCurrentStyle can be used to change all histogram graphics
2869 /// attributes to correspond to the current selected style.
2870 /// This function must be called for each histogram.
2871 /// In case one reads and draws many histograms from a file, one can force
2872 /// the histograms to inherit automatically the current graphics style
2873 /// by calling before gROOT->ForceStyle();
2874 ///
2875 /// See the THistPainter class for a description of all the drawing options.
2876 
2877 void TH1::Draw(Option_t *option)
2879  TString opt1 = option; opt1.ToLower();
2880  TString opt2 = option;
2881  Int_t index = opt1.Index("same");
2882 
2883  // Check if the string "same" is part of a TCutg name.
2884  if (index>=0) {
2885  Int_t indb = opt1.Index("[");
2886  if (indb>=0) {
2887  Int_t indk = opt1.Index("]");
2888  if (index>indb && index<indk) index = -1;
2889  }
2890  }
2891 
2892  // If there is no pad or an empty pad the the "same" is ignored.
2893  if (gPad) {
2894  if (!gPad->IsEditable()) gROOT->MakeDefCanvas();
2895  if (index>=0) {
2896  if (gPad->GetX1() == 0 && gPad->GetX2() == 1 &&
2897  gPad->GetY1() == 0 && gPad->GetY2() == 1 &&
2898  gPad->GetListOfPrimitives()->GetSize()==0) opt2.Remove(index,4);
2899  } else {
2900  //the following statement is necessary in case one attempts to draw
2901  //a temporary histogram already in the current pad
2902  if (TestBit(kCanDelete)) gPad->GetListOfPrimitives()->Remove(this);
2903  gPad->Clear();
2904  }
2905  } else {
2906  if (index>=0) opt2.Remove(index,4);
2907  }
2908 
2909  AppendPad(opt2.Data());
2910 }
2911 
2912 
2913 ////////////////////////////////////////////////////////////////////////////////
2914 /// Copy this histogram and Draw in the current pad.
2915 ///
2916 /// Once the histogram is drawn into the pad, any further modification
2917 /// using graphics input will be made on the copy of the histogram,
2918 /// and not to the original object.
2919 /// By default a postfix "_copy" is added to the histogram name. Pass an empty postfix in case
2920 /// you want to draw an histogram with the same name
2921 ///
2922 /// See Draw for the list of options
2923 
2924 TH1 *TH1::DrawCopy(Option_t *option, const char * name_postfix) const
2926  TString opt = option;
2927  opt.ToLower();
2928  if (gPad && !opt.Contains("same")) gPad->Clear();
2929  TString newName = (name_postfix) ? TString::Format("%s%s",GetName(),name_postfix) : "";
2930  TH1 *newth1 = (TH1 *)Clone(newName);
2931  newth1->SetDirectory(0);
2932  newth1->SetBit(kCanDelete);
2933  newth1->AppendPad(option);
2934  return newth1;
2935 }
2936 
2937 
2938 ////////////////////////////////////////////////////////////////////////////////
2939 /// Draw a normalized copy of this histogram.
2940 ///
2941 /// A clone of this histogram is normalized to norm and drawn with option.
2942 /// A pointer to the normalized histogram is returned.
2943 /// The contents of the histogram copy are scaled such that the new
2944 /// sum of weights (excluding under and overflow) is equal to norm.
2945 /// Note that the returned normalized histogram is not added to the list
2946 /// of histograms in the current directory in memory.
2947 /// It is the user's responsability to delete this histogram.
2948 /// The kCanDelete bit is set for the returned object. If a pad containing
2949 /// this copy is cleared, the histogram will be automatically deleted.
2950 ///
2951 /// See Draw for the list of options
2952 
2953 TH1 *TH1::DrawNormalized(Option_t *option, Double_t norm) const
2955  Double_t sum = GetSumOfWeights();
2956  if (sum == 0) {
2957  Error("DrawNormalized","Sum of weights is null. Cannot normalize histogram: %s",GetName());
2958  return 0;
2959  }
2960  Bool_t addStatus = TH1::AddDirectoryStatus();
2962  TH1 *h = (TH1*)Clone();
2963  h->SetBit(kCanDelete);
2964  // in case of drawing with error options - scale correctly the error
2965  TString opt(option); opt.ToUpper();
2966  if (fSumw2.fN == 0) {
2967  h->Sumw2();
2968  // do not use in this case the "Error option " for drawing which is enabled by default since the normalized histogram has now errors
2969  if (opt.IsNull() || opt == "SAME") opt += "HIST";
2970  }
2971  h->Scale(norm/sum);
2972  if (TMath::Abs(fMaximum+1111) > 1e-3) h->SetMaximum(fMaximum*norm/sum);
2973  if (TMath::Abs(fMinimum+1111) > 1e-3) h->SetMinimum(fMinimum*norm/sum);
2974  h->Draw(opt);
2975  TH1::AddDirectory(addStatus);
2976  return h;
2977 }
2978 
2979 
2980 ////////////////////////////////////////////////////////////////////////////////
2981 /// Display a panel with all histogram drawing options.
2982 ///
2983 /// See class TDrawPanelHist for example
2984 
2985 void TH1::DrawPanel()
2987  if (!fPainter) {Draw(); if (gPad) gPad->Update();}
2988  if (fPainter) fPainter->DrawPanel();
2989 }
2990 
2991 
2992 ////////////////////////////////////////////////////////////////////////////////
2993 /// Evaluate function f1 at the center of bins of this histogram.
2994 ///
2995 /// If option "R" is specified, the function is evaluated only
2996 /// for the bins included in the function range.
2997 /// If option "A" is specified, the value of the function is added to the
2998 /// existing bin contents
2999 /// If option "S" is specified, the value of the function is used to
3000 /// generate a value, distributed according to the Poisson
3001 /// distribution, with f1 as the mean.
3002 
3003 void TH1::Eval(TF1 *f1, Option_t *option)
3005  Double_t x[3];
3006  Int_t range, stat, add;
3007  if (!f1) return;
3008 
3009  TString opt = option;
3010  opt.ToLower();
3011  if (opt.Contains("a")) add = 1;
3012  else add = 0;
3013  if (opt.Contains("s")) stat = 1;
3014  else stat = 0;
3015  if (opt.Contains("r")) range = 1;
3016  else range = 0;
3017 
3018  // delete buffer if it is there since it will become invalid
3019  if (fBuffer) BufferEmpty(1);
3020 
3021  Int_t nbinsx = fXaxis.GetNbins();
3022  Int_t nbinsy = fYaxis.GetNbins();
3023  Int_t nbinsz = fZaxis.GetNbins();
3024  if (!add) Reset();
3025 
3026  for (Int_t binz = 1; binz <= nbinsz; ++binz) {
3027  x[2] = fZaxis.GetBinCenter(binz);
3028  for (Int_t biny = 1; biny <= nbinsy; ++biny) {
3029  x[1] = fYaxis.GetBinCenter(biny);
3030  for (Int_t binx = 1; binx <= nbinsx; ++binx) {
3031  Int_t bin = GetBin(binx,biny,binz);
3032  x[0] = fXaxis.GetBinCenter(binx);
3033  if (range && !f1->IsInside(x)) continue;
3034  Double_t fu = f1->Eval(x[0], x[1], x[2]);
3035  if (stat) fu = gRandom->PoissonD(fu);
3036  AddBinContent(bin, fu);
3037  if (fSumw2.fN) fSumw2.fArray[bin] += TMath::Abs(fu);
3038  }
3039  }
3040  }
3041 }
3042 
3043 
3044 ////////////////////////////////////////////////////////////////////////////////
3045 /// Execute action corresponding to one event.
3046 ///
3047 /// This member function is called when a histogram is clicked with the locator
3048 ///
3049 /// If Left button clicked on the bin top value, then the content of this bin
3050 /// is modified according to the new position of the mouse when it is released.
3051 
3052 void TH1::ExecuteEvent(Int_t event, Int_t px, Int_t py)
3054  if (fPainter) fPainter->ExecuteEvent(event, px, py);
3055 }
3056 
3057 
3058 ////////////////////////////////////////////////////////////////////////////////
3059 /// This function allows to do discrete Fourier transforms of TH1 and TH2.
3060 /// Available transform types and flags are described below.
3061 ///
3062 /// To extract more information about the transform, use the function
3063 /// TVirtualFFT::GetCurrentTransform() to get a pointer to the current
3064 /// transform object.
3065 ///
3066 /// \param[out] h_output histogram for the output. If a null pointer is passed, a new histogram is created
3067 /// and returned, otherwise, the provided histogram is used and should be big enough
3068 /// \param[in] option option parameters consists of 3 parts:
3069 /// - option on what to return
3070 /// - "RE" - returns a histogram of the real part of the output
3071 /// - "IM" - returns a histogram of the imaginary part of the output
3072 /// - "MAG"- returns a histogram of the magnitude of the output
3073 /// - "PH" - returns a histogram of the phase of the output
3074 /// - option of transform type
3075 /// - "R2C" - real to complex transforms - default
3076 /// - "R2HC" - real to halfcomplex (special format of storing output data,
3077 /// results the same as for R2C)
3078 /// - "DHT" - discrete Hartley transform
3079 /// real to real transforms (sine and cosine):
3080 /// - "R2R_0", "R2R_1", "R2R_2", "R2R_3" - discrete cosine transforms of types I-IV
3081 /// - "R2R_4", "R2R_5", "R2R_6", "R2R_7" - discrete sine transforms of types I-IV
3082 /// To specify the type of each dimension of a 2-dimensional real to real
3083 /// transform, use options of form "R2R_XX", for example, "R2R_02" for a transform,
3084 /// which is of type "R2R_0" in 1st dimension and "R2R_2" in the 2nd.
3085 /// - option of transform flag
3086 /// - "ES" (from "estimate") - no time in preparing the transform, but probably sub-optimal
3087 /// performance
3088 /// - "M" (from "measure") - some time spend in finding the optimal way to do the transform
3089 /// - "P" (from "patient") - more time spend in finding the optimal way to do the transform
3090 /// - "EX" (from "exhaustive") - the most optimal way is found
3091 /// This option should be chosen depending on how many transforms of the same size and
3092 /// type are going to be done. Planning is only done once, for the first transform of this
3093 /// size and type. Default is "ES".
3094 ///
3095 /// Examples of valid options: "Mag R2C M" "Re R2R_11" "Im R2C ES" "PH R2HC EX"
3096 
3097 TH1* TH1::FFT(TH1* h_output, Option_t *option)
3099 
3100  Int_t ndim[3];
3101  ndim[0] = this->GetNbinsX();
3102  ndim[1] = this->GetNbinsY();
3103  ndim[2] = this->GetNbinsZ();
3104 
3105  TVirtualFFT *fft;
3106  TString opt = option;
3107  opt.ToUpper();
3108  if (!opt.Contains("2R")){
3109  if (!opt.Contains("2C") && !opt.Contains("2HC") && !opt.Contains("DHT")) {
3110  //no type specified, "R2C" by default
3111  opt.Append("R2C");
3112  }
3113  fft = TVirtualFFT::FFT(this->GetDimension(), ndim, opt.Data());
3114  }
3115  else {
3116  //find the kind of transform
3117  Int_t ind = opt.Index("R2R", 3);
3118  Int_t *kind = new Int_t[2];
3119  char t;
3120  t = opt[ind+4];
3121  kind[0] = atoi(&t);
3122  if (h_output->GetDimension()>1) {
3123  t = opt[ind+5];
3124  kind[1] = atoi(&t);
3125  }
3126  fft = TVirtualFFT::SineCosine(this->GetDimension(), ndim, kind, option);
3127  delete [] kind;
3128  }
3129 
3130  if (!fft) return 0;
3131  Int_t in=0;
3132  for (Int_t binx = 1; binx<=ndim[0]; binx++) {
3133  for (Int_t biny=1; biny<=ndim[1]; biny++) {
3134  for (Int_t binz=1; binz<=ndim[2]; binz++) {
3135  fft->SetPoint(in, this->GetBinContent(binx, biny, binz));
3136  in++;
3137  }
3138  }
3139  }
3140  fft->Transform();
3141  h_output = TransformHisto(fft, h_output, option);
3142  return h_output;
3143 }
3144 
3145 
3146 ////////////////////////////////////////////////////////////////////////////////
3147 /// Increment bin with abscissa X by 1.
3148 ///
3149 /// if x is less than the low-edge of the first bin, the Underflow bin is incremented
3150 /// if x is greater than the upper edge of last bin, the Overflow bin is incremented
3151 ///
3152 /// If the storage of the sum of squares of weights has been triggered,
3153 /// via the function Sumw2, then the sum of the squares of weights is incremented
3154 /// by 1 in the bin corresponding to x.
3155 ///
3156 /// The function returns the corresponding bin number which has its content incremented by 1
3157 
3160  if (fBuffer) return BufferFill(x,1);
3161 
3162  Int_t bin;
3163  fEntries++;
3164  bin =fXaxis.FindBin(x);
3165  if (bin <0) return -1;
3166  AddBinContent(bin);
3167  if (fSumw2.fN) ++fSumw2.fArray[bin];
3168  if (bin == 0 || bin > fXaxis.GetNbins()) {
3169  if (!fgStatOverflows) return -1;
3170  }
3171  ++fTsumw;
3172  ++fTsumw2;
3173  fTsumwx += x;
3174  fTsumwx2 += x*x;
3175  return bin;
3176 }
3177 
3178 
3179 ////////////////////////////////////////////////////////////////////////////////
3180 /// Increment bin with abscissa X with a weight w.
3181 ///
3182 /// if x is less than the low-edge of the first bin, the Underflow bin is incremented
3183 /// if x is greater than the upper edge of last bin, the Overflow bin is incremented
3184 ///
3185 /// If the weight is not equal to 1, the storage of the sum of squares of
3186 /// weights is automatically triggered and the sum of the squares of weights is incremented
3187 /// by w^2 in the bin corresponding to x.
3188 ///
3189 /// The function returns the corresponding bin number which has its content incremented by w
3190 
3193 
3194  if (fBuffer) return BufferFill(x,w);
3195 
3196  Int_t bin;
3197  fEntries++;
3198  bin =fXaxis.FindBin(x);
3199  if (bin <0) return -1;
3200  if (!fSumw2.fN && w != 1.0 && !TestBit(TH1::kIsNotW) ) Sumw2(); // must be called before AddBinContent
3201  if (fSumw2.fN) fSumw2.fArray[bin] += w*w;
3202  AddBinContent(bin, w);
3203  if (bin == 0 || bin > fXaxis.GetNbins()) {
3204  if (!fgStatOverflows) return -1;
3205  }
3206  Double_t z= w;
3207  fTsumw += z;
3208  fTsumw2 += z*z;
3209  fTsumwx += z*x;
3210  fTsumwx2 += z*x*x;
3211  return bin;
3212 }
3213 
3214 
3215 ////////////////////////////////////////////////////////////////////////////////
3216 /// Increment bin with namex with a weight w
3217 ///
3218 /// if x is less than the low-edge of the first bin, the Underflow bin is incremented
3219 /// if x is greater than the upper edge of last bin, the Overflow bin is incremented
3220 ///
3221 /// If the weight is not equal to 1, the storage of the sum of squares of
3222 /// weights is automatically triggered and the sum of the squares of weights is incremented
3223 /// by w^2 in the bin corresponding to x.
3224 ///
3225 /// The function returns the corresponding bin number which has its content
3226 /// incremented by w
3227 
3228 Int_t TH1::Fill(const char *namex, Double_t w)
3230  Int_t bin;
3231  fEntries++;
3232  bin =fXaxis.FindBin(namex);
3233  if (bin <0) return -1;
3234  if (!fSumw2.fN && w != 1.0 && !TestBit(TH1::kIsNotW)) Sumw2();
3235  if (fSumw2.fN) fSumw2.fArray[bin] += w*w;
3236  AddBinContent(bin, w);
3237  if (bin == 0 || bin > fXaxis.GetNbins()) return -1;
3238  Double_t z= w;
3239  fTsumw += z;
3240  fTsumw2 += z*z;
3241  // this make sense if the histogram is not expanding (no axis can be extended)
3242  if (!CanExtendAllAxes()) {
3243  Double_t x = fXaxis.GetBinCenter(bin);
3244  fTsumwx += z*x;
3245  fTsumwx2 += z*x*x;
3246  }
3247  return bin;
3248 }
3249 
3250 
3251 ////////////////////////////////////////////////////////////////////////////////
3252 /// Fill this histogram with an array x and weights w.
3253 ///
3254 /// \param[in] ntimes number of entries in arrays x and w (array size must be ntimes*stride)
3255 /// \param[in] x array of values to be histogrammed
3256 /// \param[in[ w array of weighs
3257 /// \param[in] stride step size through arrays x and w
3258 ///
3259 /// If the weight is not equal to 1, the storage of the sum of squares of
3260 /// weights is automatically triggered and the sum of the squares of weights is incremented
3261 /// y w^2 in the bin corresponding to x.
3262 /// if w is NULL each entry is assumed a weight=1
3263 
3264 void TH1::FillN(Int_t ntimes, const Double_t *x, const Double_t *w, Int_t stride)
3266  //If a buffer is activated, fill buffer
3267  if (fBuffer) {
3268  ntimes *= stride;
3269  Int_t i = 0;
3270  for (i=0;i<ntimes;i+=stride) {
3271  if (!fBuffer) break; // buffer can be deleted in BufferFill when is empty
3272  if (w) BufferFill(x[i],w[i]);
3273  else BufferFill(x[i], 1.);
3274  }
3275  // fill the remaining entries if the buffer has been deleted
3276  if (i < ntimes && fBuffer==0)
3277  DoFillN((ntimes-i)/stride,&x[i],&w[i],stride);
3278  return;
3279  }
3280  // call internal method
3281  DoFillN(ntimes, x, w, stride);
3282 }
3283 
3284 ////////////////////////////////////////////////////////////////////////////////
3285 /// internal method to fill histogram content from a vector
3286 /// called directly by TH1::BufferEmpty
3287 
3288 void TH1::DoFillN(Int_t ntimes, const Double_t *x, const Double_t *w, Int_t stride)
3290  Int_t bin,i;
3291 
3292  fEntries += ntimes;
3293  Double_t ww = 1;
3294  Int_t nbins = fXaxis.GetNbins();
3295  ntimes *= stride;
3296  for (i=0;i<ntimes;i+=stride) {
3297  bin =fXaxis.FindBin(x[i]);
3298  if (bin <0) continue;
3299  if (w) ww = w[i];
3300  if (!fSumw2.fN && ww != 1.0 && !TestBit(TH1::kIsNotW)) Sumw2();
3301  if (fSumw2.fN) fSumw2.fArray[bin] += ww*ww;
3302  AddBinContent(bin, ww);
3303  if (bin == 0 || bin > nbins) {
3304  if (!fgStatOverflows) continue;
3305  }
3306  Double_t z= ww;
3307  fTsumw += z;
3308  fTsumw2 += z*z;
3309  fTsumwx += z*x[i];
3310  fTsumwx2 += z*x[i]*x[i];
3311  }
3312 }
3313 
3314 
3315 ////////////////////////////////////////////////////////////////////////////////
3316 /// Fill histogram following distribution in function fname.
3317 ///
3318 /// The distribution contained in the function fname (TF1) is integrated
3319 /// over the channel contents for the bin range of this histogram.
3320 /// It is normalized to 1.
3321 /// Getting one random number implies:
3322 /// - Generating a random number between 0 and 1 (say r1)
3323 /// - Look in which bin in the normalized integral r1 corresponds to
3324 /// - Fill histogram channel
3325 /// ntimes random numbers are generated
3326 ///
3327 /// One can also call TF1::GetRandom to get a random variate from a function.
3328 
3329 void TH1::FillRandom(const char *fname, Int_t ntimes)
3331  Int_t bin, binx, ibin, loop;
3332  Double_t r1, x;
3333  // - Search for fname in the list of ROOT defined functions
3334  TF1 *f1 = (TF1*)gROOT->GetFunction(fname);
3335  if (!f1) { Error("FillRandom", "Unknown function: %s",fname); return; }
3336 
3337  // - Allocate temporary space to store the integral and compute integral
3338 
3339  TAxis * xAxis = &fXaxis;
3340 
3341  // in case axis of histogram is not defined use the function axis
3342  if (fXaxis.GetXmax() <= fXaxis.GetXmin()) {
3343  Double_t xmin,xmax;
3344  f1->GetRange(xmin,xmax);
3345  Info("FillRandom","Using function axis and range [%g,%g]",xmin, xmax);
3346  xAxis = f1->GetHistogram()->GetXaxis();
3347  }
3348 
3349  Int_t first = xAxis->GetFirst();
3350  Int_t last = xAxis->GetLast();
3351  Int_t nbinsx = last-first+1;
3352 
3353  Double_t *integral = new Double_t[nbinsx+1];
3354  integral[0] = 0;
3355  for (binx=1;binx<=nbinsx;binx++) {
3356  Double_t fint = f1->Integral(xAxis->GetBinLowEdge(binx+first-1),xAxis->GetBinUpEdge(binx+first-1));
3357  integral[binx] = integral[binx-1] + fint;
3358  }
3359 
3360  // - Normalize integral to 1
3361  if (integral[nbinsx] == 0 ) {
3362  delete [] integral;
3363  Error("FillRandom", "Integral = zero"); return;
3364  }
3365  for (bin=1;bin<=nbinsx;bin++) integral[bin] /= integral[nbinsx];
3366 
3367  // --------------Start main loop ntimes
3368  for (loop=0;loop<ntimes;loop++) {
3369  r1 = gRandom->Rndm(loop);
3370  ibin = TMath::BinarySearch(nbinsx,&integral[0],r1);
3371  //binx = 1 + ibin;
3372  //x = xAxis->GetBinCenter(binx); //this is not OK when SetBuffer is used
3373  x = xAxis->GetBinLowEdge(ibin+first)
3374  +xAxis->GetBinWidth(ibin+first)*(r1-integral[ibin])/(integral[ibin+1] - integral[ibin]);
3375  Fill(x);
3376  }
3377  delete [] integral;
3378 }
3379 
3380 
3381 ////////////////////////////////////////////////////////////////////////////////
3382 /// Fill histogram following distribution in histogram h.
3383 ///
3384 /// The distribution contained in the histogram h (TH1) is integrated
3385 /// over the channel contents for the bin range of this histogram.
3386 /// It is normalized to 1.
3387 /// Getting one random number implies:
3388 /// - Generating a random number between 0 and 1 (say r1)
3389 /// - Look in which bin in the normalized integral r1 corresponds to
3390 /// - Fill histogram channel ntimes random numbers are generated
3391 ///
3392 /// SPECIAL CASE when the target histogram has the same binning as the source.
3393 /// in this case we simply use a poisson distribution where
3394 /// the mean value per bin = bincontent/integral.
3395 
3396 void TH1::FillRandom(TH1 *h, Int_t ntimes)
3398  if (!h) { Error("FillRandom", "Null histogram"); return; }
3399  if (fDimension != h->GetDimension()) {
3400  Error("FillRandom", "Histograms with different dimensions"); return;
3401  }
3402 
3403  //in case the target histogram has the same binning and ntimes much greater
3404  //than the number of bins we can use a fast method
3405  Int_t first = fXaxis.GetFirst();
3406  Int_t last = fXaxis.GetLast();
3407  Int_t nbins = last-first+1;
3408  if (ntimes > 10*nbins) {
3409  try {
3410  CheckConsistency(this,h);
3411  Double_t sumw = h->Integral(first,last);
3412  if (sumw == 0) return;
3413  Double_t sumgen = 0;
3414  for (Int_t bin=first;bin<=last;bin++) {
3415  Double_t mean = h->RetrieveBinContent(bin)*ntimes/sumw;
3416  Double_t cont = (Double_t)gRandom->Poisson(mean);
3417  sumgen += cont;
3418  AddBinContent(bin,cont);
3419  if (fSumw2.fN) fSumw2.fArray[bin] += cont;
3420  }
3421 
3422  // fix for the fluctations in the total number n
3423  // since we use Poisson instead of multinomial
3424  // add a correction to have ntimes as generated entries
3425  Int_t i;
3426  if (sumgen < ntimes) {
3427  // add missing entries
3428  for (i = Int_t(sumgen+0.5); i < ntimes; ++i)
3429  {
3430  Double_t x = h->GetRandom();
3431  Fill(x);
3432  }
3433  }
3434  else if (sumgen > ntimes) {
3435  // remove extra entries
3436  i = Int_t(sumgen+0.5);
3437  while( i > ntimes) {
3438  Double_t x = h->GetRandom();
3439  Int_t ibin = fXaxis.FindBin(x);
3440  Double_t y = RetrieveBinContent(ibin);
3441  // skip in case bin is empty
3442  if (y > 0) {
3443  SetBinContent(ibin, y-1.);
3444  i--;
3445  }
3446  }
3447  }
3448 
3449  ResetStats();
3450  return;
3451  }
3452  catch(std::exception&) {} // do nothing
3453  }
3454  // case of different axis and not too large ntimes
3455 
3456  if (h->ComputeIntegral() ==0) return;
3457  Int_t loop;
3458  Double_t x;
3459  for (loop=0;loop<ntimes;loop++) {
3460  x = h->GetRandom();
3461  Fill(x);
3462  }
3463 }
3464 
3465 
3466 ////////////////////////////////////////////////////////////////////////////////
3467 /// Return Global bin number corresponding to x,y,z
3468 ///
3469 /// 2-D and 3-D histograms are represented with a one dimensional
3470 /// structure. This has the advantage that all existing functions, such as
3471 /// GetBinContent, GetBinError, GetBinFunction work for all dimensions.
3472 /// This function tries to extend the axis if the given point belongs to an
3473 /// under-/overflow bin AND if CanExtendAllAxes() is true.
3474 ///
3475 /// See also TH1::GetBin, TAxis::FindBin and TAxis::FindFixBin
3476 
3479  if (GetDimension() < 2) {
3480  return fXaxis.FindBin(x);
3481  }
3482  if (GetDimension() < 3) {
3483  Int_t nx = fXaxis.GetNbins()+2;
3484  Int_t binx = fXaxis.FindBin(x);
3485  Int_t biny = fYaxis.FindBin(y);
3486  return binx + nx*biny;
3487  }
3488  if (GetDimension() < 4) {
3489  Int_t nx = fXaxis.GetNbins()+2;
3490  Int_t ny = fYaxis.GetNbins()+2;
3491  Int_t binx = fXaxis.FindBin(x);
3492  Int_t biny = fYaxis.FindBin(y);
3493  Int_t binz = fZaxis.FindBin(z);
3494  return binx + nx*(biny +ny*binz);
3495  }
3496  return -1;
3497 }
3498 
3499 
3500 ////////////////////////////////////////////////////////////////////////////////
3501 /// Return Global bin number corresponding to x,y,z.
3502 ///
3503 /// 2-D and 3-D histograms are represented with a one dimensional
3504 /// structure. This has the advantage that all existing functions, such as
3505 /// GetBinContent, GetBinError, GetBinFunction work for all dimensions.
3506 /// This function DOES NOT try to extend the axis if the given point belongs
3507 /// to an under-/overflow bin.
3508 ///
3509 /// See also TH1::GetBin, TAxis::FindBin and TAxis::FindFixBin
3510 
3513  if (GetDimension() < 2) {
3514  return fXaxis.FindFixBin(x);
3515  }
3516  if (GetDimension() < 3) {
3517  Int_t nx = fXaxis.GetNbins()+2;
3518  Int_t binx = fXaxis.FindFixBin(x);
3519  Int_t biny = fYaxis.FindFixBin(y);
3520  return binx + nx*biny;
3521  }
3522  if (GetDimension() < 4) {
3523  Int_t nx = fXaxis.GetNbins()+2;
3524  Int_t ny = fYaxis.GetNbins()+2;
3525  Int_t binx = fXaxis.FindFixBin(x);
3526  Int_t biny = fYaxis.FindFixBin(y);
3527  Int_t binz = fZaxis.FindFixBin(z);
3528  return binx + nx*(biny +ny*binz);
3529  }
3530  return -1;
3531 }
3532 
3533 
3534 ////////////////////////////////////////////////////////////////////////////////
3535 /// Find first bin with content > threshold for axis (1=x, 2=y, 3=z)
3536 /// if no bins with content > threshold is found the function returns -1.
3537 
3540  if (fBuffer) ((TH1*)this)->BufferEmpty();
3541 
3542  if (axis != 1) {
3543  Warning("FindFirstBinAbove","Invalid axis number : %d, axis x assumed\n",axis);
3544  axis = 1;
3545  }
3546  Int_t nbins = fXaxis.GetNbins();
3547  for (Int_t bin=1;bin<=nbins;bin++) {
3548  if (RetrieveBinContent(bin) > threshold) return bin;
3549  }
3550  return -1;
3551 }
3552 
3553 
3554 ////////////////////////////////////////////////////////////////////////////////
3555 /// Find last bin with content > threshold for axis (1=x, 2=y, 3=z)
3556 /// if no bins with content > threshold is found the function returns -1.
3557 
3558 Int_t TH1::FindLastBinAbove(Double_t threshold, Int_t axis) const
3560  if (fBuffer) ((TH1*)this)->BufferEmpty();
3561 
3562  if (axis != 1) {
3563  Warning("FindLastBinAbove","Invalid axis number : %d, axis x assumed\n",axis);
3564  axis = 1;
3565  }
3566  Int_t nbins = fXaxis.GetNbins();
3567  for (Int_t bin=nbins;bin>=1;bin--) {
3568  if (RetrieveBinContent(bin) > threshold) return bin;
3569  }
3570  return -1;
3571 }
3572 
3573 
3574 ////////////////////////////////////////////////////////////////////////////////
3575 /// search object named name in the list of functions
3576 
3577 TObject *TH1::FindObject(const char *name) const
3579  if (fFunctions) return fFunctions->FindObject(name);
3580  return 0;
3581 }
3582 
3583 
3584 ////////////////////////////////////////////////////////////////////////////////
3585 /// search object obj in the list of functions
3586 
3587 TObject *TH1::FindObject(const TObject *obj) const
3589  if (fFunctions) return fFunctions->FindObject(obj);
3590  return 0;
3591 }
3592 
3593 
3594 ////////////////////////////////////////////////////////////////////////////////
3595 /// Fit histogram with function fname.
3596 ///
3597 /// fname is the name of an already predefined function created by TF1 or TF2
3598 /// Predefined functions such as gaus, expo and poln are automatically
3599 /// created by ROOT.
3600 /// fname can also be a formula, accepted by the linear fitter (linear parts divided
3601 /// by "++" sign), for example "x++sin(x)" for fitting "[0]*x+[1]*sin(x)"
3602 ///
3603 /// This function finds a pointer to the TF1 object with name fname
3604 /// and calls TH1::Fit(TF1 *f1,...)
3605 
3606 TFitResultPtr TH1::Fit(const char *fname ,Option_t *option ,Option_t *goption, Double_t xxmin, Double_t xxmax)
3608  char *linear;
3609  linear= (char*)strstr(fname, "++");
3610  TF1 *f1=0;
3611  TF2 *f2=0;
3612  TF3 *f3=0;
3613  Int_t ndim=GetDimension();
3614  if (linear){
3615  if (ndim<2){
3616  f1=new TF1(fname, fname, xxmin, xxmax);
3617  return Fit(f1,option,goption,xxmin,xxmax);
3618  }
3619  else if (ndim<3){
3620  f2=new TF2(fname, fname);
3621  return Fit(f2,option,goption,xxmin,xxmax);
3622  }
3623  else{
3624  f3=new TF3(fname, fname);
3625  return Fit(f3,option,goption,xxmin,xxmax);
3626  }
3627  }
3628 
3629  else{
3630  f1 = (TF1*)gROOT->GetFunction(fname);
3631  if (!f1) { Printf("Unknown function: %s",fname); return -1; }
3632  return Fit(f1,option,goption,xxmin,xxmax);
3633  }
3634 }
3635 
3636 
3637 ////////////////////////////////////////////////////////////////////////////////
3638 /// Fit histogram with function f1.
3639 ///
3640 /// \param[in] option fit options is given in parameter option.
3641 /// - "W" Set all weights to 1 for non empty bins; ignore error bars
3642 /// - "WW" Set all weights to 1 including empty bins; ignore error bars
3643 /// - "I" Use integral of function in bin, normalized by the bin volume,
3644 /// instead of value at bin center
3645 /// - "L" Use Loglikelihood method (default is chisquare method)
3646 /// - "WL" Use Loglikelihood method and bin contents are not integer,
3647 /// i.e. histogram is weighted (must have Sumw2() set)
3648 /// - "P" Use Pearson chi2 (using expected errors instead of observed errors)
3649 /// - "U" Use a User specified fitting algorithm (via SetFCN)
3650 /// - "Q" Quiet mode (minimum printing)
3651 /// - "V" Verbose mode (default is between Q and V)
3652 /// - "E" Perform better Errors estimation using Minos technique
3653 /// - "B" User defined parameter settings are used for predefined functions
3654 /// like "gaus", "expo", "poln", "landau".
3655 /// Use this option when you want to fix one or more parameters for these functions.
3656 /// - "M" More. Improve fit results.
3657 /// It uses the IMPROVE command of TMinuit (see TMinuit::mnimpr).
3658 /// This algorithm attempts to improve the found local minimum by searching for a
3659 /// better one.
3660 /// - "R" Use the Range specified in the function range
3661 /// - "N" Do not store the graphics function, do not draw
3662 /// - "0" Do not plot the result of the fit. By default the fitted function
3663 /// is drawn unless the option"N" above is specified.
3664 /// - "+" Add this new fitted function to the list of fitted functions
3665 /// (by default, any previous function is deleted)
3666 /// - "C" In case of linear fitting, don't calculate the chisquare
3667 /// (saves time)
3668 /// - "F" If fitting a polN, switch to minuit fitter
3669 /// - "S" The result of the fit is returned in the TFitResultPtr
3670 /// (see below Access to the Fit Result)
3671 /// \param[in] goption specify a list of graphics options. See TH1::Draw for a complete list of these options.
3672 /// \param[in] xxmin range
3673 /// \param[in] xxmax range
3674 ///
3675 /// In order to use the Range option, one must first create a function
3676 /// with the expression to be fitted. For example, if your histogram
3677 /// has a defined range between -4 and 4 and you want to fit a gaussian
3678 /// only in the interval 1 to 3, you can do:
3679 ///
3680 /// TF1 *f1 = new TF1("f1", "gaus", 1, 3);
3681 /// histo->Fit("f1", "R");
3682 ///
3683 /// ## Setting initial conditions
3684 /// Parameters must be initialized before invoking the Fit function.
3685 /// The setting of the parameter initial values is automatic for the
3686 /// predefined functions : poln, expo, gaus, landau. One can however disable
3687 /// this automatic computation by specifying the option "B".
3688 /// Note that if a predefined function is defined with an argument,
3689 /// eg, gaus(0), expo(1), you must specify the initial values for
3690 /// the parameters.
3691 /// You can specify boundary limits for some or all parameters via
3692 ///
3693 /// f1->SetParLimits(p_number, parmin, parmax);
3694 /// if parmin>=parmax, the parameter is fixed
3695 /// Note that you are not forced to fix the limits for all parameters.
3696 /// For example, if you fit a function with 6 parameters, you can do:
3697 ///
3698 /// func->SetParameters(0, 3.1, 1.e-6, -8, 0, 100);
3699 /// func->SetParLimits(3, -10, -4);
3700 /// func->FixParameter(4, 0);
3701 /// func->SetParLimits(5, 1, 1);
3702 /// With this setup, parameters 0->2 can vary freely
3703 /// Parameter 3 has boundaries [-10,-4] with initial value -8
3704 /// Parameter 4 is fixed to 0
3705 /// Parameter 5 is fixed to 100.
3706 /// When the lower limit and upper limit are equal, the parameter is fixed.
3707 /// However to fix a parameter to 0, one must call the FixParameter function.
3708 ///
3709 /// Note that option "I" gives better results but is slower.
3710 ///
3711 /// ## Changing the fitting objective function
3712 /// By default a chi square function is used for fitting. When option "L" (or "LL") is used
3713 /// a Poisson likelihood function (see note below) is used.
3714 /// The functions are defined in the header Fit/Chi2Func.h or Fit/PoissonLikelihoodFCN and they
3715 /// are implemented using the routines FitUtil::EvaluateChi2 or FitUtil::EvaluatePoissonLogL in
3716 /// the file math/mathcore/src/FitUtil.cxx.
3717 /// To specify a User defined fitting function, specify option "U" and
3718 /// call the following functions:
3719 ///
3720 /// TVirtualFitter::Fitter(myhist)->SetFCN(MyFittingFunction)
3721 /// where MyFittingFunction is of type:
3722 ///
3723 /// extern void MyFittingFunction(Int_t &npar, Double_t *gin, Double_t &f, Double_t *u, Int_t flag);
3724 ///
3725 /// ## Chi2 Fits
3726 /// By default a chi2 (least-square) fit is performed on the histogram. The so-called modified least-square method
3727 /// is used where the residual for each bin is computed using as error the observed value (the bin error)
3728 ///
3729 /// Chi2 = Sum{ ( y(i) - f (x(i) | p )/ e(i) )^2 }
3730 ///
3731 /// 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
3732 /// an un-weighted histogram. Bins with zero errors are excluded from the fit. See also later the note on the treatment of empty bins.
3733 /// When using option "I" the residual is computed not using the function value at the bin center, f (x(i) | p), but the integral
3734 /// of the function in the bin, Integral{ f(x|p)dx } divided by the bin volume
3735 ///
3736 /// ## Likelihood Fits
3737 /// When using option "L" a likelihood fit is used instead of the default chi2 square fit.
3738 /// The likelihood is built assuming a Poisson probability density function for each bin.
3739 /// The negative log-likelihood to be minimized is
3740 ///
3741 /// NLL = Sum{ log Poisson( y(i) |{ f(x(i) | p ) ) }
3742 /// The exact likelihood used is the Poisson likelihood described in this paper:
3743 /// S. Baker and R. D. Cousins, “Clarification of the use of chi-square and likelihood functions in fits to histograms,”
3744 /// Nucl. Instrum. Meth. 221 (1984) 437.
3745 ///
3746 /// This method can then be used only when the bin content represents counts (i.e. errors are sqrt(N) ).
3747 /// The likelihood method has the advantage of treating correctly bins with low statistics. In case of high
3748 /// statistics/bin the distribution of the bin content becomes a normal distribution and the likelihood and chi2 fit
3749 /// give the same result.
3750 ///
3751 /// The likelihood method, although a bit slower, it is therefore the recommended method in case of low
3752 /// bin statistics, where the chi2 method may give incorrect results, in particular when there are
3753 /// several empty bins (see also below).
3754 /// In case of a weighted histogram, it is possible to perform a likelihood fit by using the
3755 /// option "WL". Note a weighted histogram is an histogram which has been filled with weights and it
3756 /// contains the sum of the weight square ( TH1::Sumw2() has been called). The bin error for a weighted
3757 /// histogram is the square root of the sum of the weight square.
3758 ///
3759 /// ## Treatment of Empty Bins
3760 /// Empty bins, which have the content equal to zero AND error equal to zero,
3761 /// are excluded by default from the chisquare fit, but they are considered in the likelihood fit.
3762 /// since they affect the likelihood if the function value in these bins is not negligible.
3763 /// When using option "WW" these bins will be considered in the chi2 fit with an error of 1.
3764 /// Note that if the histogram is having bins with zero content and non zero-errors they are considered as
3765 /// any other bins in the fit. Instead bins with zero error and non-zero content are excluded in the chi2 fit.
3766 /// A likelihood fit should also not be peformed on such an histogram, since we are assuming a wrong pdf for each bin.
3767 /// In general, one should not fit an histogram with non-empty bins and zero errors, apart if all the bins have zero errors.
3768 /// In this case one could use the option "w", which gives a weight=1 for each bin (unweighted least-square fit).
3769 ///
3770 /// ## Fitting a histogram of dimension N with a function of dimension N-1
3771 /// It is possible to fit a TH2 with a TF1 or a TH3 with a TF2.
3772 /// In this case the option "Integral" is not allowed and each cell has
3773 /// equal weight.
3774 ///
3775 /// ## Associated functions
3776 /// One or more object (typically a TF1*) can be added to the list
3777 /// of functions (fFunctions) associated to each histogram.
3778 /// When TH1::Fit is invoked, the fitted function is added to this list.
3779 /// Given an histogram h, one can retrieve an associated function
3780 /// with: TF1 *myfunc = h->GetFunction("myfunc");
3781 ///
3782 /// ##Access to the fit result
3783 /// The function returns a TFitResultPtr which can hold a pointer to a TFitResult object.
3784 /// By default the TFitResultPtr contains only the status of the fit which is return by an
3785 /// automatic conversion of the TFitResultPtr to an integer. One can write in this case directly:
3786 ///
3787 /// Int_t fitStatus = h->Fit(myFunc)
3788 ///
3789 /// If the option "S" is instead used, TFitResultPtr contains the TFitResult and behaves as a smart
3790 /// pointer to it. For example one can do:
3791 ///
3792 /// TFitResultPtr r = h->Fit(myFunc,"S");
3793 /// TMatrixDSym cov = r->GetCovarianceMatrix(); // to access the covariance matrix
3794 /// Double_t chi2 = r->Chi2(); // to retrieve the fit chi2
3795 /// Double_t par0 = r->Parameter(0); // retrieve the value for the parameter 0
3796 /// Double_t err0 = r->ParError(0); // retrieve the error for the parameter 0
3797 /// r->Print("V"); // print full information of fit including covariance matrix
3798 /// r->Write(); // store the result in a file
3799 ///
3800 /// The fit parameters, error and chi2 (but not covariance matrix) can be retrieved also
3801 /// from the fitted function.
3802 /// If the histogram is made persistent, the list of
3803 /// associated functions is also persistent. Given a pointer (see above)
3804 /// to an associated function myfunc, one can retrieve the function/fit
3805 /// parameters with calls such as:
3806 ///
3807 /// Double_t chi2 = myfunc->GetChisquare();
3808 /// Double_t par0 = myfunc->GetParameter(0); //value of 1st parameter
3809 /// Double_t err0 = myfunc->GetParError(0); //error on first parameter
3810 ///
3811 /// ## Access to the fit status
3812 /// The status of the fit can be obtained converting the TFitResultPtr to an integer
3813 /// independently if the fit option "S" is used or not:
3814 ///
3815 /// TFitResultPtr r = h->Fit(myFunc,opt);
3816 /// Int_t fitStatus = r;
3817 ///
3818 /// The fitStatus is 0 if the fit is OK (i.e no error occurred).
3819 /// The value of the fit status code is negative in case of an error not connected with the
3820 /// minimization procedure, for example when a wrong function is used.
3821 /// Otherwise the return value is the one returned from the minimization procedure.
3822 /// When TMinuit (default case) or Minuit2 are used as minimizer the status returned is :
3823 /// fitStatus = migradResult + 10*minosResult + 100*hesseResult + 1000*improveResult.
3824 /// TMinuit will return 0 (for migrad, minos, hesse or improve) in case of success and 4 in
3825 /// case of error (see the documentation of TMinuit::mnexcm). So for example, for an error
3826 /// only in Minos but not in Migrad a fitStatus of 40 will be returned.
3827 /// Minuit2 will return also 0 in case of success and different values in migrad minos or
3828 /// hesse depending on the error. See in this case the documentation of
3829 /// Minuit2Minimizer::Minimize for the migradResult, Minuit2Minimizer::GetMinosError for the
3830 /// minosResult and Minuit2Minimizer::Hesse for the hesseResult.
3831 /// If other minimizers are used see their specific documentation for the status code returned.
3832 /// For example in the case of Fumili, for the status returned see TFumili::Minimize.
3833 ///
3834 /// ## Excluding points
3835 /// Use TF1::RejectPoint inside your fitting function to exclude points
3836 /// within a certain range from the fit. Example:
3837 ///
3838 /// Double_t fline(Double_t *x, Double_t *par)
3839 /// {
3840 /// if (x[0] > 2.5 && x[0] < 3.5) {
3841 /// TF1::RejectPoint();
3842 /// return 0;
3843 /// }
3844 /// return par[0] + par[1]*x[0];
3845 /// }
3846 ///
3847 /// void exclude() {
3848 /// TF1 *f1 = new TF1("f1", "[0] +[1]*x +gaus(2)", 0, 5);
3849 /// f1->SetParameters(6, -1,5, 3, 0.2);
3850 /// TH1F *h = new TH1F("h", "background + signal", 100, 0, 5);
3851 /// h->FillRandom("f1", 2000);
3852 /// TF1 *fline = new TF1("fline", fline, 0, 5, 2);
3853 /// fline->SetParameters(2, -1);
3854 /// h->Fit("fline", "l");
3855 /// }
3856 ///
3857 /// ## Warning when using the option "0"
3858 /// When selecting the option "0", the fitted function is added to
3859 /// the list of functions of the histogram, but it is not drawn.
3860 /// You can undo what you disabled in the following way:
3861 ///
3862 /// h.Fit("myFunction", "0"); // fit, store function but do not draw
3863 /// h.Draw(); function is not drawn
3864 /// const Int_t kNotDraw = 1<<9;
3865 /// h.GetFunction("myFunction")->ResetBit(kNotDraw);
3866 /// h.Draw(); // function is visible again
3867 ///
3868 /// ## Access to the Minimizer information during fitting
3869 /// This function calls, the ROOT::Fit::FitObject function implemented in HFitImpl.cxx
3870 /// which uses the ROOT::Fit::Fitter class. The Fitter class creates the objective fuction
3871 /// (e.g. chi2 or likelihood) and uses an implementation of the Minimizer interface for minimizing
3872 /// the function.
3873 /// The default minimizer is Minuit (class TMinuitMinimizer which calls TMinuit).
3874 /// The default can be set in the resource file in etc/system.rootrc. For example
3875 ///
3876 /// Root.Fitter: Minuit2
3877 /// A different fitter can also be set via ROOT::Math::MinimizerOptions::SetDefaultMinimizer
3878 /// (or TVirtualFitter::SetDefaultFitter).
3879 /// For example ROOT::Math::MinimizerOptions::SetDefaultMinimizer("GSLMultiMin","BFGS");
3880 /// will set the usdage of the BFGS algorithm of the GSL multi-dimensional minimization
3881 /// (implemented in libMathMore). ROOT::Math::MinimizerOptions can be used also to set other
3882 /// default options, like maximum number of function calls, minimization tolerance or print
3883 /// level. See the documentation of this class.
3884 ///
3885 /// For fitting linear functions (containing the "++" sign" and polN functions,
3886 /// the linear fitter is automatically initialized.
3887 
3888 TFitResultPtr TH1::Fit(TF1 *f1 ,Option_t *option ,Option_t *goption, Double_t xxmin, Double_t xxmax)
3890  // implementation of Fit method is in file hist/src/HFitImpl.cxx
3891  Foption_t fitOption;
3893 
3894  // create range and minimizer options with default values
3895  ROOT::Fit::DataRange range(xxmin,xxmax);
3896  ROOT::Math::MinimizerOptions minOption;
3897 
3898  // need to empty the buffer before
3899  // (t.b.d. do a ML unbinned fit with buffer data)
3900  if (fBuffer) BufferEmpty();
3901 
3902  return ROOT::Fit::FitObject(this, f1 , fitOption , minOption, goption, range);
3903 }
3904 
3905 
3906 ////////////////////////////////////////////////////////////////////////////////
3907 /// Display a panel with all histogram fit options.
3908 ///
3909 /// See class TFitPanel for example
3910 
3911 void TH1::FitPanel()
3913  if (!gPad)
3914  gROOT->MakeDefCanvas();
3915 
3916  if (!gPad) {
3917  Error("FitPanel", "Unable to create a default canvas");
3918  return;
3919  }
3920 
3921 
3922  // use plugin manager to create instance of TFitEditor
3923  TPluginHandler *handler = gROOT->GetPluginManager()->FindHandler("TFitEditor");
3924  if (handler && handler->LoadPlugin() != -1) {
3925  if (handler->ExecPlugin(2, gPad, this) == 0)
3926  Error("FitPanel", "Unable to create the FitPanel");
3927  }
3928  else
3929  Error("FitPanel", "Unable to find the FitPanel plug-in");
3930 }
3931 
3932 
3933 ////////////////////////////////////////////////////////////////////////////////
3934 /// Return an histogram containing the asymmetry of this histogram with h2,
3935 /// where the asymmetry is defined as:
3936 ///
3937 /// Asymmetry = (h1 - h2)/(h1 + h2) where h1 = this
3938 ///
3939 /// works for 1D, 2D, etc. histograms
3940 /// c2 is an optional argument that gives a relative weight between the two
3941 /// histograms, and dc2 is the error on this weight. This is useful, for example,
3942 /// when forming an asymmetry between two histograms from 2 different data sets that
3943 /// need to be normalized to each other in some way. The function calculates
3944 /// the errors asumming Poisson statistics on h1 and h2 (that is, dh = sqrt(h)).
3945 ///
3946 /// example: assuming 'h1' and 'h2' are already filled
3947 ///
3948 /// h3 = h1->GetAsymmetry(h2)
3949 ///
3950 /// then 'h3' is created and filled with the asymmetry between 'h1' and 'h2';
3951 /// h1 and h2 are left intact.
3952 ///
3953 /// Note that it is the user's responsibility to manage the created histogram.
3954 /// The name of the returned histogram will be Asymmetry_nameOfh1-nameOfh2
3955 ///
3956 /// code proposed by Jason Seely (seely@mit.edu) and adapted by R.Brun
3957 ///
3958 /// clone the histograms so top and bottom will have the
3959 /// correct dimensions:
3960 /// Sumw2 just makes sure the errors will be computed properly
3961 /// when we form sums and ratios below.
3962 
3965  TH1 *h1 = this;
3966  TString name = TString::Format("Asymmetry_%s-%s",h1->GetName(),h2->GetName() );
3967  TH1 *asym = (TH1*)Clone(name);
3968 
3969  // set also the title
3970  TString title = TString::Format("(%s - %s)/(%s+%s)",h1->GetName(),h2->GetName(),h1->GetName(),h2->GetName() );
3971  asym->SetTitle(title);
3972 
3973  asym->Sumw2();
3974  Bool_t addStatus = TH1::AddDirectoryStatus();
3976  TH1 *top = (TH1*)asym->Clone();
3977  TH1 *bottom = (TH1*)asym->Clone();
3978  TH1::AddDirectory(addStatus);
3979 
3980  // form the top and bottom of the asymmetry, and then divide:
3981  top->Add(h1,h2,1,-c2);
3982  bottom->Add(h1,h2,1,c2);
3983  asym->Divide(top,bottom);
3984 
3985  Int_t xmax = asym->GetNbinsX();
3986  Int_t ymax = asym->GetNbinsY();
3987  Int_t zmax = asym->GetNbinsZ();
3988 
3989  if (h1->fBuffer) h1->BufferEmpty(1);
3990  if (h2->fBuffer) h2->BufferEmpty(1);
3991  if (bottom->fBuffer) bottom->BufferEmpty(1);
3992 
3993  // now loop over bins to calculate the correct errors
3994  // the reason this error calculation looks complex is because of c2
3995  for(Int_t i=1; i<= xmax; i++){
3996  for(Int_t j=1; j<= ymax; j++){
3997  for(Int_t k=1; k<= zmax; k++){
3998  Int_t bin = GetBin(i, j, k);
3999  // here some bin contents are written into variables to make the error
4000  // calculation a little more legible:
4001  Double_t a = h1->RetrieveBinContent(bin);
4002  Double_t b = h2->RetrieveBinContent(bin);
4003  Double_t bot = bottom->RetrieveBinContent(bin);
4004 
4005  // make sure there are some events, if not, then the errors are set = 0
4006  // automatically.
4007  //if(bot < 1){} was changed to the next line from recommendation of Jason Seely (28 Nov 2005)
4008  if(bot < 1e-6){}
4009  else{
4010  // computation of errors by Christos Leonidopoulos
4011  Double_t dasq = h1->GetBinErrorSqUnchecked(bin);
4012  Double_t dbsq = h2->GetBinErrorSqUnchecked(bin);
4013  Double_t error = 2*TMath::Sqrt(a*a*c2*c2*dbsq + c2*c2*b*b*dasq+a*a*b*b*dc2*dc2)/(bot*bot);
4014  asym->SetBinError(i,j,k,error);
4015  }
4016  }
4017  }
4018  }
4019  delete top;
4020  delete bottom;
4021 
4022  return asym;
4023 }
4024 
4025 
4026 ////////////////////////////////////////////////////////////////////////////////
4027 /// static function
4028 /// return the default buffer size for automatic histograms
4029 /// the parameter fgBufferSize may be changed via SetDefaultBufferSize
4030 
4033  return fgBufferSize;
4034 }
4035 
4036 
4037 ////////////////////////////////////////////////////////////////////////////////
4038 /// return kTRUE if TH1::Sumw2 must be called when creating new histograms.
4039 /// see TH1::SetDefaultSumw2.
4040 
4043  return fgDefaultSumw2;
4044 }
4045 
4046 
4047 ////////////////////////////////////////////////////////////////////////////////
4048 /// return the current number of entries
4049 
4050 Double_t TH1::GetEntries() const
4052  if (fBuffer) {
4053  Int_t nentries = (Int_t) fBuffer[0];
4054  if (nentries > 0) return nentries;
4055  }
4056 
4057  return fEntries;
4058 }
4059 
4060 
4061 ////////////////////////////////////////////////////////////////////////////////
4062 /// number of effective entries of the histogram,
4063 /// neff = (Sum of weights )^2 / (Sum of weight^2 )
4064 /// In case of an unweighted histogram this number is equivalent to the
4065 /// number of entries of the histogram.
4066 /// For a weighted histogram, this number corresponds to the hypotetical number of unweighted entries
4067 /// a histogram would need to have the same statistical power as this weighted histogram.
4068 /// Note: The underflow/overflow are included if one has set the TH1::StatOverFlows flag
4069 /// and if the statistics has been computed at filling time.
4070 /// If a range is set in the histogram the number is computed from the given range.
4071 
4074  Stat_t s[kNstat];
4075  this->GetStats(s);// s[1] sum of squares of weights, s[0] sum of weights
4076  return (s[1] ? s[0]*s[0]/s[1] : TMath::Abs(s[0]) );
4077 }
4078 
4079 
4080 ////////////////////////////////////////////////////////////////////////////////
4081 /// Redefines TObject::GetObjectInfo.
4082 /// Displays the histogram info (bin number, contents, integral up to bin
4083 /// corresponding to cursor position px,py
4084 
4085 char *TH1::GetObjectInfo(Int_t px, Int_t py) const
4087  return ((TH1*)this)->GetPainter()->GetObjectInfo(px,py);
4088 }
4089 
4090 
4091 ////////////////////////////////////////////////////////////////////////////////
4092 /// return pointer to painter
4093 /// if painter does not exist, it is created
4094 
4097  if (!fPainter) {
4098  TString opt = option;
4099  opt.ToLower();
4100  if (opt.Contains("gl") || gStyle->GetCanvasPreferGL()) {
4101  //try to create TGLHistPainter
4102  TPluginHandler *handler = gROOT->GetPluginManager()->FindHandler("TGLHistPainter");
4103 
4104  if (handler && handler->LoadPlugin() != -1)
4105  fPainter = reinterpret_cast<TVirtualHistPainter *>(handler->ExecPlugin(1, this));
4106  }
4107  }
4108 
4110 
4111  return fPainter;
4112 }
4113 
4114 
4115 ////////////////////////////////////////////////////////////////////////////////
4116 /// Compute Quantiles for this histogram
4117 /// Quantile x_q of a probability distribution Function F is defined as
4118 ///
4119 /// F(x_q) = q with 0 <= q <= 1.
4120 ///
4121 /// For instance the median x_0.5 of a distribution is defined as that value
4122 /// of the random variable for which the distribution function equals 0.5:
4123 ///
4124 /// F(x_0.5) = Probability(x < x_0.5) = 0.5
4125 ///
4126 /// code from Eddy Offermann, Renaissance
4127 ///
4128 /// \param[in] nprobSum maximum size of array q and size of array probSum (if given)
4129 /// \param[in] probSum array of positions where quantiles will be computed.
4130 /// - if probSum is null, probSum will be computed internally and will
4131 /// have a size = number of bins + 1 in h. it will correspond to the
4132 /// quantiles calculated at the lowest edge of the histogram (quantile=0) and
4133 /// all the upper edges of the bins.
4134 /// - if probSum is not null, it is assumed to contain at least nprobSum values.
4135 /// \param[out] q array q filled with nq quantiles
4136 /// \return value nq (<=nprobSum) with the number of quantiles computed
4137 ///
4138 /// Note that the Integral of the histogram is automatically recomputed
4139 /// if the number of entries is different of the number of entries when
4140 /// the integral was computed last time. In case you do not use the Fill
4141 /// functions to fill your histogram, but SetBinContent, you must call
4142 /// TH1::ComputeIntegral before calling this function.
4143 ///
4144 /// Getting quantiles q from two histograms and storing results in a TGraph,
4145 /// a so-called QQ-plot
4146 /// ~~~{.cpp}
4147 /// TGraph *gr = new TGraph(nprob);
4148 /// h1->GetQuantiles(nprob,gr->GetX());
4149 /// h2->GetQuantiles(nprob,gr->GetY());
4150 /// gr->Draw("alp");
4151 /// ~~~
4152 ///
4153 /// Example:
4154 /// ~~~{cpp}
4155 /// void quantiles() {
4156 /// // demo for quantiles
4157 /// const Int_t nq = 20;
4158 /// TH1F *h = new TH1F("h","demo quantiles",100,-3,3);
4159 /// h->FillRandom("gaus",5000);
4160 ///
4161 /// Double_t xq[nq]; // position where to compute the quantiles in [0,1]
4162 /// Double_t yq[nq]; // array to contain the quantiles
4163 /// for (Int_t i=0;i<nq;i++) xq[i] = Float_t(i+1)/nq;
4164 /// h->GetQuantiles(nq,yq,xq);
4165 ///
4166 /// //show the original histogram in the top pad
4167 /// TCanvas *c1 = new TCanvas("c1","demo quantiles",10,10,700,900);
4168 /// c1->Divide(1,2);
4169 /// c1->cd(1);
4170 /// h->Draw();
4171 ///
4172 /// // show the quantiles in the bottom pad
4173 /// c1->cd(2);
4174 /// gPad->SetGrid();
4175 /// TGraph *gr = new TGraph(nq,xq,yq);
4176 /// gr->SetMarkerStyle(21);
4177 /// gr->Draw("alp");
4178 /// }
4179 /// ~~~
4180 
4181 Int_t TH1::GetQuantiles(Int_t nprobSum, Double_t *q, const Double_t *probSum)
4183  if (GetDimension() > 1) {
4184  Error("GetQuantiles","Only available for 1-d histograms");
4185  return 0;
4186  }
4187 
4188  const Int_t nbins = GetXaxis()->GetNbins();
4189  if (!fIntegral) ComputeIntegral();
4190  if (fIntegral[nbins+1] != fEntries) ComputeIntegral();
4191 
4192  Int_t i, ibin;
4193  Double_t *prob = (Double_t*)probSum;
4194  Int_t nq = nprobSum;
4195  if (probSum == 0) {
4196  nq = nbins+1;
4197  prob = new Double_t[nq];
4198  prob[0] = 0;
4199  for (i=1;i<nq;i++) {
4200  prob[i] = fIntegral[i]/fIntegral[nbins];
4201  }
4202  }
4203 
4204  for (i = 0; i < nq; i++) {
4205  ibin = TMath::BinarySearch(nbins,fIntegral,prob[i]);
4206  while (ibin < nbins-1 && fIntegral[ibin+1] == prob[i]) {
4207  if (fIntegral[ibin+2] == prob[i]) ibin++;
4208  else break;
4209  }
4210  q[i] = GetBinLowEdge(ibin+1);
4211  const Double_t dint = fIntegral[ibin+1]-fIntegral[ibin];
4212  if (dint > 0) q[i] += GetBinWidth(ibin+1)*(prob[i]-fIntegral[ibin])/dint;
4213  }
4214 
4215  if (!probSum) delete [] prob;
4216  return nq;
4217 }
4218 
4219 
4220 ////////////////////////////////////////////////////////////////////////////////
4221 /// Decode string choptin and fill fitOption structure.
4222 
4223 Int_t TH1::FitOptionsMake(Option_t *choptin, Foption_t &fitOption)
4226  return 1;
4227 }
4228 
4229 
4230 ////////////////////////////////////////////////////////////////////////////////
4231 /// Compute Initial values of parameters for a gaussian.
4232 
4233 void H1InitGaus()
4235  Double_t allcha, sumx, sumx2, x, val, stddev, mean;
4236  Int_t bin;
4237  const Double_t sqrtpi = 2.506628;
4238 
4239  // - Compute mean value and StdDev of the histogram in the given range
4241  TH1 *curHist = (TH1*)hFitter->GetObjectFit();
4242  Int_t hxfirst = hFitter->GetXfirst();
4243  Int_t hxlast = hFitter->GetXlast();
4244  Double_t valmax = curHist->GetBinContent(hxfirst);
4245  Double_t binwidx = curHist->GetBinWidth(hxfirst);
4246  allcha = sumx = sumx2 = 0;
4247  for (bin=hxfirst;bin<=hxlast;bin++) {
4248  x = curHist->GetBinCenter(bin);
4249  val = TMath::Abs(curHist->GetBinContent(bin));
4250  if (val > valmax) valmax = val;
4251  sumx += val*x;
4252  sumx2 += val*x*x;
4253  allcha += val;
4254  }
4255  if (allcha == 0) return;
4256  mean = sumx/allcha;
4257  stddev = sumx2/allcha - mean*mean;
4258  if (stddev > 0) stddev = TMath::Sqrt(stddev);
4259  else stddev = 0;
4260  if (stddev == 0) stddev = binwidx*(hxlast-hxfirst+1)/4;
4261  //if the distribution is really gaussian, the best approximation
4262  //is binwidx*allcha/(sqrtpi*stddev)
4263  //However, in case of non-gaussian tails, this underestimates
4264  //the normalisation constant. In this case the maximum value
4265  //is a better approximation.
4266  //We take the average of both quantities
4267  Double_t constant = 0.5*(valmax+binwidx*allcha/(sqrtpi*stddev));
4268 
4269  //In case the mean value is outside the histo limits and
4270  //the StdDev is bigger than the range, we take
4271  // mean = center of bins
4272  // stddev = half range
4273  Double_t xmin = curHist->GetXaxis()->GetXmin();
4274  Double_t xmax = curHist->GetXaxis()->GetXmax();
4275  if ((mean < xmin || mean > xmax) && stddev > (xmax-xmin)) {
4276  mean = 0.5*(xmax+xmin);
4277  stddev = 0.5*(xmax-xmin);
4278  }
4279  TF1 *f1 = (TF1*)hFitter->GetUserFunc();
4280  f1->SetParameter(0,constant);
4281  f1->SetParameter(1,mean);
4282  f1->SetParameter(2,stddev);
4283  f1->SetParLimits(2,0,10*stddev);
4284 }
4285 
4286 
4287 ////////////////////////////////////////////////////////////////////////////////
4288 /// Compute Initial values of parameters for an exponential.
4289 
4290 void H1InitExpo()
4292  Double_t constant, slope;
4293  Int_t ifail;
4295  Int_t hxfirst = hFitter->GetXfirst();
4296  Int_t hxlast = hFitter->GetXlast();
4297  Int_t nchanx = hxlast - hxfirst + 1;
4298 
4299  H1LeastSquareLinearFit(-nchanx, constant, slope, ifail);
4300 
4301  TF1 *f1 = (TF1*)hFitter->GetUserFunc();
4302  f1->SetParameter(0,constant);
4303  f1->SetParameter(1,slope);
4304 
4305 }
4306 
4307 
4308 ////////////////////////////////////////////////////////////////////////////////
4309 /// Compute Initial values of parameters for a polynom.
4310 
4311 void H1InitPolynom()
4313  Double_t fitpar[25];
4314 
4316  TF1 *f1 = (TF1*)hFitter->GetUserFunc();
4317  Int_t hxfirst = hFitter->GetXfirst();
4318  Int_t hxlast = hFitter->GetXlast();
4319  Int_t nchanx = hxlast - hxfirst + 1;
4320  Int_t npar = f1->GetNpar();
4321 
4322  if (nchanx <=1 || npar == 1) {
4323  TH1 *curHist = (TH1*)hFitter->GetObjectFit();
4324  fitpar[0] = curHist->GetSumOfWeights()/Double_t(nchanx);
4325  } else {
4326  H1LeastSquareFit( nchanx, npar, fitpar);
4327  }
4328  for (Int_t i=0;i<npar;i++) f1->SetParameter(i, fitpar[i]);
4329 }
4330 
4331 
4332 ////////////////////////////////////////////////////////////////////////////////
4333 /// Least squares lpolynomial fitting without weights.
4334 ///
4335 /// \param[in] n number of points to fit
4336 /// \param[in] m number of parameters
4337 /// \param[in] a array of parameters
4338 ///
4339 /// based on CERNLIB routine LSQ: Translated to C++ by Rene Brun
4340 /// (E.Keil. revised by B.Schorr, 23.10.1981.)
4341 
4344  const Double_t zero = 0.;
4345  const Double_t one = 1.;
4346  const Int_t idim = 20;
4347 
4348  Double_t b[400] /* was [20][20] */;
4349  Int_t i, k, l, ifail;
4350  Double_t power;
4351  Double_t da[20], xk, yk;
4352 
4353  if (m <= 2) {
4354  H1LeastSquareLinearFit(n, a[0], a[1], ifail);
4355  return;
4356  }
4357  if (m > idim || m > n) return;
4358  b[0] = Double_t(n);
4359  da[0] = zero;
4360  for (l = 2; l <= m; ++l) {
4361  b[l-1] = zero;
4362  b[m + l*20 - 21] = zero;
4363  da[l-1] = zero;
4364  }
4366  TH1 *curHist = (TH1*)hFitter->GetObjectFit();
4367  Int_t hxfirst = hFitter->GetXfirst();
4368  Int_t hxlast = hFitter->GetXlast();
4369  for (k = hxfirst; k <= hxlast; ++k) {
4370  xk = curHist->GetBinCenter(k);
4371  yk = curHist->GetBinContent(k);
4372  power = one;
4373  da[0] += yk;
4374  for (l = 2; l <= m; ++l) {
4375  power *= xk;
4376  b[l-1] += power;
4377  da[l-1] += power*yk;
4378  }
4379  for (l = 2; l <= m; ++l) {
4380  power *= xk;
4381  b[m + l*20 - 21] += power;
4382  }
4383  }
4384  for (i = 3; i <= m; ++i) {
4385  for (k = i; k <= m; ++k) {
4386  b[k - 1 + (i-1)*20 - 21] = b[k + (i-2)*20 - 21];
4387  }
4388  }
4389  H1LeastSquareSeqnd(m, b, idim, ifail, 1, da);
4390 
4391  for (i=0; i<m; ++i) a[i] = da[i];
4392 
4393 }
4394 
4395 
4396 ////////////////////////////////////////////////////////////////////////////////
4397 /// Least square linear fit without weights.
4398 ///
4399 /// extracted from CERNLIB LLSQ: Translated to C++ by Rene Brun
4400 /// (added to LSQ by B. Schorr, 15.02.1982.)
4401 
4402 void H1LeastSquareLinearFit(Int_t ndata, Double_t &a0, Double_t &a1, Int_t &ifail)
4404  Double_t xbar, ybar, x2bar;
4405  Int_t i, n;
4406  Double_t xybar;
4407  Double_t fn, xk, yk;
4408  Double_t det;
4409 
4410  n = TMath::Abs(ndata);
4411  ifail = -2;
4412  xbar = ybar = x2bar = xybar = 0;
4414  TH1 *curHist = (TH1*)hFitter->GetObjectFit();
4415  Int_t hxfirst = hFitter->GetXfirst();
4416  Int_t hxlast = hFitter->GetXlast();
4417  for (i = hxfirst; i <= hxlast; ++i) {
4418  xk = curHist->GetBinCenter(i);
4419  yk = curHist->GetBinContent(i);
4420  if (ndata < 0) {
4421  if (yk <= 0) yk = 1e-9;
4422  yk = TMath::Log(yk);
4423  }
4424  xbar += xk;
4425  ybar += yk;
4426  x2bar += xk*xk;
4427  xybar += xk*yk;
4428  }
4429  fn = Double_t(n);
4430  det = fn*x2bar - xbar*xbar;
4431  ifail = -1;
4432  if (det <= 0) {
4433  a0 = ybar/fn;
4434  a1 = 0;
4435  return;
4436  }
4437  ifail = 0;
4438  a0 = (x2bar*ybar - xbar*xybar) / det;
4439  a1 = (fn*xybar - xbar*ybar) / det;
4440 
4441 }
4442 
4443 
4444 ////////////////////////////////////////////////////////////////////////////////
4445 /// Extracted from CERN Program library routine DSEQN.
4446 ///
4447 /// : Translated to C++ by Rene Brun
4448 
4449 void H1LeastSquareSeqnd(Int_t n, Double_t *a, Int_t idim, Int_t &ifail, Int_t k, Double_t *b)
4451  Int_t a_dim1, a_offset, b_dim1, b_offset;
4452  Int_t nmjp1, i, j, l;
4453  Int_t im1, jp1, nm1, nmi;
4454  Double_t s1, s21, s22;
4455  const Double_t one = 1.;
4456 
4457  /* Parameter adjustments */
4458  b_dim1 = idim;
4459  b_offset = b_dim1 + 1;
4460  b -= b_offset;
4461  a_dim1 = idim;
4462  a_offset = a_dim1 + 1;
4463  a -= a_offset;
4464 
4465  if (idim < n) return;
4466 
4467  ifail = 0;
4468  for (j = 1; j <= n; ++j) {
4469  if (a[j + j*a_dim1] <= 0) { ifail = -1; return; }
4470  a[j + j*a_dim1] = one / a[j + j*a_dim1];
4471  if (j == n) continue;
4472  jp1 = j + 1;
4473  for (l = jp1; l <= n; ++l) {
4474  a[j + l*a_dim1] = a[j + j*a_dim1] * a[l + j*a_dim1];
4475  s1 = -a[l + (j+1)*a_dim1];
4476  for (i = 1; i <= j; ++i) { s1 = a[l + i*a_dim1] * a[i + (j+1)*a_dim1] + s1; }
4477  a[l + (j+1)*a_dim1] = -s1;
4478  }
4479  }
4480  if (k <= 0) return;
4481 
4482  for (l = 1; l <= k; ++l) {
4483  b[l*b_dim1 + 1] = a[a_dim1 + 1]*b[l*b_dim1 + 1];
4484  }
4485  if (n == 1) return;
4486  for (l = 1; l <= k; ++l) {
4487  for (i = 2; i <= n; ++i) {
4488  im1 = i - 1;
4489  s21 = -b[i + l*b_dim1];
4490  for (j = 1; j <= im1; ++j) {
4491  s21 = a[i + j*a_dim1]*b[j + l*b_dim1] + s21;
4492  }
4493  b[i + l*b_dim1] = -a[i + i*a_dim1]*s21;
4494  }
4495  nm1 = n - 1;
4496  for (i = 1; i <= nm1; ++i) {
4497  nmi = n - i;
4498  s22 = -b[nmi + l*b_dim1];
4499  for (j = 1; j <= i; ++j) {
4500  nmjp1 = n - j + 1;
4501  s22 = a[nmi + nmjp1*a_dim1]*b[nmjp1 + l*b_dim1] + s22;
4502  }
4503  b[nmi + l*b_dim1] = -s22;
4504  }
4505  }
4506 }
4507 
4508 
4509 ////////////////////////////////////////////////////////////////////////////////
4510 /// Return Global bin number corresponding to binx,y,z.
4511 ///
4512 /// 2-D and 3-D histograms are represented with a one dimensional
4513 /// structure.
4514 /// This has the advantage that all existing functions, such as
4515 /// GetBinContent, GetBinError, GetBinFunction work for all dimensions.
4516 ///
4517 /// In case of a TH1x, returns binx directly.
4518 /// see TH1::GetBinXYZ for the inverse transformation.
4519 ///
4520 /// Convention for numbering bins
4521 ///
4522 /// For all histogram types: nbins, xlow, xup
4523 /// bin = 0; underflow bin
4524 /// bin = 1; first bin with low-edge xlow INCLUDED
4525 /// bin = nbins; last bin with upper-edge xup EXCLUDED
4526 /// bin = nbins+1; overflow bin
4527 /// In case of 2-D or 3-D histograms, a "global bin" number is defined.
4528 /// For example, assuming a 3-D histogram with binx,biny,binz, the function
4529 ///
4530 /// Int_t bin = h->GetBin(binx,biny,binz);
4531 /// returns a global/linearized bin number. This global bin is useful
4532 /// to access the bin information independently of the dimension.
4533 
4534 Int_t TH1::GetBin(Int_t binx, Int_t, Int_t) const
4536  Int_t ofx = fXaxis.GetNbins() + 1; // overflow bin
4537  if (binx < 0) binx = 0;
4538  if (binx > ofx) binx = ofx;
4539 
4540  return binx;
4541 }
4542 
4543 
4544 ////////////////////////////////////////////////////////////////////////////////
4545 /// return binx, biny, binz corresponding to the global bin number globalbin
4546 /// see TH1::GetBin function above
4547 
4548 void TH1::GetBinXYZ(Int_t binglobal, Int_t &binx, Int_t &biny, Int_t &binz) const
4550  Int_t nx = fXaxis.GetNbins()+2;
4551  Int_t ny = fYaxis.GetNbins()+2;
4552 
4553  if (GetDimension() == 1) {
4554  binx = binglobal%nx;
4555  biny = 0;
4556  binz = 0;
4557  return;
4558  }
4559  if (GetDimension() == 2) {
4560  binx = binglobal%nx;
4561  biny = ((binglobal-binx)/nx)%ny;
4562  binz = 0;
4563  return;
4564  }
4565  if (GetDimension() == 3) {
4566  binx = binglobal%nx;
4567  biny = ((binglobal-binx)/nx)%ny;
4568  binz = ((binglobal-binx)/nx -biny)/ny;
4569  }
4570 }
4571 
4572 
4573 ////////////////////////////////////////////////////////////////////////////////
4574 /// return a random number distributed according the histogram bin contents.
4575 /// This function checks if the bins integral exists. If not, the integral
4576 /// is evaluated, normalized to one.
4577 /// The integral is automatically recomputed if the number of entries
4578 /// is not the same then when the integral was computed.
4579 /// NB Only valid for 1-d histograms. Use GetRandom2 or 3 otherwise.
4580 /// If the histogram has a bin with negative content a NaN is returned
4581 
4582 Double_t TH1::GetRandom() const
4584  if (fDimension > 1) {
4585  Error("GetRandom","Function only valid for 1-d histograms");
4586  return 0;
4587  }
4588  Int_t nbinsx = GetNbinsX();
4589  Double_t integral = 0;
4590  // compute integral checking that all bins have positive content (see ROOT-5894)
4591  if (fIntegral) {
4592  if (fIntegral[nbinsx+1] != fEntries) integral = ((TH1*)this)->ComputeIntegral(true);
4593  else integral = fIntegral[nbinsx];
4594  } else {
4595  integral = ((TH1*)this)->ComputeIntegral(true);
4596  }
4597  if (integral == 0) return 0;
4598  // return a NaN in case some bins have negative content
4599  if (integral == TMath::QuietNaN() ) return TMath::QuietNaN();
4600 
4601  Double_t r1 = gRandom->Rndm();
4602  Int_t ibin = TMath::BinarySearch(nbinsx,fIntegral,r1);
4603  Double_t x = GetBinLowEdge(ibin+1);
4604  if (r1 > fIntegral[ibin]) x +=
4605  GetBinWidth(ibin+1)*(r1-fIntegral[ibin])/(fIntegral[ibin+1] - fIntegral[ibin]);
4606  return x;
4607 }
4608 
4609 
4610 ////////////////////////////////////////////////////////////////////////////////
4611 /// Return content of bin number bin.
4612 ///
4613 /// Implemented in TH1C,S,F,D
4614 ///
4615 /// Convention for numbering bins
4616 ///
4617 /// For all histogram types: nbins, xlow, xup
4618 /// bin = 0; underflow bin
4619 /// bin = 1; first bin with low-edge xlow INCLUDED
4620 /// bin = nbins; last bin with upper-edge xup EXCLUDED
4621 /// bin = nbins+1; overflow bin
4622 /// In case of 2-D or 3-D histograms, a "global bin" number is defined.
4623 /// For example, assuming a 3-D histogram with binx,biny,binz, the function
4624 /// Int_t bin = h->GetBin(binx,biny,binz);
4625 /// returns a global/linearized bin number. This global bin is useful
4626 /// to access the bin information independently of the dimension.
4627 
4630  if (fBuffer) const_cast<TH1*>(this)->BufferEmpty();
4631  if (bin < 0) bin = 0;
4632  if (bin >= fNcells) bin = fNcells-1;
4633 
4634  return RetrieveBinContent(bin);
4635 }
4636 
4637 
4638 ////////////////////////////////////////////////////////////////////////////////
4639 /// compute first binx in the range [firstx,lastx] for which
4640 /// diff = abs(bin_content-c) <= maxdiff
4641 /// In case several bins in the specified range with diff=0 are found
4642 /// the first bin found is returned in binx.
4643 /// In case several bins in the specified range satisfy diff <=maxdiff
4644 /// the bin with the smallest difference is returned in binx.
4645 /// In all cases the function returns the smallest difference.
4646 ///
4647 /// NOTE1: if firstx <= 0, firstx is set to bin 1
4648 /// if (lastx < firstx then firstx is set to the number of bins
4649 /// ie if firstx=0 and lastx=0 (default) the search is on all bins.
4650 /// NOTE2: if maxdiff=0 (default), the first bin with content=c is returned.
4651 
4652 Double_t TH1::GetBinWithContent(Double_t c, Int_t &binx, Int_t firstx, Int_t lastx,Double_t maxdiff) const
4654  if (fDimension > 1) {
4655  binx = 0;
4656  Error("GetBinWithContent","function is only valid for 1-D histograms");
4657  return 0;
4658  }
4659 
4660  if (fBuffer) ((TH1*)this)->BufferEmpty();
4661 
4662  if (firstx <= 0) firstx = 1;
4663  if (lastx < firstx) lastx = fXaxis.GetNbins();
4664  Int_t binminx = 0;
4665  Double_t diff, curmax = 1.e240;
4666  for (Int_t i=firstx;i<=lastx;i++) {
4667  diff = TMath::Abs(RetrieveBinContent(i)-c);
4668  if (diff <= 0) {binx = i; return diff;}
4669  if (diff < curmax && diff <= maxdiff) {curmax = diff, binminx=i;}
4670  }
4671  binx = binminx;
4672  return curmax;
4673 }
4674 
4675 
4676 ////////////////////////////////////////////////////////////////////////////////
4677 /// Given a point x, approximates the value via linear interpolation
4678 /// based on the two nearest bin centers
4679 /// Andy Mastbaum 10/21/08
4680 
4683  if (fBuffer) ((TH1*)this)->BufferEmpty();
4684 
4685  Int_t xbin = FindBin(x);
4686  Double_t x0,x1,y0,y1;
4687 
4688  if(x<=GetBinCenter(1)) {
4689  return RetrieveBinContent(1);
4690  } else if(x>=GetBinCenter(GetNbinsX())) {
4691  return RetrieveBinContent(GetNbinsX());
4692  } else {
4693  if(x<=GetBinCenter(xbin)) {
4694  y0 = RetrieveBinContent(xbin-1);
4695  x0 = GetBinCenter(xbin-1);
4696  y1 = RetrieveBinContent(xbin);
4697  x1 = GetBinCenter(xbin);
4698  } else {
4699  y0 = RetrieveBinContent(xbin);
4700  x0 = GetBinCenter(xbin);
4701  y1 = RetrieveBinContent(xbin+1);
4702  x1 = GetBinCenter(xbin+1);
4703  }
4704  return y0 + (x-x0)*((y1-y0)/(x1-x0));
4705  }
4706 }
4707 
4708 
4709 ////////////////////////////////////////////////////////////////////////////////
4710 
4713  //Not yet implemented
4714  Error("Interpolate","This function must be called with 1 argument for a TH1");
4715  return 0;
4716 }
4717 
4718 
4719 ////////////////////////////////////////////////////////////////////////////////
4720 
4723  //Not yet implemented
4724  Error("Interpolate","This function must be called with 1 argument for a TH1");
4725  return 0;
4726 }
4727 
4728 
4729 ////////////////////////////////////////////////////////////////////////////////
4730 
4731 Bool_t TH1::IsBinOverflow(Int_t bin) const
4733  // Return true if the bin is overflow.
4734  Int_t binx, biny, binz;
4735  GetBinXYZ(bin, binx, biny, binz);
4736 
4737  if ( fDimension == 1 )
4738  return binx >= GetNbinsX() + 1;
4739  else if ( fDimension == 2 )
4740  return (binx >= GetNbinsX() + 1) ||
4741  (biny >= GetNbinsY() + 1);
4742  else if ( fDimension == 3 )
4743  return (binx >= GetNbinsX() + 1) ||
4744  (biny >= GetNbinsY() + 1) ||
4745  (binz >= GetNbinsZ() + 1);
4746  else
4747  return 0;
4748 }
4749 
4750 
4751 ////////////////////////////////////////////////////////////////////////////////
4752 
4753 Bool_t TH1::IsBinUnderflow(Int_t bin) const
4755  // Return true if the bin is overflow.
4756  Int_t binx, biny, binz;
4757  GetBinXYZ(bin, binx, biny, binz);
4758 
4759  if ( fDimension == 1 )
4760  return (binx <= 0);
4761  else if ( fDimension == 2 )
4762  return (binx <= 0 || biny <= 0);
4763  else if ( fDimension == 3 )
4764  return (binx <= 0 || biny <= 0 || binz <= 0);
4765  else
4766  return 0;
4767 }
4768 
4769 
4770 ////////////////////////////////////////////////////////////////////////////////
4771 /// Reduce the number of bins for the axis passed in the option to the number of bins having a label.
4772 /// The method will remove only the extra bins existing after the last "labeled" bin.
4773 /// Note that if there are "un-labeled" bins present between "labeled" bins they will not be removed
4774 
4775 void TH1::LabelsDeflate(Option_t *ax)
4777  Int_t iaxis = AxisChoice(ax);
4778  TAxis *axis = 0;
4779  if (iaxis == 1) axis = GetXaxis();
4780  if (iaxis == 2) axis = GetYaxis();
4781  if (iaxis == 3) axis = GetZaxis();
4782  if (!axis) {
4783  Error("LabelsDeflate","Invalid axis option %s",ax);
4784  return;
4785  }
4786  if (!axis->GetLabels()) return;
4787 
4788  // find bin with last labels
4789  // bin number is object ID in list of labels
4790  // therefore max bin number is number of bins of the deflated histograms
4791  TIter next(axis->GetLabels());
4792  TObject *obj;
4793  Int_t nbins = 0;
4794  while ((obj = next())) {
4795  Int_t ibin = obj->GetUniqueID();
4796  if (ibin > nbins) nbins = ibin;
4797  }
4798  if (nbins < 1) nbins = 1;
4799  TH1 *hold = (TH1*)IsA()->New();
4800  R__ASSERT(hold);
4801  hold->SetDirectory(0);
4802  Copy(*hold);
4803 
4804  Bool_t timedisp = axis->GetTimeDisplay();
4805  Double_t xmin = axis->GetXmin();
4806  Double_t xmax = axis->GetBinUpEdge(nbins);
4807  if (xmax <= xmin) xmax = xmin +nbins;
4808  axis->SetRange(0,0);
4809  axis->Set(nbins,xmin,xmax);
4810  SetBinsLength(-1); // reset the number of cells
4811  Int_t errors = fSumw2.fN;
4812  if (errors) fSumw2.Set(fNcells);
4813  axis->SetTimeDisplay(timedisp);
4814  // reset histogram content
4815  Reset("ICE");
4816 
4817  //now loop on all bins and refill
4818  // NOTE that if the bins without labels have content
4819  // it will be put in the underflow/overflow.
4820  // For this reason we use AddBinContent method
4821  Double_t oldEntries = fEntries;
4822  Int_t bin,binx,biny,binz;
4823  for (bin=0; bin < hold->fNcells; ++bin) {
4824  hold->GetBinXYZ(bin,binx,biny,binz);
4825  Int_t ibin = GetBin(binx,biny,binz);
4826  Double_t cu = hold->RetrieveBinContent(bin);
4827  AddBinContent(ibin,cu);
4828  if (errors) {
4829  fSumw2.fArray[ibin] += hold->fSumw2.fArray[bin];
4830  }
4831  }
4832  fEntries = oldEntries;
4833  delete hold;
4834 }
4835 
4836 
4837 ////////////////////////////////////////////////////////////////////////////////
4838 /// Double the number of bins for axis.
4839 /// Refill histogram
4840 /// This function is called by TAxis::FindBin(const char *label)
4841 
4842 void TH1::LabelsInflate(Option_t *ax)
4844  Int_t iaxis = AxisChoice(ax);
4845  TAxis *axis = 0;
4846  if (iaxis == 1) axis = GetXaxis();
4847  if (iaxis == 2) axis = GetYaxis();
4848  if (iaxis == 3) axis = GetZaxis();
4849  if (!axis) return;
4850 
4851  TH1 *hold = (TH1*)IsA()->New();;
4852  hold->SetDirectory(0);
4853  Copy(*hold);
4854 
4855  Bool_t timedisp = axis->GetTimeDisplay();
4856  Int_t nbins = axis->GetNbins();
4857  Double_t xmin = axis->GetXmin();
4858  Double_t xmax = axis->GetXmax();
4859  xmax = xmin + 2*(xmax-xmin);
4860  axis->SetRange(0,0);
4861  // double the bins and recompute ncells
4862  axis->Set(2*nbins,xmin,xmax);
4863  SetBinsLength(-1);
4864  Int_t errors = fSumw2.fN;
4865  if (errors) fSumw2.Set(fNcells);
4866  axis->SetTimeDisplay(timedisp);
4867 
4868  Reset("ICE"); // reset content and error
4869 
4870  //now loop on all bins and refill
4871  Double_t oldEntries = fEntries;
4872  Int_t bin,ibin,binx,biny,binz;
4873  for (ibin =0; ibin < fNcells; ibin++) {
4874  GetBinXYZ(ibin,binx,biny,binz);
4875  bin = hold->GetBin(binx,biny,binz);
4876 
4877  // underflow and overflow will be cleaned up because their meaning has been altered
4878  if (IsBinUnderflow(bin) || IsBinOverflow(bin)) UpdateBinContent(ibin, 0.0);
4879  else {
4880  AddBinContent(ibin, hold->RetrieveBinContent(bin));
4881  if (errors) fSumw2.fArray[ibin] += hold->fSumw2.fArray[bin];
4882  }
4883  }
4884  fEntries = oldEntries;
4885  delete hold;
4886 }
4887 
4888 
4889 ////////////////////////////////////////////////////////////////////////////////
4890 /// Set option(s) to draw axis with labels
4891 /// \param[in] option
4892 /// - "a" sort by alphabetic order
4893 /// - ">" sort by decreasing values
4894 /// - "<" sort by increasing values
4895 /// - "h" draw labels horizontal
4896 /// - "v" draw labels vertical
4897 /// - "u" draw labels up (end of label right adjusted)
4898 /// - "d" draw labels down (start of label left adjusted)
4899 
4900 void TH1::LabelsOption(Option_t *option, Option_t *ax)
4902  Int_t iaxis = AxisChoice(ax);
4903  TAxis *axis = 0;
4904  if (iaxis == 1) axis = GetXaxis();
4905  if (iaxis == 2) axis = GetYaxis();
4906  if (iaxis == 3) axis = GetZaxis();
4907  if (!axis) return;
4908  THashList *labels = axis->GetLabels();
4909  if (!labels) {
4910  Warning("LabelsOption","Cannot sort. No labels");
4911  return;
4912  }
4913  TString opt = option;
4914  opt.ToLower();
4915  if (opt.Contains("h")) {
4916  axis->SetBit(TAxis::kLabelsHori);
4919  axis->ResetBit(TAxis::kLabelsUp);
4920  }
4921  if (opt.Contains("v")) {
4922  axis->SetBit(TAxis::kLabelsVert);
4925  axis->ResetBit(TAxis::kLabelsUp);
4926  }
4927  if (opt.Contains("u")) {
4928  axis->SetBit(TAxis::kLabelsUp);
4932  }
4933  if (opt.Contains("d")) {
4934  axis->SetBit(TAxis::kLabelsDown);
4937  axis->ResetBit(TAxis::kLabelsUp);
4938  }
4939  Int_t sort = -1;
4940  if (opt.Contains("a")) sort = 0;
4941  if (opt.Contains(">")) sort = 1;
4942  if (opt.Contains("<")) sort = 2;
4943  if (sort < 0) return;
4944  if (sort > 0 && GetDimension() > 2) {
4945  Error("LabelsOption","Sorting by value not implemented for 3-D histograms");
4946  return;
4947  }
4948 
4949  Double_t entries = fEntries;
4950  Int_t n = TMath::Min(axis->GetNbins(), labels->GetSize());
4951  std::vector<Int_t> a(n+2);
4952 
4953  Int_t i,j,k;
4954  std::vector<Double_t> cont;
4955  std::vector<Double_t> errors;
4956  THashList *labold = new THashList(labels->GetSize(),1);
4957  TIter nextold(labels);
4958  TObject *obj;
4959  while ((obj=nextold())) {
4960  labold->Add(obj);
4961  }
4962  labels->Clear();
4963  if (sort > 0) {
4964  //---sort by values of bins
4965  if (GetDimension() == 1) {
4966  cont.resize(n);
4967  if (fSumw2.fN) errors.resize(n);
4968  for (i=1;i<=n;i++) {
4969  cont[i-1] = GetBinContent(i);
4970  if (!errors.empty()) errors[i-1] = GetBinError(i);
4971  }
4972  if (sort ==1) TMath::Sort(n,cont.data(),a.data(),kTRUE); //sort by decreasing values
4973  else TMath::Sort(n,cont.data(),a.data(),kFALSE); //sort by increasing values
4974  for (i=1;i<=n;i++) {
4975  SetBinContent(i,cont[a[i-1]]);
4976  if (!errors.empty()) SetBinError(i,errors[a[i-1]]);
4977  }
4978  for (i=1;i<=n;i++) {
4979  obj = labold->At(a[i-1]);
4980  labels->Add(obj);
4981  obj->SetUniqueID(i);
4982  }
4983  } else if (GetDimension()== 2) {
4984  std::vector<Double_t> pcont(n+2);
4985  Int_t nx = fXaxis.GetNbins();
4986  Int_t ny = fYaxis.GetNbins();
4987  cont.resize( (nx+2)*(ny+2));
4988  if (fSumw2.fN) errors.resize( (nx+2)*(ny+2));
4989  for (i=1;i<=nx;i++) {
4990  for (j=1;j<=ny;j++) {
4991  cont[i+nx*j] = GetBinContent(i,j);
4992  if (!errors.empty()) errors[i+nx*j] = GetBinError(i,j);
4993  if (axis == GetXaxis()) k = i;
4994  else k = j;
4995  pcont[k-1] += cont[i+nx*j];
4996  }
4997  }
4998  if (sort ==1) TMath::Sort(n,pcont.data(),a.data(),kTRUE); //sort by decreasing values
4999  else TMath::Sort(n,pcont.data(),a.data(),kFALSE); //sort by increasing values
5000  for (i=0;i<n;i++) {
5001  obj = labold->At(a[i]);
5002  labels->Add(obj);
5003  obj->SetUniqueID(i+1);
5004  }
5005  if (axis == GetXaxis()) {
5006  for (i=1;i<=n;i++) {
5007  for (j=1;j<=ny;j++) {
5008  SetBinContent(i,j,cont[a[i-1]+1+nx*j]);
5009  if (!errors.empty()) SetBinError(i,j,errors[a[i-1]+1+nx*j]);
5010  }
5011  }
5012  }
5013  else {
5014  // using y axis
5015  for (i=1;i<=nx;i++) {
5016  for (j=1;j<=n;j++) {
5017  SetBinContent(i,j,cont[i+nx*(a[j-1]+1)]);
5018  if (!errors.empty()) SetBinError(i,j,errors[i+nx*(a[j-1]+1)]);
5019  }
5020  }
5021  }
5022  } else {
5023  //to be implemented for 3d
5024  }
5025  } else {
5026  //---alphabetic sort
5027  const UInt_t kUsed = 1<<18;
5028  TObject *objk=0;
5029  a[0] = 0;
5030  a[n+1] = n+1;
5031  for (i=1;i<=n;i++) {
5032  const char *label = "zzzzzzzzzzzz";
5033  for (j=1;j<=n;j++) {
5034  obj = labold->At(j-1);
5035  if (!obj) continue;
5036  if (obj->TestBit(kUsed)) continue;
5037  //use strcasecmp for case non-sensitive sort (may be an option)
5038  if (strcmp(label,obj->GetName()) < 0) continue;
5039  objk = obj;
5040  a[i] = j;
5041  label = obj->GetName();
5042  }
5043  if (objk) {
5044  objk->SetUniqueID(i);
5045  labels->Add(objk);
5046  objk->SetBit(kUsed);
5047  }
5048  }
5049  for (i=1;i<=n;i++) {
5050  obj = labels->At(i-1);
5051  if (!obj) continue;
5052  obj->ResetBit(kUsed);
5053  }
5054 
5055  if (GetDimension() == 1) {
5056  cont.resize(n+2);
5057  if (fSumw2.fN) errors.resize(n+2);
5058  for (i=1;i<=n;i++) {
5059  cont[i] = GetBinContent(a[i]);
5060  if (!errors.empty()) errors[i] = GetBinError(a[i]);
5061  }
5062  for (i=1;i<=n;i++) {
5063  SetBinContent(i,cont[i]);
5064  if (!errors.empty()) SetBinError(i,errors[i]);
5065  }
5066  } else if (GetDimension()== 2) {
5067  Int_t nx = fXaxis.GetNbins()+2;
5068  Int_t ny = fYaxis.GetNbins()+2;
5069  cont.resize(nx*ny);
5070  if (fSumw2.fN) errors.resize(nx*ny);
5071  for (i=0;i<nx;i++) {
5072  for (j=0;j<ny;j++) {
5073  cont[i+nx*j] = GetBinContent(i,j);
5074  if (!errors.empty()) errors[i+nx*j] = GetBinError(i,j);
5075  }
5076  }
5077  if (axis == GetXaxis()) {
5078  for (i=1;i<=n;i++) {
5079  for (j=0;j<ny;j++) {
5080  SetBinContent(i,j,cont[a[i]+nx*j]);
5081  if (!errors.empty()) SetBinError(i,j,errors[a[i]+nx*j]);
5082  }
5083  }
5084  } else {
5085  for (i=0;i<nx;i++) {
5086  for (j=1;j<=n;j++) {
5087  SetBinContent(i,j,cont[i+nx*a[j]]);
5088  if (!errors.empty()) SetBinError(i,j,errors[i+nx*a[j]]);
5089  }
5090  }
5091  }
5092  } else {
5093  Int_t nx = fXaxis.GetNbins()+2;
5094  Int_t ny = fYaxis.GetNbins()+2;
5095  Int_t nz = fZaxis.GetNbins()+2;
5096  cont.resize(nx*ny*nz);
5097  if (fSumw2.fN) errors.resize(nx*ny*nz);
5098  for (i=0;i<nx;i++) {
5099  for (j=0;j<ny;j++) {
5100  for (k=0;k<nz;k++) {
5101  cont[i+nx*(j+ny*k)] = GetBinContent(i,j,k);
5102  if (!errors.empty()) errors[i+nx*(j+ny*k)] = GetBinError(i,j,k);
5103  }
5104  }
5105  }
5106  if (axis == GetXaxis()) {
5107  // labels on x axis
5108  for (i=1;i<=n;i++) {
5109  for (j=0;j<ny;j++) {
5110  for (k=0;k<nz;k++) {
5111  SetBinContent(i,j,k,cont[a[i]+nx*(j+ny*k)]);
5112  if (!errors.empty()) SetBinError(i,j,k,errors[a[i]+nx*(j+ny*k)]);
5113  }
5114  }
5115  }
5116  }
5117  else if (axis == GetYaxis()) {
5118  // labels on y axis
5119  for (i=0;i<nx;i++) {
5120  for (j=1;j<=n;j++) {
5121  for (k=0;k<nz;k++) {
5122  SetBinContent(i,j,k,cont[i+nx*(a[j]+ny*k)]);
5123  if (!errors.empty()) SetBinError(i,j,k,errors[i+nx*(a[j]+ny*k)]);
5124  }
5125  }
5126  }
5127  }
5128  else {
5129  // labels on z axis
5130  for (i=0;i<nx;i++) {
5131  for (j=0;j<ny;j++) {
5132  for (k=1;k<=n;k++) {
5133  SetBinContent(i,j,k,cont[i+nx*(j+ny*a[k])]);
5134  if (!errors.empty()) SetBinError(i,j,k,errors[i+nx*(j+ny*a[k])]);
5135  }
5136  }
5137  }
5138  }
5139  }
5140  }
5141  fEntries = entries;
5142  delete labold;
5143 }
5144 
5145 
5146 ////////////////////////////////////////////////////////////////////////////////
5147 
5148 static inline Bool_t AlmostEqual(Double_t a, Double_t b, Double_t epsilon = 0.00000001)
5150  return TMath::Abs(a - b) < epsilon;
5151 }
5152 
5153 
5154 ////////////////////////////////////////////////////////////////////////////////
5155 
5156 static inline Bool_t AlmostInteger(Double_t a, Double_t epsilon = 0.00000001)
5158  return AlmostEqual(a - TMath::Floor(a), 0, epsilon) ||
5159  AlmostEqual(a - TMath::Floor(a), 1, epsilon);
5160 }
5161 
5162 static inline bool IsEquidistantBinning(const TAxis& axis)
5164  // check if axis bin are equals
5165  if (!axis.GetXbins()->fN) return true; //
5166  // not able to check if there is only one axis entry
5167  bool isEquidistant = true;
5168  const Double_t firstBinWidth = axis.GetBinWidth(1);
5169  for (int i = 1; i < axis.GetNbins(); ++i) {
5170  const Double_t binWidth = axis.GetBinWidth(i);
5171  const bool match = TMath::AreEqualRel(firstBinWidth, binWidth, TMath::Limits<Double_t>::Epsilon());
5172  isEquidistant &= match;
5173  if (!match)
5174  break;
5175  }
5176  return isEquidistant;
5177 }
5178 
5179 
5180 ////////////////////////////////////////////////////////////////////////////////
5181 /// Same limits and bins.
5182 
5183 Bool_t TH1::SameLimitsAndNBins(const TAxis& axis1, const TAxis& axis2)
5185  return axis1.GetNbins() == axis2.GetNbins()
5186  && axis1.GetXmin() == axis2.GetXmin()
5187  && axis1.GetXmax() == axis2.GetXmax();
5188 }
5189 
5190 ////////////////////////////////////////////////////////////////////////////////
5191 /// Finds new limits for the axis for the Merge function.
5192 /// returns false if the limits are incompatible
5193 
5194 Bool_t TH1::RecomputeAxisLimits(TAxis& destAxis, const TAxis& anAxis)
5196  if (SameLimitsAndNBins(destAxis, anAxis))
5197  return kTRUE;
5198 
5199  if (!IsEquidistantBinning(destAxis) || !IsEquidistantBinning(anAxis))
5200  return kFALSE; // not equidistant user binning not supported
5201 
5202  Double_t width1 = destAxis.GetBinWidth(0);
5203  Double_t width2 = anAxis.GetBinWidth(0);
5204  if (width1 == 0 || width2 == 0)
5205  return kFALSE; // no binning not supported
5206 
5207  Double_t xmin = TMath::Min(destAxis.GetXmin(), anAxis.GetXmin());
5208  Double_t xmax = TMath::Max(destAxis.GetXmax(), anAxis.GetXmax());
5209  Double_t width = TMath::Max(width1, width2);
5210 
5211  // check the bin size
5212  if (!AlmostInteger(width/width1) || !AlmostInteger(width/width2))
5213  return kFALSE;
5214 
5215  // std::cout << "Find new limit using given axis " << anAxis.GetXmin() << " , " << anAxis.GetXmax() << " bin width " << width2 << std::endl;
5216  // std::cout << " and destination axis " << destAxis.GetXmin() << " , " << destAxis.GetXmax() << " bin width " << width1 << std::endl;
5217 
5218 
5219  // check the limits
5220  Double_t delta;
5221  delta = (destAxis.GetXmin() - xmin)/width1;
5222  if (!AlmostInteger(delta))
5223  xmin -= (TMath::Ceil(delta) - delta)*width1;
5224 
5225  delta = (anAxis.GetXmin() - xmin)/width2;
5226  if (!AlmostInteger(delta))
5227  xmin -= (TMath::Ceil(delta) - delta)*width2;
5228 
5229 
5230  delta = (destAxis.GetXmin() - xmin)/width1;
5231  if (!AlmostInteger(delta))
5232  return kFALSE;
5233 
5234 
5235  delta = (xmax - destAxis.GetXmax())/width1;
5236  if (!AlmostInteger(delta))
5237  xmax += (TMath::Ceil(delta) - delta)*width1;
5238 
5239 
5240  delta = (xmax - anAxis.GetXmax())/width2;
5241  if (!AlmostInteger(delta))
5242  xmax += (TMath::Ceil(delta) - delta)*width2;
5243 
5244 
5245  delta = (xmax - destAxis.GetXmax())/width1;
5246  if (!AlmostInteger(delta))
5247  return kFALSE;
5248 #ifdef DEBUG
5249  if (!AlmostInteger((xmax - xmin) / width)) { // unnecessary check
5250  printf("TH1::RecomputeAxisLimits - Impossible\n");
5251  return kFALSE;
5252  }
5253 #endif
5254 
5255 
5256  destAxis.Set(TMath::Nint((xmax - xmin)/width), xmin, xmax);
5257 
5258  //std::cout << "New re-computed axis : [ " << xmin << " , " << xmax << " ] width = " << width << " nbins " << destAxis.GetNbins() << std::endl;
5259 
5260  return kTRUE;
5261 }
5262 
5263 
5264 ////////////////////////////////////////////////////////////////////////////////
5265 /// Add all histograms in the collection to this histogram.
5266 /// This function computes the min/max for the x axis,
5267 /// compute a new number of bins, if necessary,
5268 /// add bin contents, errors and statistics.
5269 /// If all histograms have bin labels, bins with identical labels
5270 /// will be merged, no matter what their order is.
5271 /// If overflows are present and limits are different the function will fail.
5272 /// The function returns the total number of entries in the result histogram
5273 /// if the merge is successful, -1 otherwise.
5274 ///
5275 /// IMPORTANT remark. The axis x may have different number
5276 /// of bins and different limits, BUT the largest bin width must be
5277 /// a multiple of the smallest bin width and the upper limit must also
5278 /// be a multiple of the bin width.
5279 /// Example:
5280 ///
5281 /// ~~~{.cpp}
5282 /// void atest() {
5283 /// TH1F *h1 = new TH1F("h1","h1",110,-110,0);
5284 /// TH1F *h2 = new TH1F("h2","h2",220,0,110);
5285 /// TH1F *h3 = new TH1F("h3","h3",330,-55,55);
5286 /// TRandom r;
5287 /// for (Int_t i=0;i<10000;i++) {
5288 /// h1->Fill(r.Gaus(-55,10));
5289 /// h2->Fill(r.Gaus(55,10));
5290 /// h3->Fill(r.Gaus(0,10));
5291 /// }
5292 ///
5293 /// TList *list = new TList;
5294 /// list->Add(h1);
5295 /// list->Add(h2);
5296 /// list->Add(h3);
5297 /// TH1F *h = (TH1F*)h1->Clone("h");
5298 /// h->Reset();
5299 /// h->Merge(list);
5300 /// h->Draw();
5301 /// }
5302 /// ~~~
5303 
5306  if (!li) return 0;
5307  if (li->IsEmpty()) return (Long64_t) GetEntries();
5308 
5309  // is this really needed ?
5310  TList inlist;
5311  inlist.AddAll(li);
5312 
5313 
5314  TAxis newXAxis;
5315 
5316  Bool_t initialLimitsFound = kFALSE;
5317  Bool_t allHaveLabels = kTRUE; // assume all histo have labels and check later
5318  Bool_t allHaveLimits = kTRUE;
5319  Bool_t allSameLimits = kTRUE;
5320  Bool_t foundLabelHist = kFALSE;
5321  //Bool_t firstHistWithLimits = kTRUE;
5322 
5323 
5324  TIter next(&inlist);
5325  // start looping with this histogram
5326  TH1 * h = this;
5327 
5328  do {
5329  // do not skip anymore empty histograms
5330  // since are used to set the limits
5331  Bool_t hasLimits = h->GetXaxis()->GetXmin() < h->GetXaxis()->GetXmax();
5332  allHaveLimits = allHaveLimits && hasLimits;
5333 
5334  if (hasLimits) {
5335  h->BufferEmpty();
5336 
5337  // this is done in case the first histograms are empty and
5338  // the histogram have different limits
5339 #ifdef LATER
5340  if (firstHistWithLimits ) {
5341  // set axis limits in the case the first histogram did not have limits
5342  if (h != this && !SameLimitsAndNBins( fXaxis, *h->GetXaxis()) ) {
5343  if (h->GetXaxis()->GetXbins()->GetSize() != 0) fXaxis.Set(h->GetXaxis()->GetNbins(), h->GetXaxis()->GetXbins()->GetArray());
5344  else fXaxis.Set(h->GetXaxis()->GetNbins(), h->GetXaxis()->GetXmin(), h->GetXaxis()->GetXmax());
5345  }
5346  firstHistWithLimits = kFALSE;
5347  }
5348 #endif
5349 
5350  // this is executed the first time an histogram with limits is found
5351  // to set some initial values on the new axis
5352  if (!initialLimitsFound) {
5353  initialLimitsFound = kTRUE;
5354  if (h->GetXaxis()->GetXbins()->GetSize() != 0) newXAxis.Set(h->GetXaxis()->GetNbins(), h->GetXaxis()->GetXbins()->GetArray());
5355  else newXAxis.Set(h->GetXaxis()->GetNbins(), h->GetXaxis()->GetXmin(), h->GetXaxis()->GetXmax());
5356  }
5357  else {
5358  // check first if histograms have same bins
5359  if (!SameLimitsAndNBins(newXAxis, *(h->GetXaxis())) ) {
5360  allSameLimits = kFALSE;
5361  // recompute the limits in this case the optimal limits
5362  // The condition to works is that the histogram have same bin with
5363  // and one common bin edge
5364  if (!RecomputeAxisLimits(newXAxis, *(h->GetXaxis()))) {
5365  Error("Merge", "Cannot merge histograms - limits are inconsistent:\n "
5366  "first: (%d, %f, %f), second: (%d, %f, %f)",
5367  newXAxis.GetNbins(), newXAxis.GetXmin(), newXAxis.GetXmax(),
5368  h->GetXaxis()->GetNbins(), h->GetXaxis()->GetXmin(),
5369  h->GetXaxis()->GetXmax());
5370  return -1;
5371  }
5372  }
5373  }
5374  }
5375  if (allHaveLabels) {
5376  THashList* hlabels=h->GetXaxis()->GetLabels();
5377  Bool_t haveOneLabel = (hlabels != 0);
5378  // do here to print message only one time
5379  if (foundLabelHist && allHaveLabels && !haveOneLabel) {
5380  Warning("Merge","Not all histograms have labels. I will ignore labels,"
5381  " falling back to bin numbering mode.");
5382  }
5383 
5384  allHaveLabels &= (haveOneLabel);
5385  // for the error message
5386  if (haveOneLabel) foundLabelHist = kTRUE;
5387  // If histograms have labels but CanExtendAllAxes() is false
5388  // use merging of bin content
5389  if (allHaveLabels && !CanExtendAllAxes()) {
5390  allHaveLabels = kFALSE;
5391  }
5392  // it means
5393  // I could add a check if histogram contains bins without a label
5394  // and with non-zero bin content
5395  // Do we want to support this ???
5396  // only in case the !h->CanExtendAllAxes()
5397  if (allHaveLabels && !h->CanExtendAllAxes()) {
5398  // count number of bins with non-null content
5399  Int_t non_zero_bins = 0;
5400  Int_t nbins = h->GetXaxis()->GetNbins();
5401  if (nbins > hlabels->GetEntries() ) {
5402  for (Int_t i = 1; i <= nbins; i++) {
5403  if (h->RetrieveBinContent(i) != 0 || (fSumw2.fN && h->GetBinError(i) != 0) ) {
5404  non_zero_bins++;
5405  }
5406  }
5407  if (non_zero_bins > hlabels->GetEntries() ) {
5408  Warning("Merge","Histogram %s contains non-empty bins without labels - falling back to bin numbering mode",h->GetName() );
5409  allHaveLabels = kFALSE;
5410  }
5411  }
5412  // else if (h == this) {
5413  // // in case of a full labels histogram set
5414  // // the kCanRebin bit otherwise labels will be lost
5415  // // Info("Merge","Histogram %s has labels but has not the kCanRebin bit set - set the bit on to not loose labels",GetName() );
5416  // // allHaveLabels = kFALSE;
5417  // }
5418  }
5419  }
5420  } while ( ( h = dynamic_cast<TH1*> ( next() ) ) != NULL );
5421 
5422  if (!h && (*next) ) {
5423  Error("Merge","Attempt to merge object of class: %s to a %s",
5424  (*next)->ClassName(),this->ClassName());
5425  return -1;
5426  }
5427 
5428 
5429  next.Reset();
5430  // In the case of histogram with different limits
5431  // newXAxis will now have the new found limits
5432  // but one needs first to clone this histogram to perform the merge
5433  // The clone is not needed when all histograms have the same limits
5434  TH1 * hclone = 0;
5435  if (!allSameLimits) {
5436  // We don't want to add the clone to gDirectory,
5437  // so remove our kMustCleanup bit temporarily
5438  Bool_t mustCleanup = TestBit(kMustCleanup);
5439  if (mustCleanup) ResetBit(kMustCleanup);
5440  hclone = (TH1*)IsA()->New();
5441  hclone->SetDirectory(0);
5442  Copy(*hclone);
5443  if (mustCleanup) SetBit(kMustCleanup);
5444  BufferEmpty(1); // To remove buffer.
5445  Reset(); // BufferEmpty sets limits so we can't use it later.
5446  SetEntries(0);
5447  inlist.AddFirst(hclone);
5448  }
5449 
5450  // set the binning and cell content on the histogram to merge when the histograms do not have the same binning
5451  // and when one of the histogram does not have limits
5452  if (initialLimitsFound && (!allSameLimits || !allHaveLimits )) {
5453  if (newXAxis.GetXbins()->GetSize() != 0) SetBins(newXAxis.GetNbins(), newXAxis.GetXbins()->GetArray());
5454  else SetBins(newXAxis.GetNbins(), newXAxis.GetXmin(), newXAxis.GetXmax());
5455  }
5456 
5457  // std::cout << "Merging on histogram " << GetName() << std::endl;
5458  // std::cout << "Merging flags : allHaveLimits - allHaveLabels - initialLimitsFound - allSameLimits " << std::endl;
5459  // std::cout << " " << allHaveLimits << "\t\t" << allHaveLabels << "\t\t" << initialLimitsFound << "\t\t" << allSameLimits << std::endl;
5460 
5461 
5462  if (!allHaveLimits && !allHaveLabels) {
5463  // fill this histogram with all the data from buffers of histograms without limits
5464  while (TH1* hist = (TH1*)next()) {
5465  // support also case where some histogram have limits and some have the buffer
5466  if ( (hist->GetXaxis()->GetXmin() >= hist->GetXaxis()->GetXmax() ) && hist->fBuffer ) {
5467  // no limits
5468  Int_t nbentries = (Int_t)hist->fBuffer[0];
5469  for (Int_t i = 0; i < nbentries; i++)
5470  Fill(hist->fBuffer[2*i + 2], hist->fBuffer[2*i + 1]);
5471  // Entries from buffers have to be filled one by one
5472  // because FillN doesn't resize histograms.
5473  }
5474  }
5475 
5476  // all histograms have been processed
5477  if (!initialLimitsFound ) {
5478  // here the case where all histograms don't have limits
5479  // In principle I should not have copied in hclone since
5480  // when initialLimitsFound = false then allSameLimits should be true
5481  if (hclone) {
5482  inlist.Remove(hclone);
5483  delete hclone;
5484  }
5485  return (Long64_t) GetEntries();
5486  }
5487 
5488  // In case some of the histograms do not have limits
5489  // I need to remove the buffer
5490  if (fBuffer) BufferEmpty(1);
5491 
5492  next.Reset();
5493  }
5494 
5495  //merge bin contents and errors
5496  // in case when histogram have limits
5497 
5498  Double_t stats[kNstat], totstats[kNstat];
5499  for (Int_t i=0;i<kNstat;i++) {totstats[i] = stats[i] = 0;}
5500  GetStats(totstats);
5502  UInt_t oldExtendBitMask = CanExtendAllAxes();
5503  // reset, otherwise setting the under/overflow will extend the axis and make a mess
5504  if (!allHaveLabels) SetCanExtend(kNoAxis);
5505  while (TH1* hist=(TH1*)next()) {
5506  // process only if the histogram has limits; otherwise it was processed before
5507  // in the case of an existing buffer (see if statement just before)
5508 
5509  //std::cout << "merging histogram " << GetName() << " with " << hist->GetName() << std::endl;
5510 
5511  // skip empty histograms
5512  Double_t histEntries = hist->GetEntries();
5513  if (hist->fTsumw == 0 && histEntries == 0) continue;
5514 
5515 
5516  // merge for labels or histogram with limits
5517  if (allHaveLabels || (hist->GetXaxis()->GetXmin() < hist->GetXaxis()->GetXmax()) ) {
5518  // import statistics
5519  hist->GetStats(stats);
5520  for (Int_t i=0;i<kNstat;i++)
5521  totstats[i] += stats[i];
5522  nentries += histEntries;
5523 
5524  Int_t nx = hist->GetXaxis()->GetNbins();
5525  // loop on bins of the histogram and do the merge
5526  for (Int_t binx = 0; binx <= nx + 1; binx++) {
5527 
5528  Double_t cu = hist->RetrieveBinContent(binx);
5529  Double_t e1sq = 0.0;
5530  Int_t ix = -1;
5531  if (fSumw2.fN) e1sq= hist->GetBinErrorSqUnchecked(binx);
5532  // do only for bins with non null bin content or non-null errors (if Sumw2)
5533  if (TMath::Abs(cu) > 0 || (fSumw2.fN && e1sq > 0 ) ) {
5534  // case of overflow bins
5535  // they do not make sense also in the case of labels
5536  if (!allHaveLabels) {
5537  // case of bins without labels
5538  if (!allSameLimits) {
5539  if ( binx==0 || binx== nx+1) {
5540  Error("Merge", "Cannot merge histograms - the histograms have"
5541  " different limits and undeflows/overflows are present."
5542  " The initial histogram is now broken!");
5543  return -1;
5544  }
5545  // NOTE: in the case of one of the histogram as labels - it is treated as
5546  // an error and it has been flagged before
5547  // since calling FindBin(x) for histo with labels does not make sense
5548  // and the result is unpredictable
5549  ix = fXaxis.FindBin(hist->GetXaxis()->GetBinCenter(binx));
5550  }
5551  else {
5552  // histogram have same limits - no need to call FindBin
5553  ix = binx;
5554  }
5555  } else {
5556  // here only in the case of bins with labels
5557  const char* label=hist->GetXaxis()->GetBinLabel(binx);
5558  // do we need to support case when there are bins with labels and bins without them ??
5559  // NO -then return an error
5560  if (label == 0 ) {
5561  Error("Merge","Histogram %s with labels has NULL label pointer for bin %d",
5562  hist->GetName(),binx );
5563  return -1;
5564  }
5565  // special case for underflow/overflows
5566  if (label[0] == 0 && (binx == 0 || binx ==(nx+1)) ) {
5567  ix = binx;
5568  }
5569  else {
5570  // if bin does not exists FindBin will add it automatically
5571  // by calling LabelsInflate() if the bit is set
5572  // otherwise it will return zero and bin will be merged in underflow/overflow
5573  // Do we want to keep this case ??
5574  ix = fXaxis.FindBin(label);
5575  if (ix <= 0) {
5576  Warning("Merge", "Histogram %s has labels but CanExtendAllAxes() is false - label %s is lost", GetName(), label);
5577  continue;
5578  }
5579  }
5580  }
5581  if (ix >= 0) {
5582  // MERGE here the bin contents
5583  //std::cout << "merging bin " << binx << " into " << ix << " with bin content " << cu << " bin center x = " << GetBinCenter(ix) << std::endl;
5584  if (ix > fNcells )
5585  Fatal("Merge","Fatal error merging histogram %s - bin number is %d and array size is %d",GetName(), ix,fNcells);
5586 
5587  AddBinContent(ix,cu);
5588  if (fSumw2.fN) fSumw2.fArray[ix] += e1sq;
5589  }
5590  }
5591  }
5592  }
5593  }
5594  SetCanExtend(oldExtendBitMask); // restore previous extend state
5595 
5596 
5597  //copy merged stats
5598  PutStats(totstats);
5599  SetEntries(nentries);
5600  if (hclone) {
5601  inlist.Remove(hclone);
5602  delete hclone;
5603  }
5604  return (Long64_t)nentries;
5605 }
5606 
5607 
5608 ////////////////////////////////////////////////////////////////////////////////
5609 /// Performs the operation: this = this*c1*f1
5610 /// if errors are defined (see TH1::Sumw2), errors are also recalculated.
5611 ///
5612 /// Only bins inside the function range are recomputed.
5613 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
5614 /// you should call Sumw2 before making this operation.
5615 /// This is particularly important if you fit the histogram after TH1::Multiply
5616 ///
5617 /// The function return kFALSE if the Multiply operation failed
5618 
5621  if (!f1) {
5622  Error("Add","Attempt to multiply by a non-existing function");
5623  return kFALSE;
5624  }
5625 
5626  // delete buffer if it is there since it will become invalid
5627  if (fBuffer) BufferEmpty(1);
5628 
5629  Int_t nx = GetNbinsX() + 2; // normal bins + uf / of (cells)
5630  Int_t ny = GetNbinsY() + 2;
5631  Int_t nz = GetNbinsZ() + 2;
5632  if (fDimension < 2) ny = 1;
5633  if (fDimension < 3) nz = 1;
5634 
5635  // reset min-maximum
5636  SetMinimum();
5637  SetMaximum();
5638 
5639  // - Loop on bins (including underflows/overflows)
5640  Double_t xx[3];
5641  Double_t *params = 0;
5642  f1->InitArgs(xx,params);
5643 
5644  for (Int_t binz = 0; binz < nz; ++binz) {
5645  xx[2] = fZaxis.GetBinCenter(binz);
5646  for (Int_t biny = 0; biny < ny; ++biny) {
5647  xx[1] = fYaxis.GetBinCenter(biny);
5648  for (Int_t binx = 0; binx < nx; ++binx) {
5649  xx[0] = fXaxis.GetBinCenter(binx);
5650  if (!f1->IsInside(xx)) continue;
5652  Int_t bin = binx + nx * (biny + ny *binz);
5653  Double_t cu = c1*f1->EvalPar(xx);
5654  if (TF1::RejectedPoint()) continue;
5655  UpdateBinContent(bin, RetrieveBinContent(bin) * cu);
5656  if (fSumw2.fN) {
5657  fSumw2.fArray[bin] = cu * cu * GetBinErrorSqUnchecked(bin);
5658  }
5659  }
5660  }
5661  }
5662  ResetStats();
5663  return kTRUE;
5664 }
5665 
5666 
5667 ////////////////////////////////////////////////////////////////////////////////
5668 /// Multiply this histogram by h1.
5669 ///
5670 /// this = this*h1
5671 ///
5672 /// If errors of this are available (TH1::Sumw2), errors are recalculated.
5673 /// Note that if h1 has Sumw2 set, Sumw2 is automatically called for this
5674 /// if not already set.
5675 ///
5676 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
5677 /// you should call Sumw2 before making this operation.
5678 /// This is particularly important if you fit the histogram after TH1::Multiply
5679 ///
5680 /// The function return kFALSE if the Multiply operation failed
5681 
5682 Bool_t TH1::Multiply(const TH1 *h1)
5684  if (!h1) {
5685  Error("Multiply","Attempt to multiply by a non-existing histogram");
5686  return kFALSE;
5687  }
5688 
5689  // delete buffer if it is there since it will become invalid
5690  if (fBuffer) BufferEmpty(1);
5691 
5692  try {
5693  CheckConsistency(this,h1);
5694  } catch(DifferentNumberOfBins&) {
5695  Error("Multiply","Attempt to multiply histograms with different number of bins");
5696  return kFALSE;
5697  } catch(DifferentAxisLimits&) {
5698  Warning("Multiply","Attempt to multiply histograms with different axis limits");
5699  } catch(DifferentBinLimits&) {
5700  Warning("Multiply","Attempt to multiply histograms with different bin limits");
5701  } catch(DifferentLabels&) {
5702  Warning("Multiply","Attempt to multiply histograms with different labels");
5703  }
5704 
5705  // Create Sumw2 if h1 has Sumw2 set
5706  if (fSumw2.fN == 0 && h1->GetSumw2N() != 0) Sumw2();
5707 
5708  // - Reset min- maximum
5709  SetMinimum();
5710  SetMaximum();
5711 
5712  // - Loop on bins (including underflows/overflows)
5713  for (Int_t i = 0; i < fNcells; ++i) {
5714  Double_t c0 = RetrieveBinContent(i);
5715  Double_t c1 = h1->RetrieveBinContent(i);
5716  UpdateBinContent(i, c0 * c1);
5717  if (fSumw2.fN) {
5718  fSumw2.fArray[i] = GetBinErrorSqUnchecked(i) * c1 * c1 + h1->GetBinErrorSqUnchecked(i) * c0 * c0;
5719  }
5720  }
5721  ResetStats();
5722  return kTRUE;
5723 }
5724 
5725 
5726 ////////////////////////////////////////////////////////////////////////////////
5727 /// Replace contents of this histogram by multiplication of h1 by h2.
5728 ///
5729 /// this = (c1*h1)*(c2*h2)
5730 ///
5731 /// If errors of this are available (TH1::Sumw2), errors are recalculated.
5732 /// Note that if h1 or h2 have Sumw2 set, Sumw2 is automatically called for this
5733 /// if not already set.
5734 ///
5735 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
5736 /// you should call Sumw2 before making this operation.
5737 /// This is particularly important if you fit the histogram after TH1::Multiply
5738 ///
5739 /// The function return kFALSE if the Multiply operation failed
5740 
5741 Bool_t TH1::Multiply(const TH1 *h1, const TH1 *h2, Double_t c1, Double_t c2, Option_t *option)
5743  TString opt = option;
5744  opt.ToLower();
5745  // Bool_t binomial = kFALSE;
5746  // if (opt.Contains("b")) binomial = kTRUE;
5747  if (!h1 || !h2) {
5748  Error("Multiply","Attempt to multiply by a non-existing histogram");
5749  return kFALSE;
5750  }
5751 
5752  // delete buffer if it is there since it will become invalid
5753  if (fBuffer) BufferEmpty(1);
5754 
5755  try {
5756  CheckConsistency(h1,h2);
5757  CheckConsistency(this,h1);
5758  } catch(DifferentNumberOfBins&) {
5759  Error("Multiply","Attempt to multiply histograms with different number of bins");
5760  return kFALSE;
5761  } catch(DifferentAxisLimits&) {
5762  Warning("Multiply","Attempt to multiply histograms with different axis limits");
5763  } catch(DifferentBinLimits&) {
5764  Warning("Multiply","Attempt to multiply histograms with different bin limits");
5765  } catch(DifferentLabels&) {
5766  Warning("Multiply","Attempt to multiply histograms with different labels");
5767  }
5768 
5769  // Create Sumw2 if h1 or h2 have Sumw2 set
5770  if (fSumw2.fN == 0 && (h1->GetSumw2N() != 0 || h2->GetSumw2N() != 0)) Sumw2();
5771 
5772  // - Reset min - maximum
5773  SetMinimum();
5774  SetMaximum();
5775 
5776  // - Loop on bins (including underflows/overflows)
5777  Double_t c1sq = c1 * c1; Double_t c2sq = c2 * c2;
5778  for (Int_t i = 0; i < fNcells; ++i) {
5779  Double_t b1 = h1->RetrieveBinContent(i);
5780  Double_t b2 = h2->RetrieveBinContent(i);
5781  UpdateBinContent(i, c1 * b1 * c2 * b2);
5782  if (fSumw2.fN) {
5783  fSumw2.fArray[i] = c1sq * c2sq * (h1->GetBinErrorSqUnchecked(i) * b2 * b2 + h2->GetBinErrorSqUnchecked(i) * b1 * b1);
5784  }
5785  }
5786  ResetStats();
5787  return kTRUE;
5788 }
5789 
5790 
5791 ////////////////////////////////////////////////////////////////////////////////
5792 /// Control routine to paint any kind of histograms.
5793 ///
5794 /// This function is automatically called by TCanvas::Update.
5795 /// (see TH1::Draw for the list of options)
5796 
5797 void TH1::Paint(Option_t *option)
5799  GetPainter(option);
5800 
5801  if (fPainter) {
5802  if (strlen(option) > 0) fPainter->Paint(option);
5803  else fPainter->Paint(fOption.Data());
5804  }
5805 }
5806 
5807 
5808 ////////////////////////////////////////////////////////////////////////////////
5809 /// Rebin this histogram
5810 ///
5811 /// ### case 1 xbins=0
5812 /// If newname is blank (default), the current histogram is modified and
5813 /// a pointer to it is returned.
5814 ///
5815 /// If newname is not blank, the current histogram is not modified, and a
5816 /// new histogram is returned which is a Clone of the current histogram
5817 /// with its name set to newname.
5818 ///
5819 /// The parameter ngroup indicates how many bins of this have to be merged
5820 /// into one bin of the result.
5821 ///
5822 /// If the original histogram has errors stored (via Sumw2), the resulting
5823 /// histograms has new errors correctly calculated.
5824 ///
5825 /// examples: if h1 is an existing TH1F histogram with 100 bins
5826 ///
5827 /// h1->Rebin(); //merges two bins in one in h1: previous contents of h1 are lost
5828 /// h1->Rebin(5); //merges five bins in one in h1
5829 /// TH1F *hnew = h1->Rebin(5,"hnew"); // creates a new histogram hnew
5830 /// // merging 5 bins of h1 in one bin
5831 ///
5832 /// NOTE: If ngroup is not an exact divider of the number of bins,
5833 /// the top limit of the rebinned histogram is reduced
5834 /// to the upper edge of the last bin that can make a complete
5835 /// group. The remaining bins are added to the overflow bin.
5836 /// Statistics will be recomputed from the new bin contents.
5837 ///
5838 /// ### case 2 xbins!=0
5839 /// A new histogram is created (you should specify newname).
5840 /// The parameter ngroup is the number of variable size bins in the created histogram.
5841 /// The array xbins must contain ngroup+1 elements that represent the low-edges
5842 /// of the bins.
5843 /// If the original histogram has errors stored (via Sumw2), the resulting
5844 /// histograms has new errors correctly calculated.
5845 ///
5846 /// NOTE: The bin edges specified in xbins should correspond to bin edges
5847 /// in the original histogram. If a bin edge in the new histogram is
5848 /// in the middle of a bin in the original histogram, all entries in
5849 /// the split bin in the original histogram will be transfered to the
5850 /// lower of the two possible bins in the new histogram. This is
5851 /// probably not what you want.
5852 ///
5853 /// examples: if h1 is an existing TH1F histogram with 100 bins
5854 ///
5855 /// Double_t xbins[25] = {...} array of low-edges (xbins[25] is the upper edge of last bin
5856 /// h1->Rebin(24,"hnew",xbins); //creates a new variable bin size histogram hnew
5857 
5858 TH1 *TH1::Rebin(Int_t ngroup, const char*newname, const Double_t *xbins)
5860  Int_t nbins = fXaxis.GetNbins();
5863  if ((ngroup <= 0) || (ngroup > nbins)) {
5864  Error("Rebin", "Illegal value of ngroup=%d",ngroup);
5865  return 0;
5866  }
5867 
5868  if (fDimension > 1 || InheritsFrom(TProfile::Class())) {
5869  Error("Rebin", "Operation valid on 1-D histograms only");
5870  return 0;
5871  }
5872  if (!newname && xbins) {
5873  Error("Rebin","if xbins is specified, newname must be given");
5874  return 0;
5875  }
5876 
5877  Int_t newbins = nbins/ngroup;
5878  if (!xbins) {
5879  Int_t nbg = nbins/ngroup;
5880  if (nbg*ngroup != nbins) {
5881  Warning("Rebin", "ngroup=%d is not an exact divider of nbins=%d.",ngroup,nbins);
5882  }
5883  }
5884  else {
5885  // in the case that xbins is given (rebinning in variable bins), ngroup is
5886  // the new number of bins and number of grouped bins is not constant.
5887  // when looping for setting the contents for the new histogram we
5888  // need to loop on all bins of original histogram. Then set ngroup=nbins
5889  newbins = ngroup;
5890  ngroup = nbins;
5891  }
5892 
5893  // Save old bin contents into a new array
5894  Double_t entries = fEntries;
5895  Double_t *oldBins = new Double_t[nbins+2];
5896  Int_t bin, i;
5897  for (bin=0;bin<nbins+2;bin++) oldBins[bin] = RetrieveBinContent(bin);
5898  Double_t *oldErrors = 0;
5899  if (fSumw2.fN != 0) {
5900  oldErrors = new Double_t[nbins+2];
5901  for (bin=0;bin<nbins+2;bin++) oldErrors[bin] = GetBinError(bin);
5902  }
5903  // rebin will not include underflow/overflow if new axis range is larger than old axis range
5904  if (xbins) {
5905  if (xbins[0] < fXaxis.GetXmin() && oldBins[0] != 0 )
5906  Warning("Rebin","underflow entries will not be used when rebinning");
5907  if (xbins[newbins] > fXaxis.GetXmax() && oldBins[nbins+1] != 0 )
5908  Warning("Rebin","overflow entries will not be used when rebinning");
5909  }
5910 
5911 
5912  // create a clone of the old histogram if newname is specified
5913  TH1 *hnew = this;
5914  if ((newname && strlen(newname) > 0) || xbins) {
5915  hnew = (TH1*)Clone(newname);
5916  }
5917 
5918  //reset can extend bit to avoid an axis extension in SetBinContent
5919  UInt_t oldExtendBitMask = hnew->SetCanExtend(kNoAxis);
5920 
5921  // save original statistics
5922  Double_t stat[kNstat];
5923  GetStats(stat);
5924  bool resetStat = false;
5925  // change axis specs and rebuild bin contents array::RebinAx
5926  if(!xbins && (newbins*ngroup != nbins)) {
5927  xmax = fXaxis.GetBinUpEdge(newbins*ngroup);
5928  resetStat = true; //stats must be reset because top bins will be moved to overflow bin
5929  }
5930  // save the TAttAxis members (reset by SetBins)
5931  Int_t nDivisions = fXaxis.GetNdivisions();
5932  Color_t axisColor = fXaxis.GetAxisColor();
5933  Color_t labelColor = fXaxis.GetLabelColor();
5934  Style_t labelFont = fXaxis.GetLabelFont();
5935  Float_t labelOffset = fXaxis.GetLabelOffset();
5936  Float_t labelSize = fXaxis.GetLabelSize();
5937  Float_t tickLength = fXaxis.GetTickLength();
5938  Float_t titleOffset = fXaxis.GetTitleOffset();
5939  Float_t titleSize = fXaxis.GetTitleSize();
5940  Color_t titleColor = fXaxis.GetTitleColor();
5941  Style_t titleFont = fXaxis.GetTitleFont();
5942 
5943  if(!xbins && (fXaxis.GetXbins()->GetSize() > 0)){ // variable bin sizes
5944  Double_t *bins = new Double_t[newbins+1];
5945  for(i = 0; i <= newbins; ++i) bins[i] = fXaxis.GetBinLowEdge(1+i*ngroup);
5946  hnew->SetBins(newbins,bins); //this also changes errors array (if any)
5947  delete [] bins;
5948  } else if (xbins) {
5949  hnew->SetBins(newbins,xbins);
5950  } else {
5951  hnew->SetBins(newbins,xmin,xmax);
5952  }
5953 
5954  // Restore axis attributes
5955  fXaxis.SetNdivisions(nDivisions);
5956  fXaxis.SetAxisColor(axisColor);
5957  fXaxis.SetLabelColor(labelColor);
5958  fXaxis.SetLabelFont(labelFont);
5959  fXaxis.SetLabelOffset(labelOffset);
5960  fXaxis.SetLabelSize(labelSize);
5961  fXaxis.SetTickLength(tickLength);
5962  fXaxis.SetTitleOffset(titleOffset);
5963  fXaxis.SetTitleSize(titleSize);
5964  fXaxis.SetTitleColor(titleColor);
5965  fXaxis.SetTitleFont(titleFont);
5966 
5967  // copy merged bin contents (ignore under/overflows)
5968  // Start merging only once the new lowest edge is reached
5969  Int_t startbin = 1;
5970  const Double_t newxmin = hnew->GetXaxis()->GetBinLowEdge(1);
5971  while( fXaxis.GetBinCenter(startbin) < newxmin && startbin <= nbins ) {
5972  startbin++;
5973  }
5974  Int_t oldbin = startbin;
5975  Double_t binContent, binError;
5976  for (bin = 1;bin<=newbins;bin++) {
5977  binContent = 0;
5978  binError = 0;
5979  Int_t imax = ngroup;
5980  Double_t xbinmax = hnew->GetXaxis()->GetBinUpEdge(bin);
5981  for (i=0;i<ngroup;i++) {
5982  if( (oldbin+i > nbins) ||
5983  ( hnew != this && (fXaxis.GetBinCenter(oldbin+i) > xbinmax)) ) {
5984  imax = i;
5985  break;
5986  }
5987  binContent += oldBins[oldbin+i];
5988  if (oldErrors) binError += oldErrors[oldbin+i]*oldErrors[oldbin+i];
5989  }
5990  hnew->SetBinContent(bin,binContent);
5991  if (oldErrors) hnew->SetBinError(bin,TMath::Sqrt(binError));
5992  oldbin += imax;
5993  }
5994 
5995  // sum underflow and overflow contents until startbin
5996  binContent = 0;
5997  binError = 0;
5998  for (i = 0; i < startbin; ++i) {
5999  binContent += oldBins[i];
6000  if (oldErrors) binError += oldErrors[i]*oldErrors[i];
6001  }
6002  hnew->SetBinContent(0,binContent);
6003  if (oldErrors) hnew->SetBinError(0,TMath::Sqrt(binError));
6004  // sum overflow
6005  binContent = 0;
6006  binError = 0;
6007  for (i = oldbin; i <= nbins+1; ++i) {
6008  binContent += oldBins[i];
6009  if (oldErrors) binError += oldErrors[i]*oldErrors[i];
6010  }
6011  hnew->SetBinContent(newbins+1,binContent);
6012  if (oldErrors) hnew->SetBinError(newbins+1,TMath::Sqrt(binError));
6013 
6014  hnew->SetCanExtend(oldExtendBitMask); // restore previous state
6015 
6016  // restore statistics and entries modified by SetBinContent
6017  hnew->SetEntries(entries);
6018  if (!resetStat) hnew->PutStats(stat);
6019  delete [] oldBins;
6020  if (oldErrors) delete [] oldErrors;
6021  return hnew;
6022 }
6023 
6024 
6025 ////////////////////////////////////////////////////////////////////////////////
6026 /// finds new limits for the axis so that *point* is within the range and
6027 /// the limits are compatible with the previous ones (see TH1::Merge).
6028 /// new limits are put into *newMin* and *newMax* variables.
6029 /// axis - axis whose limits are to be recomputed
6030 /// point - point that should fit within the new axis limits
6031 /// newMin - new minimum will be stored here
6032 /// newMax - new maximum will be stored here.
6033 /// false if failed (e.g. if the initial axis limits are wrong
6034 /// or the new range is more than 2^64 times the old one).
6035 
6036 Bool_t TH1::FindNewAxisLimits(const TAxis* axis, const Double_t point, Double_t& newMin, Double_t &newMax)
6038  Double_t xmin = axis->GetXmin();
6039  Double_t xmax = axis->GetXmax();
6040  if (xmin >= xmax) return kFALSE;
6041  Double_t range = xmax-xmin;
6042  Double_t binsize = range / axis->GetNbins();
6043 
6044  //recompute new axis limits by doubling the current range
6045  Int_t ntimes = 0;
6046  while (point < xmin) {
6047  if (ntimes++ > 64)
6048  return kFALSE;
6049  xmin = xmin - range;
6050  range *= 2;
6051  binsize *= 2;
6052  // // make sure that the merging will be correct
6053  // if ( xmin / binsize - TMath::Floor(xmin / binsize) >= 0.5) {
6054  // xmin += 0.5 * binsize;
6055  // xmax += 0.5 * binsize; // won't work with a histogram with only one bin, but I don't care
6056  // }
6057  }
6058  while (point >= xmax) {
6059  if (ntimes++ > 64)
6060  return kFALSE;
6061  xmax = xmax + range;
6062  range *= 2;
6063  binsize *= 2;
6064  // // make sure that the merging will be correct
6065  // if ( xmin / binsize - TMath::Floor(xmin / binsize) >= 0.5) {
6066  // xmin -= 0.5 * binsize;
6067  // xmax -= 0.5 * binsize; // won't work with a histogram with only one bin, but I don't care
6068  // }
6069  }
6070  newMin = xmin;
6071  newMax = xmax;
6072  // Info("FindNewAxisLimits", "OldAxis: (%lf, %lf), new: (%lf, %lf), point: %lf",
6073  // axis->GetXmin(), axis->GetXmax(), xmin, xmax, point);
6074 
6075  return kTRUE;
6076 }
6077 
6078 
6079 ////////////////////////////////////////////////////////////////////////////////
6080 /// Histogram is resized along axis such that x is in the axis range.
6081 /// The new axis limits are recomputed by doubling iteratively
6082 /// the current axis range until the specified value x is within the limits.
6083 /// The algorithm makes a copy of the histogram, then loops on all bins
6084 /// of the old histogram to fill the extended histogram.
6085 /// Takes into account errors (Sumw2) if any.
6086 /// The algorithm works for 1-d, 2-D and 3-D histograms.
6087 /// The axis must be extendable before invoking this function.
6088 /// Ex: h->GetXaxis()->SetCanExtend(kTRUE);
6089 
6092  if (!axis->CanExtend()) return;
6093  if (TMath::IsNaN(x)) { // x may be a NaN
6095  return;
6096  }
6097 
6098  if (axis->GetXmin() >= axis->GetXmax()) return;
6099  if (axis->GetNbins() <= 0) return;
6100 
6101  Double_t xmin, xmax;
6102  if (!FindNewAxisLimits(axis, x, xmin, xmax))
6103  return;
6104 
6105  //save a copy of this histogram
6106  TH1 *hold = (TH1*)IsA()->New();
6107  hold->SetDirectory(0);
6108  Copy(*hold);
6109  //set new axis limits
6110  axis->SetLimits(xmin,xmax);
6111 
6112  Int_t nbinsx = fXaxis.GetNbins();
6113  Int_t nbinsy = fYaxis.GetNbins();
6114  Int_t nbinsz = fZaxis.GetNbins();
6115 
6116  //now loop on all bins and refill
6117  Double_t bx,by,bz;
6118  Int_t errors = GetSumw2N();
6119  Int_t ix,iy,iz,ibin,binx,biny,binz,bin;
6120  Reset("ICE"); //reset only Integral, contents and Errors
6121  for (binz=1;binz<=nbinsz;binz++) {
6122  bz = hold->GetZaxis()->GetBinCenter(binz);
6123  iz = fZaxis.FindFixBin(bz);
6124  for (biny=1;biny<=nbinsy;biny++) {
6125  by = hold->GetYaxis()->GetBinCenter(biny);
6126  iy = fYaxis.FindFixBin(by);
6127  for (binx=1;binx<=nbinsx;binx++) {
6128  bx = hold->GetXaxis()->GetBinCenter(binx);
6129  ix = fXaxis.FindFixBin(bx);
6130  bin = hold->GetBin(binx,biny,binz);
6131  ibin= GetBin(ix,iy,iz);
6132  AddBinContent(ibin, hold->RetrieveBinContent(bin));
6133  if (errors) {
6134  fSumw2.fArray[ibin] += hold->GetBinErrorSqUnchecked(bin);
6135  }
6136  }
6137  }
6138  }
6139  delete hold;
6140 }
6141 
6142 
6143 ////////////////////////////////////////////////////////////////////////////////
6144 /// Recursively remove object from the list of functions
6145 
6146 void TH1::RecursiveRemove(TObject *obj)
6148  if (fFunctions) {
6150  }
6151 }
6152 
6153 
6154 ////////////////////////////////////////////////////////////////////////////////
6155 /// Multiply this histogram by a constant c1.
6156 ///
6157 ///this = c1*this
6158 ///
6159 /// Note that both contents and errors(if any) are scaled.
6160 /// This function uses the services of TH1::Add
6161 ///
6162 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
6163 /// you should call Sumw2 before making this operation.
6164 /// This is particularly important if you fit the histogram after TH1::Scale
6165 ///
6166 /// One can scale an histogram such that the bins integral is equal to
6167 /// the normalization parameter via TH1::Scale(Double_t norm), where norm
6168 /// is the desired normalization divided by the integral of the histogram.
6169 ///
6170 /// If option contains "width" the bin contents and errors are divided
6171 /// by the bin width.
6172 
6173 void TH1::Scale(Double_t c1, Option_t *option)
6175 
6176  TString opt = option; opt.ToLower();
6177  if (opt.Contains("width")) Add(this, this, c1, -1);
6178  else {
6179  if (fBuffer) BufferEmpty(1);
6180  for(Int_t i = 0; i < fNcells; ++i) UpdateBinContent(i, c1 * RetrieveBinContent(i));
6181  if (fSumw2.fN) for(Int_t i = 0; i < fNcells; ++i) fSumw2.fArray[i] *= (c1 * c1); // update errors
6182  SetMinimum(); SetMaximum(); // minimum and maximum value will be recalculated the next time
6183  }
6184 
6185  // if contours set, must also scale contours
6186  Int_t ncontours = GetContour();
6187  if (ncontours == 0) return;
6188  Double_t* levels = fContour.GetArray();
6189  for (Int_t i = 0; i < ncontours; ++i) levels[i] *= c1;
6190 }
6191 
6192 
6193 ////////////////////////////////////////////////////////////////////////////////
6194 /// returns true if all axes are extendable
6195 
6198  Bool_t canExtend = fXaxis.CanExtend();
6199  if (GetDimension() > 1) canExtend &= fYaxis.CanExtend();
6200  if (GetDimension() > 2) canExtend &= fZaxis.CanExtend();
6201 
6202  return canExtend;
6203 }
6204 
6205 
6206 ////////////////////////////////////////////////////////////////////////////////
6207 /// make the histogram axes extendable / not extendable according to the bit mask
6208 /// returns the previous bit mask specifying which axes are extendable
6209 
6210 UInt_t TH1::SetCanExtend(UInt_t extendBitMask)
6212  UInt_t oldExtendBitMask = kNoAxis;
6213 
6214  if (fXaxis.CanExtend()) oldExtendBitMask |= kXaxis;
6215  if (extendBitMask & kXaxis) fXaxis.SetCanExtend(kTRUE);
6216  else fXaxis.SetCanExtend(kFALSE);
6217 
6218  if (GetDimension() > 1) {
6219  if (fYaxis.CanExtend()) oldExtendBitMask |= kYaxis;
6220  if (extendBitMask & kYaxis) fYaxis.SetCanExtend(kTRUE);
6221  else fYaxis.SetCanExtend(kFALSE);
6222  }
6223 
6224  if (GetDimension() > 2) {
6225  if (fZaxis.CanExtend()) oldExtendBitMask |= kZaxis;
6226  if (extendBitMask & kZaxis) fZaxis.SetCanExtend(kTRUE);
6227  else fZaxis.SetCanExtend(kFALSE);
6228  }
6229 
6230  return oldExtendBitMask;
6231 }
6232 
6233 
6234 ////////////////////////////////////////////////////////////////////////////////
6235 /// static function to set the default buffer size for automatic histograms.
6236 /// When an histogram is created with one of its axis lower limit greater
6237 /// or equal to its upper limit, the function SetBuffer is automatically
6238 /// called with the default buffer size.
6239 
6240 void TH1::SetDefaultBufferSize(Int_t buffersize)
6242  fgBufferSize = buffersize > 0 ? buffersize : 0;
6243 }
6244 
6245 
6246 ////////////////////////////////////////////////////////////////////////////////
6247 /// static function.
6248 /// When this static function is called with sumw2=kTRUE, all new
6249 /// histograms will automatically activate the storage
6250 /// of the sum of squares of errors, ie TH1::Sumw2 is automatically called.
6251 
6252 void TH1::SetDefaultSumw2(Bool_t sumw2)
6254  fgDefaultSumw2 = sumw2;
6255 }
6256 
6257 
6258 ////////////////////////////////////////////////////////////////////////////////
6259 /// Change (i.e. set) the title
6260 ///
6261 ///if title is in the form "stringt;stringx;stringy;stringz"
6262 ///the histogram title is set to stringt, the x axis title to stringx,
6263 ///the y axis title to stringy, and the z axis title to stringz.
6264 ///To insert the character ";" in one of the titles, one should use "#;"
6265 ///or "#semicolon".
6266 
6267 void TH1::SetTitle(const char *title)
6269  fTitle = title;
6270  fTitle.ReplaceAll("#;",2,"#semicolon",10);
6271 
6272  // Decode fTitle. It may contain X, Y and Z titles
6273  TString str1 = fTitle, str2;
6274  Int_t isc = str1.Index(";");
6275  Int_t lns = str1.Length();
6276 
6277  if (isc >=0 ) {
6278  fTitle = str1(0,isc);
6279  str1 = str1(isc+1, lns);
6280  isc = str1.Index(";");
6281  if (isc >=0 ) {
6282  str2 = str1(0,isc);
6283  str2.ReplaceAll("#semicolon",10,";",1);
6284  fXaxis.SetTitle(str2.Data());
6285  lns = str1.Length();
6286  str1 = str1(isc+1, lns);
6287  isc = str1.Index(";");
6288  if (isc >=0 ) {
6289  str2 = str1(0,isc);
6290  str2.ReplaceAll("#semicolon",10,";",1);
6291  fYaxis.SetTitle(str2.Data());
6292  lns = str1.Length();
6293  str1 = str1(isc+1, lns);
6294  str1.ReplaceAll("#semicolon",10,";",1);
6295  fZaxis.SetTitle(str1.Data());
6296  } else {
6297  str1.ReplaceAll("#semicolon",10,";",1);
6298  fYaxis.SetTitle(str1.Data());
6299  }
6300  } else {
6301  str1.ReplaceAll("#semicolon",10,";",1);
6302  fXaxis.SetTitle(str1.Data());
6303  }
6304  }
6305 
6306  fTitle.ReplaceAll("#semicolon",10,";",1);
6307 
6308  if (gPad && TestBit(kMustCleanup)) gPad->Modified();
6309 }
6310 
6311 
6312 ////////////////////////////////////////////////////////////////////////////////
6313 /// smooth array xx, translation of Hbook routine hsmoof.F
6314 /// based on algorithm 353QH twice presented by J. Friedman
6315 /// in Proc.of the 1974 CERN School of Computing, Norway, 11-24 August, 1974.
6316 
6317 void TH1::SmoothArray(Int_t nn, Double_t *xx, Int_t ntimes)
6319  if (nn < 3 ) {
6320  ::Error("SmoothArray","Need at least 3 points for smoothing: n = %d",nn);
6321  return;
6322  }
6323 
6324  Int_t ii;
6325  Double_t hh[6] = {0,0,0,0,0,0};
6326 
6327  std::vector<double> yy(nn);
6328  std::vector<double> zz(nn);
6329  std::vector<double> rr(nn);
6330 
6331  for (Int_t pass=0;pass<ntimes;pass++) {
6332  // first copy original data into temp array
6333  std::copy(xx, xx+nn, zz.begin() );
6334 
6335 
6336 
6337  for (int noent = 0; noent < 2; ++noent) { // run algorithm two times
6338 
6339  // do 353 i.e. running median 3, 5, and 3 in a single loop
6340  for (int kk = 0; kk < 3; kk++) {
6341  std::copy(zz.begin(), zz.end(), yy.begin());
6342  int medianType = (kk != 1) ? 3 : 5;
6343  int ifirst = (kk != 1 ) ? 1 : 2;
6344  int ilast = (kk != 1 ) ? nn-1 : nn -2;
6345  //nn2 = nn - ik - 1;
6346  // do all elements beside the first and last point for median 3
6347  // and first two and last 2 for median 5
6348  for ( ii = ifirst; ii < ilast; ii++) {
6349  assert(ii - ifirst >= 0);
6350  for (int jj = 0; jj < medianType; jj++) {
6351  hh[jj] = yy[ii - ifirst + jj ];
6352  }
6353  zz[ii] = TMath::Median(medianType, hh);
6354  }
6355 
6356  if (kk == 0) { // first median 3
6357  // first point
6358  hh[0] = zz[1];
6359  hh[1] = zz[0];
6360  hh[2] = 3*zz[1] - 2*zz[2];
6361  zz[0] = TMath::Median(3, hh);
6362  // last point
6363  hh[0] = zz[nn - 2];
6364  hh[1] = zz[nn - 1];
6365  hh[2] = 3*zz[nn - 2] - 2*zz[nn - 3];
6366  zz[nn - 1] = TMath::Median(3, hh);
6367  }
6368 
6369 
6370  if (kk == 1) { // median 5
6371  for (ii = 0; ii < 3; ii++) {
6372  hh[ii] = yy[ii];
6373  }
6374  zz[1] = TMath::Median(3, hh);
6375  // last two points
6376  for (ii = 0; ii < 3; ii++) {
6377  hh[ii] = yy[nn - 3 + ii];
6378  }
6379  zz[nn - 2] = TMath::Median(3, hh);
6380  }
6381 
6382  }
6383 
6384  std::copy ( zz.begin(), zz.end(), yy.begin() );
6385 
6386  // quadratic interpolation for flat segments
6387  for (ii = 2; ii < (nn - 2); ii++) {
6388  if (zz[ii - 1] != zz[ii]) continue;
6389  if (zz[ii] != zz[ii + 1]) continue;
6390  hh[0] = zz[ii - 2] - zz[ii];
6391  hh[1] = zz[ii + 2] - zz[ii];
6392  if (hh[0] * hh[1] <= 0) continue;
6393  int jk = 1;
6394  if ( TMath::Abs(hh[1]) > TMath::Abs(hh[0]) ) jk = -1;
6395  yy[ii] = -0.5*zz[ii - 2*jk] + zz[ii]/0.75 + zz[ii + 2*jk] /6.;
6396  yy[ii + jk] = 0.5*(zz[ii + 2*jk] - zz[ii - 2*jk]) + zz[ii];
6397  }
6398 
6399  // running means
6400  //std::copy(zz.begin(), zz.end(), yy.begin());
6401  for (ii = 1; ii < nn - 1; ii++) {
6402  zz[ii] = 0.25*yy[ii - 1] + 0.5*yy[ii] + 0.25*yy[ii + 1];
6403  }
6404  zz[0] = yy[0];
6405  zz[nn - 1] = yy[nn - 1];
6406 
6407  if (noent == 0) {
6408 
6409  // save computed values
6410  std::copy(zz.begin(), zz.end(), rr.begin());
6411 
6412  // COMPUTE residuals
6413  for (ii = 0; ii < nn; ii++) {
6414  zz[ii] = xx[ii] - zz[ii];
6415  }
6416  }
6417 
6418  } // end loop on noent
6419 
6420 
6421  double xmin = TMath::MinElement(nn,xx);
6422  for (ii = 0; ii < nn; ii++) {
6423  if (xmin < 0) xx[ii] = rr[ii] + zz[ii];
6424  // make smoothing defined positive - not better using 0 ?
6425  else xx[ii] = TMath::Max((rr[ii] + zz[ii]),0.0 );
6426  }
6427  }
6428 }
6429 
6430 
6431 ////////////////////////////////////////////////////////////////////////////////
6432 /// Smooth bin contents of this histogram.
6433 /// if option contains "R" smoothing is applied only to the bins
6434 /// defined in the X axis range (default is to smooth all bins)
6435 /// Bin contents are replaced by their smooth values.
6436 /// Errors (if any) are not modified.
6437 /// the smoothing procedure is repeated ntimes (default=1)
6438 
6439 void TH1::Smooth(Int_t ntimes, Option_t *option)
6441  if (fDimension != 1) {
6442  Error("Smooth","Smooth only supported for 1-d histograms");
6443  return;
6444  }
6445  Int_t nbins = fXaxis.GetNbins();
6446  if (nbins < 3) {
6447  Error("Smooth","Smooth only supported for histograms with >= 3 bins. Nbins = %d",nbins);
6448  return;
6449  }
6450 
6451  // delete buffer if it is there since it will become invalid
6452  if (fBuffer) BufferEmpty(1);
6453 
6454  Int_t firstbin = 1, lastbin = nbins;
6455  TString opt = option;
6456  opt.ToLower();
6457  if (opt.Contains("r")) {
6458  firstbin= fXaxis.GetFirst();
6459  lastbin = fXaxis.GetLast();
6460  }
6461  nbins = lastbin - firstbin + 1;
6462  Double_t *xx = new Double_t[nbins];
6463  Double_t nent = fEntries;
6464  Int_t i;
6465  for (i=0;i<nbins;i++) {
6466  xx[i] = RetrieveBinContent(i+firstbin);
6467  }
6468 
6469  TH1::SmoothArray(nbins,xx,ntimes);
6470 
6471  for (i=0;i<nbins;i++) {
6472  UpdateBinContent(i+firstbin,xx[i]);
6473  }
6474  fEntries = nent;
6475  delete [] xx;
6476 
6477  if (gPad) gPad->Modified();
6478 }
6479 
6480 
6481 ////////////////////////////////////////////////////////////////////////////////
6482 /// if flag=kTRUE, underflows and overflows are used by the Fill functions
6483 /// in the computation of statistics (mean value, StdDev).
6484 /// By default, underflows or overflows are not used.
6485 
6486 void TH1::StatOverflows(Bool_t flag)
6488  fgStatOverflows = flag;
6489 }
6490 
6491 
6492 ////////////////////////////////////////////////////////////////////////////////
6493 /// Stream a class object.
6494 
6495 void TH1::Streamer(TBuffer &b)
6496 {
6497  if (b.IsReading()) {
6498  UInt_t R__s, R__c;
6499  Version_t R__v = b.ReadVersion(&R__s, &R__c);
6500  if (fDirectory) fDirectory->Remove(this);
6501  fDirectory = 0;
6502  if (R__v > 2) {
6503  b.ReadClassBuffer(TH1::Class(), this, R__v, R__s, R__c);
6504 
6506  fXaxis.SetParent(this);
6507  fYaxis.SetParent(this);
6508  fZaxis.SetParent(this);
6510  TObject *obj;
6511  while ((obj=next())) {
6512  if (obj->InheritsFrom(TF1::Class())) ((TF1*)obj)->SetParent(this);
6513  }
6514  return;
6515  }
6516  //process old versions before automatic schema evolution
6517  TNamed::Streamer(b);
6518  TAttLine::Streamer(b);
6519  TAttFill::Streamer(b);
6520  TAttMarker::Streamer(b);
6521  b >> fNcells;
6522  fXaxis.Streamer(b);
6523  fYaxis.Streamer(b);
6524  fZaxis.Streamer(b);
6525  fXaxis.SetParent(this);
6526  fYaxis.SetParent(this);
6527  fZaxis.SetParent(this);
6528  b >> fBarOffset;
6529  b >> fBarWidth;
6530  b >> fEntries;
6531  b >> fTsumw;
6532  b >> fTsumw2;
6533  b >> fTsumwx;
6534  b >> fTsumwx2;
6535  if (R__v < 2) {
6536  Float_t maximum, minimum, norm;
6537  Float_t *contour=0;
6538  b >> maximum; fMaximum = maximum;
6539  b >> minimum; fMinimum = minimum;
6540  b >> norm; fNormFactor = norm;
6541  Int_t n = b.ReadArray(contour);
6542  fContour.Set(n);
6543  for (Int_t i=0;i<n;i++) fContour.fArray[i] = contour[i];
6544  delete [] contour;
6545  } else {
6546  b >> fMaximum;
6547  b >> fMinimum;
6548  b >> fNormFactor;
6549  fContour.Streamer(b);
6550  }
6551  fSumw2.Streamer(b);
6552  fOption.Streamer(b);
6553  fFunctions->Delete();
6554  fFunctions->Streamer(b);
6555  b.CheckByteCount(R__s, R__c, TH1::IsA());
6556 
6557  } else {
6558  b.WriteClassBuffer(TH1::Class(),this);
6559  }
6560 }
6561 
6562 
6563 ////////////////////////////////////////////////////////////////////////////////
6564 /// Print some global quantities for this histogram.
6565 /// \param[in] option
6566 /// - "base" is given, number of bins and ranges are also printed
6567 /// - "range" is given, bin contents and errors are also printed
6568 /// for all bins in the current range (default 1-->nbins)
6569 /// - "all" is given, bin contents and errors are also printed
6570 /// for all bins including under and overflows.
6571 
6572 void TH1::Print(Option_t *option) const
6574  if (fBuffer) const_cast<TH1*>(this)->BufferEmpty();
6575  printf( "TH1.Print Name = %s, Entries= %d, Total sum= %g\n",GetName(),Int_t(fEntries),GetSumOfWeights());
6576  TString opt = option;
6577  opt.ToLower();
6578  Int_t all;
6579  if (opt.Contains("all")) all = 0;
6580  else if (opt.Contains("range")) all = 1;
6581  else if (opt.Contains("base")) all = 2;
6582  else return;
6583 
6584  Int_t bin, binx, biny, binz;
6585  Int_t firstx=0,lastx=0,firsty=0,lasty=0,firstz=0,lastz=0;
6586  if (all == 0) {
6587  lastx = fXaxis.GetNbins()+1;
6588  if (fDimension > 1) lasty = fYaxis.GetNbins()+1;
6589  if (fDimension > 2) lastz = fZaxis.GetNbins()+1;
6590  } else {
6591  firstx = fXaxis.GetFirst(); lastx = fXaxis.GetLast();
6592  if (fDimension > 1) {firsty = fYaxis.GetFirst(); lasty = fYaxis.GetLast();}
6593  if (fDimension > 2) {firstz = fZaxis.GetFirst(); lastz = fZaxis.GetLast();}
6594  }
6595 
6596  if (all== 2) {
6597  printf(" Title = %s\n", GetTitle());
6598  printf(" NbinsX= %d, xmin= %g, xmax=%g", fXaxis.GetNbins(), fXaxis.GetXmin(), fXaxis.GetXmax());
6599  if( fDimension > 1) printf(", NbinsY= %d, ymin= %g, ymax=%g", fYaxis.GetNbins(), fYaxis.GetXmin(), fYaxis.GetXmax());
6600  if( fDimension > 2) printf(", NbinsZ= %d, zmin= %g, zmax=%g", fZaxis.GetNbins(), fZaxis.GetXmin(), fZaxis.GetXmax());
6601  printf("\n");
6602  return;
6603  }
6604 
6605  Double_t w,e;
6606  Double_t x,y,z;
6607  if (fDimension == 1) {
6608  for (binx=firstx;binx<=lastx;binx++) {
6609  x = fXaxis.GetBinCenter(binx);
6610  w = RetrieveBinContent(binx);
6611  e = GetBinError(binx);
6612  if(fSumw2.fN) printf(" fSumw[%d]=%g, x=%g, error=%g\n",binx,w,x,e);
6613  else printf(" fSumw[%d]=%g, x=%g\n",binx,w,x);
6614  }
6615  }
6616  if (fDimension == 2) {
6617  for (biny=firsty;biny<=lasty;biny++) {
6618  y = fYaxis.GetBinCenter(biny);
6619  for (binx=firstx;binx<=lastx;binx++) {
6620  bin = GetBin(binx,biny);
6621  x = fXaxis.GetBinCenter(binx);
6622  w = RetrieveBinContent(bin);
6623  e = GetBinError(bin);
6624  if(fSumw2.fN) printf(" fSumw[%d][%d]=%g, x=%g, y=%g, error=%g\n",binx,biny,w,x,y,e);
6625  else printf(" fSumw[%d][%d]=%g, x=%g, y=%g\n",binx,biny,w,x,y);
6626  }
6627  }
6628  }
6629  if (fDimension == 3) {
6630  for (binz=firstz;binz<=lastz;binz++) {
6631  z = fZaxis.GetBinCenter(binz);
6632  for (biny=firsty;biny<=lasty;biny++) {
6633  y = fYaxis.GetBinCenter(biny);
6634  for (binx=firstx;binx<=lastx;binx++) {
6635  bin = GetBin(binx,biny,binz);
6636  x = fXaxis.GetBinCenter(binx);
6637  w = RetrieveBinContent(bin);
6638  e = GetBinError(bin);
6639  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);
6640  else printf(" fSumw[%d][%d][%d]=%g, x=%g, y=%g, z=%g\n",binx,biny,binz,w,x,y,z);
6641  }
6642  }
6643  }
6644  }
6645 }
6646 
6647 
6648 ////////////////////////////////////////////////////////////////////////////////
6649 /// Using the current bin info, recompute the arrays for contents and errors
6650 
6651 void TH1::Rebuild(Option_t *)
6653  SetBinsLength();
6654  if (fSumw2.fN) {
6655  fSumw2.Set(fNcells);
6656  }
6657 }
6658 
6659 
6660 ////////////////////////////////////////////////////////////////////////////////
6661 /// Reset this histogram: contents, errors, etc.
6662 /// \param[in] option
6663 /// - "ICE" is specified, resets only Integral, Contents and Errors.
6664 /// - "ICES" is specified, resets only Integral, Contents , Errors and Statistics
6665 /// This option is used
6666 /// - "M" is specified, resets also Minimum and Maximum
6667 
6668 void TH1::Reset(Option_t *option)
6670  // The option "ICE" is used when extending the histogram (in ExtendAxis, LabelInflate, etc..)
6671  // The option "ICES is used in combination with the buffer (see BufferEmpty and BufferFill)
6672 
6673  TString opt = option;
6674  opt.ToUpper();
6675  fSumw2.Reset();
6676  if (fIntegral) {delete [] fIntegral; fIntegral = 0;}
6677 
6678  if (opt.Contains("M")) {
6679  SetMinimum();
6680  SetMaximum();
6681  }
6682 
6683  if (opt.Contains("ICE") && !opt.Contains("S")) return;
6684 
6685  // Setting fBuffer[0] = 0 is like resetting the buffer but not deleting it
6686  // But what is the sense of calling BufferEmpty() ? For making the axes ?
6687  // BufferEmpty will update contents that later will be
6688  // reset in calling TH1D::Reset. For this we need to reset the stats afterwards
6689  // It may be needed for computing the axis limits....
6690  if (fBuffer) {BufferEmpty(); fBuffer[0] = 0;}
6691 
6692  // need to reset also the statistics
6693  // (needs to be done after calling BufferEmpty() )
6694  fTsumw = 0;
6695  fTsumw2 = 0;
6696  fTsumwx = 0;
6697  fTsumwx2 = 0;
6698  fEntries = 0;
6699 
6700  if (opt == "ICES") return;
6701 
6702 
6703  TObject *stats = fFunctions->FindObject("stats");
6704  fFunctions->Remove(stats);
6705  //special logic to support the case where the same object is
6706  //added multiple times in fFunctions.
6707  //This case happens when the same object is added with different
6708  //drawing modes
6709  TObject *obj;
6710  while ((obj = fFunctions->First())) {
6711  while(fFunctions->Remove(obj)) { }
6712  delete obj;
6713  }
6714  if(stats) fFunctions->Add(stats);
6715  fContour.Set(0);
6716 }
6717 
6718 
6719 ////////////////////////////////////////////////////////////////////////////////
6720 /// Save primitive as a C++ statement(s) on output stream out
6721 
6722 void TH1::SavePrimitive(std::ostream &out, Option_t *option /*= ""*/)
6724  // empty the buffer before if it exists
6725  if (fBuffer) BufferEmpty();
6726 
6727  Bool_t nonEqiX = kFALSE;
6728  Bool_t nonEqiY = kFALSE;
6729  Bool_t nonEqiZ = kFALSE;
6730  Int_t i;
6731  static Int_t nxaxis = 0;
6732  static Int_t nyaxis = 0;
6733  static Int_t nzaxis = 0;
6734  TString sxaxis="xAxis",syaxis="yAxis",szaxis="zAxis";
6735 
6736  // Check if the histogram has equidistant X bins or not. If not, we
6737  // create an array holding the bins.
6738  if (GetXaxis()->GetXbins()->fN && GetXaxis()->GetXbins()->fArray) {
6739  nonEqiX = kTRUE;
6740  nxaxis++;
6741  sxaxis += nxaxis;
6742  out << " Double_t "<<sxaxis<<"[" << GetXaxis()->GetXbins()->fN
6743  << "] = {";
6744  for (i = 0; i < GetXaxis()->GetXbins()->fN; i++) {
6745  if (i != 0) out << ", ";
6746  out << GetXaxis()->GetXbins()->fArray[i];
6747  }
6748  out << "}; " << std::endl;
6749  }
6750  // If the histogram is 2 or 3 dimensional, check if the histogram
6751  // has equidistant Y bins or not. If not, we create an array
6752  // holding the bins.
6753  if (fDimension > 1 && GetYaxis()->GetXbins()->fN &&
6754  GetYaxis()->GetXbins()->fArray) {
6755  nonEqiY = kTRUE;
6756  nyaxis++;
6757  syaxis += nyaxis;
6758  out << " Double_t "<<syaxis<<"[" << GetYaxis()->GetXbins()->fN
6759  << "] = {";
6760  for (i = 0; i < GetYaxis()->GetXbins()->fN; i++) {
6761  if (i != 0) out << ", ";
6762  out << GetYaxis()->GetXbins()->fArray[i];
6763  }
6764  out << "}; " << std::endl;
6765  }
6766  // IF the histogram is 3 dimensional, check if the histogram
6767  // has equidistant Z bins or not. If not, we create an array
6768  // holding the bins.
6769  if (fDimension > 2 && GetZaxis()->GetXbins()->fN &&
6770  GetZaxis()->GetXbins()->fArray) {
6771  nonEqiZ = kTRUE;
6772  nzaxis++;
6773  szaxis += nzaxis;
6774  out << " Double_t "<<szaxis<<"[" << GetZaxis()->GetXbins()->fN
6775  << "] = {";
6776  for (i = 0; i < GetZaxis()->GetXbins()->fN; i++) {
6777  if (i != 0) out << ", ";
6778  out << GetZaxis()->GetXbins()->fArray[i];
6779  }
6780  out << "}; " << std::endl;
6781  }
6782 
6783  char quote = '"';
6784  out <<" "<<std::endl;
6785  out <<" "<< ClassName() <<" *";
6786 
6787  // Histogram pointer has by default the histogram name with an incremental suffix.
6788  // If the histogram belongs to a graph or a stack the suffix is not added because
6789  // the graph and stack objects are not aware of this new name. Same thing if
6790  // the histogram is drawn with the option COLZ because the TPaletteAxis drawn
6791  // when this option is selected, does not know this new name either.
6792  TString opt = option;
6793  opt.ToLower();
6794  static Int_t hcounter = 0;
6795  TString histName = GetName();
6796  if ( !histName.Contains("Graph")
6797  && !histName.Contains("_stack_")
6798  && !opt.Contains("colz")) {
6799  hcounter++;
6800  histName += "__";
6801  histName += hcounter;
6802  }
6803  histName = gInterpreter-> MapCppName(histName);
6804  const char *hname = histName.Data();
6805  if (!strlen(hname)) hname = "unnamed";
6806 
6807  TString t(GetTitle());
6808  t.ReplaceAll("\\","\\\\");
6809  t.ReplaceAll("\"","\\\"");
6810  out << hname << " = new " << ClassName() << "(" << quote
6811  << hname << quote << "," << quote<< t.Data() << quote
6812  << "," << GetXaxis()->GetNbins();
6813  if (nonEqiX)
6814  out << ", "<<sxaxis;
6815  else
6816  out << "," << GetXaxis()->GetXmin()
6817  << "," << GetXaxis()->GetXmax();
6818  if (fDimension > 1) {
6819  out << "," << GetYaxis()->GetNbins();
6820  if (nonEqiY)
6821  out << ", "<<syaxis;
6822  else
6823  out << "," << GetYaxis()->GetXmin()
6824  << "," << GetYaxis()->GetXmax();
6825  }
6826  if (fDimension > 2) {
6827  out << "," << GetZaxis()->GetNbins();
6828  if (nonEqiZ)
6829  out << ", "<<szaxis;
6830  else
6831  out << "," << GetZaxis()->GetXmin()
6832  << "," << GetZaxis()->GetXmax();
6833  }
6834  out << ");" << std::endl;
6835 
6836  // save bin contents
6837  Int_t bin;
6838  for (bin=0;bin<fNcells;bin++) {
6839  Double_t bc = RetrieveBinContent(bin);
6840  if (bc) {
6841  out<<" "<<hname<<"->SetBinContent("<<bin<<","<<bc<<");"<<std::endl;
6842  }
6843  }
6844 
6845  // save bin errors
6846  if (fSumw2.fN) {
6847  for (bin=0;bin<fNcells;bin++) {
6848  Double_t be = GetBinError(bin);
6849  if (be) {
6850  out<<" "<<hname<<"->SetBinError("<<bin<<","<<be<<");"<<std::endl;
6851  }
6852  }
6853  }
6854 
6855  TH1::SavePrimitiveHelp(out, hname, option);
6856 }
6857 
6858 
6859 ////////////////////////////////////////////////////////////////////////////////
6860 /// helper function for the SavePrimitive functions from TH1
6861 /// or classes derived from TH1, eg TProfile, TProfile2D.
6862 
6863 void TH1::SavePrimitiveHelp(std::ostream &out, const char *hname, Option_t *option /*= ""*/)
6865  char quote = '"';
6866  if (TMath::Abs(GetBarOffset()) > 1e-5) {
6867  out<<" "<<hname<<"->SetBarOffset("<<GetBarOffset()<<");"<<std::endl;
6868  }
6869  if (TMath::Abs(GetBarWidth()-1) > 1e-5) {
6870  out<<" "<<hname<<"->SetBarWidth("<<GetBarWidth()<<");"<<std::endl;
6871  }
6872  if (fMinimum != -1111) {
6873  out<<" "<<hname<<"->SetMinimum("<<fMinimum<<");"<<std::endl;
6874  }
6875  if (fMaximum != -1111) {
6876  out<<" "<<hname<<"->SetMaximum("<<fMaximum<<");"<<std::endl;
6877  }
6878  if (fNormFactor != 0) {
6879  out<<" "<<hname<<"->SetNormFactor("<<fNormFactor<<");"<<std::endl;
6880  }
6881  if (fEntries != 0) {
6882  out<<" "<<hname<<"->SetEntries("<<fEntries<<");"<<std::endl;
6883  }
6884  if (fDirectory == 0) {
6885  out<<" "<<hname<<"->SetDirectory(0);"<<std::endl;
6886  }
6887  if (TestBit(kNoStats)) {
6888  out<<" "<<hname<<"->SetStats(0);"<<std::endl;
6889  }
6890  if (fOption.Length() != 0) {
6891  out<<" "<<hname<<"->SetOption("<<quote<<fOption.Data()<<quote<<");"<<std::endl;
6892  }
6893 
6894  // save contour levels
6895  Int_t ncontours = GetContour();
6896  if (ncontours > 0) {
6897  out<<" "<<hname<<"->SetContour("<<ncontours<<");"<<std::endl;
6898  Double_t zlevel;
6899  for (Int_t bin=0;bin<ncontours;bin++) {
6900  if (gPad->GetLogz()) {
6901  zlevel = TMath::Power(10,GetContourLevel(bin));
6902  } else {
6903  zlevel = GetContourLevel(bin);
6904  }
6905  out<<" "<<hname<<"->SetContourLevel("<<bin<<","<<zlevel<<");"<<std::endl;
6906  }
6907  }
6908 
6909  // save list of functions
6911  TObject *obj;
6912  static Int_t funcNumber = 0;
6913  while (lnk) {
6914  obj = lnk->GetObject();
6915  obj->SavePrimitive(out,Form("nodraw #%d\n",++funcNumber));
6916  if (obj->InheritsFrom(TF1::Class())) {
6917  out<<" "<<hname<<"->GetListOfFunctions()->Add("
6918  <<Form("%s%d",obj->GetName(),funcNumber)<<");"<<std::endl;
6919  } else if (obj->InheritsFrom("TPaveStats")) {
6920  out<<" "<<hname<<"->GetListOfFunctions()->Add(ptstats);"<<std::endl;
6921  out<<" ptstats->SetParent("<<hname<<");"<<std::endl;
6922  } else {
6923  out<<" "<<hname<<"->GetListOfFunctions()->Add("
6924  <<obj->GetName()
6925  <<","<<quote<<lnk->GetOption()<<quote<<");"<<std::endl;
6926  }
6927  lnk = (TObjOptLink*)lnk->Next();
6928  }
6929 
6930  // save attributes
6931  SaveFillAttributes(out,hname,0,1001);
6932  SaveLineAttributes(out,hname,1,1,1);
6933  SaveMarkerAttributes(out,hname,1,1,1);
6934  fXaxis.SaveAttributes(out,hname,"->GetXaxis()");
6935  fYaxis.SaveAttributes(out,hname,"->GetYaxis()");
6936  fZaxis.SaveAttributes(out,hname,"->GetZaxis()");
6937  TString opt = option;
6938  opt.ToLower();
6939  if (!opt.Contains("nodraw")) {
6940  out<<" "<<hname<<"->Draw("
6941  <<quote<<option<<quote<<");"<<std::endl;
6942  }
6943 }
6944 
6945 
6946 ////////////////////////////////////////////////////////////////////////////////
6947 ///Copy current attributes from/to current style
6948 
6949 void TH1::UseCurrentStyle()
6951  if (!gStyle) return;
6952  if (gStyle->IsReading()) {
6953  fXaxis.ResetAttAxis("X");
6954  fYaxis.ResetAttAxis("Y");
6955  fZaxis.ResetAttAxis("Z");
6966  Int_t dostat = gStyle->GetOptStat();
6967  if (gStyle->GetOptFit() && !dostat) dostat = 1000000001;
6968  SetStats(dostat);
6969  } else {
6970  gStyle->SetBarOffset(fBarOffset);
6971  gStyle->SetBarWidth(fBarWidth);
6981  }
6983  TObject *obj;
6984 
6985  while ((obj = next())) {
6986  obj->UseCurrentStyle();
6987  }
6988 }
6989 
6990 
6991 ////////////////////////////////////////////////////////////////////////////////
6992 /// For axis = 1,2 or 3 returns the mean value of the histogram along
6993 /// X,Y or Z axis.
6994 /// For axis = 11, 12, 13 returns the standard error of the mean value
6995 /// of the histogram along X, Y or Z axis
6996 ///
6997 /// Note that the mean value/StdDev is computed using the bins in the currently
6998 /// defined range (see TAxis::SetRange). By default the range includes
6999 /// all bins from 1 to nbins included, excluding underflows and overflows.
7000 /// To force the underflows and overflows in the computation, one must
7001 /// call the static function TH1::StatOverflows(kTRUE) before filling
7002 /// the histogram.
7003 ///
7004 /// Return mean value of this histogram along the X axis.
7005 ///
7006 /// Note that the mean value/StdDev is computed using the bins in the currently
7007 /// defined range (see TAxis::SetRange). By default the range includes
7008 /// all bins from 1 to nbins included, excluding underflows and overflows.
7009 /// To force the underflows and overflows in the computation, one must
7010 /// call the static function TH1::StatOverflows(kTRUE) before filling
7011 /// the histogram.
7012 
7015  if (axis<1 || (axis>3 && axis<11) || axis>13) return 0;
7016  Double_t stats[kNstat];
7017  for (Int_t i=4;i<kNstat;i++) stats[i] = 0;
7018  GetStats(stats);
7019  if (stats[0] == 0) return 0;
7020  if (axis<4){
7021  Int_t ax[3] = {2,4,7};
7022  return stats[ax[axis-1]]/stats[0];
7023  } else {
7024  // mean error = StdDev / sqrt( Neff )
7025  Double_t stddev = GetStdDev(axis-10);
7026  Double_t neff = GetEffectiveEntries();
7027  return ( neff > 0 ? stddev/TMath::Sqrt(neff) : 0. );
7028  }
7029 }
7030 
7031 
7032 ////////////////////////////////////////////////////////////////////////////////
7033 /// Return standard error of mean of this histogram along the X axis.
7034 ///
7035 /// Note that the mean value/StdDev is computed using the bins in the currently
7036 /// defined range (see TAxis::SetRange). By default the range includes
7037 /// all bins from 1 to nbins included, excluding underflows and overflows.
7038 /// To force the underflows and overflows in the computation, one must
7039 /// call the static function TH1::StatOverflows(kTRUE) before filling
7040 /// the histogram.
7041 /// Also note, that although the definition of standard error doesn't include the
7042 /// assumption of normality, many uses of this feature implicitly assume it.
7043 
7046  return GetMean(axis+10);
7047 }
7048 
7049 
7050 ////////////////////////////////////////////////////////////////////////////////
7051 /// Returns the Standard Deviation (Sigma).
7052 /// The Sigma estimate is computed as Sqrt((1/N)*(Sum(x_i-x_mean)^2))
7053 ///
7054 /// For axis = 1,2 or 3 returns the Sigma value of the histogram along
7055 /// X, Y or Z axis
7056 /// For axis = 11, 12 or 13 returns the error of StdDev estimation along
7057 /// X, Y or Z axis for Normal distribution
7058 ///
7059 /// Note that the mean value/sigma is computed using the bins in the currently
7060 /// defined range (see TAxis::SetRange). By default the range includes
7061 /// all bins from 1 to nbins included, excluding underflows and overflows.
7062 /// To force the underflows and overflows in the computation, one must
7063 /// call the static function TH1::StatOverflows(kTRUE) before filling
7064 /// the histogram.
7065 
7068  if (axis<1 || (axis>3 && axis<11) || axis>13) return 0;
7069 
7070  Double_t x, stddev2, stats[kNstat];
7071  for (Int_t i=4;i<kNstat;i++) stats[i] = 0;
7072  GetStats(stats);
7073  if (stats[0] == 0) return 0;
7074  Int_t ax[3] = {2,4,7};
7075  Int_t axm = ax[axis%10 - 1];
7076  x = stats[axm]/stats[0];
7077  stddev2 = TMath::Abs(stats[axm+1]/stats[0] -x*x);
7078  if (axis<10)
7079  return TMath::Sqrt(stddev2);
7080  else {
7081  // The right formula for StdDev error depends on 4th momentum (see Kendall-Stuart Vol 1 pag 243)
7082  // formula valid for only gaussian distribution ( 4-th momentum = 3 * sigma^4 )
7083  Double_t neff = GetEffectiveEntries();
7084  return ( neff > 0 ? TMath::Sqrt(stddev2/(2*neff) ) : 0. );
7085  }
7086 }
7087 
7088 
7089 ////////////////////////////////////////////////////////////////////////////////
7090 /// Return error of standard deviation estimation for Normal distribution
7091 ///
7092 /// Note that the mean value/StdDev is computed using the bins in the currently
7093 /// defined range (see TAxis::SetRange). By default the range includes
7094 /// all bins from 1 to nbins included, excluding underflows and overflows.
7095 /// To force the underflows and overflows in the computation, one must
7096 /// call the static function TH1::StatOverflows(kTRUE) before filling
7097 /// the histogram.
7098 /// Value returned is standard deviation of sample standard deviation.
7099 /// Note that it is an approximated value which is valid only in the case that the
7100 /// original data distribution is Normal. The correct one would require
7101 /// the 4-th momentum value, which cannot be accurately estimated from an histogram since
7102 /// the x-information for all entries is not kept.
7103 
7106  return GetStdDev(axis+10);
7107 }
7108 
7109 
7110 ////////////////////////////////////////////////////////////////////////////////
7111 ///For axis = 1, 2 or 3 returns skewness of the histogram along x, y or z axis.
7112 ///For axis = 11, 12 or 13 returns the approximate standard error of skewness
7113 ///of the histogram along x, y or z axis
7114 ///Note, that since third and fourth moment are not calculated
7115 ///at the fill time, skewness and its standard error are computed bin by bin
7116 
7119 
7120  if (axis > 0 && axis <= 3){
7121 
7122  Double_t mean = GetMean(axis);
7123  Double_t stddev = GetStdDev(axis);
7124  Double_t stddev3 = stddev*stddev*stddev;
7125 
7126  Int_t firstBinX = fXaxis.GetFirst();
7127  Int_t lastBinX = fXaxis.GetLast();
7128  Int_t firstBinY = fYaxis.GetFirst();
7129  Int_t lastBinY = fYaxis.GetLast();
7130  Int_t firstBinZ = fZaxis.GetFirst();
7131  Int_t lastBinZ = fZaxis.GetLast();
7132  // include underflow/overflow if TH1::StatOverflows(kTRUE) in case no range is set on the axis
7133  if (fgStatOverflows) {
7134  if ( !fXaxis.TestBit(TAxis::kAxisRange) ) {
7135  if (firstBinX == 1) firstBinX = 0;
7136  if (lastBinX == fXaxis.GetNbins() ) lastBinX += 1;
7137  }
7138  if ( !fYaxis.TestBit(TAxis::kAxisRange) ) {
7139  if (firstBinY == 1) firstBinY = 0;
7140  if (lastBinY == fYaxis.GetNbins() ) lastBinY += 1;
7141  }
7142  if ( !fZaxis.TestBit(TAxis::kAxisRange) ) {
7143  if (firstBinZ == 1) firstBinZ = 0;
7144  if (lastBinZ == fZaxis.GetNbins() ) lastBinZ += 1;
7145  }
7146  }
7147 
7148  Double_t x = 0;
7149  Double_t sum=0;
7150  Double_t np=0;
7151  for (Int_t binx = firstBinX; binx <= lastBinX; binx++) {
7152  for (Int_t biny = firstBinY; biny <= lastBinY; biny++) {
7153  for (Int_t binz = firstBinZ; binz <= lastBinZ; binz++) {
7154  if (axis==1 ) x = fXaxis.GetBinCenter(binx);
7155  else if (axis==2 ) x = fYaxis.GetBinCenter(biny);
7156  else if (axis==3 ) x = fZaxis.GetBinCenter(binz);
7157  Double_t w = GetBinContent(binx,biny,binz);
7158  np+=w;
7159  sum+=w*(x-mean)*(x-mean)*(x-mean);
7160  }
7161  }
7162  }
7163  sum/=np*stddev3;
7164  return sum;
7165  }
7166  else if (axis > 10 && axis <= 13) {
7167  //compute standard error of skewness
7168  // assume parent normal distribution use formula from Kendall-Stuart, Vol 1 pag 243, second edition
7169  Double_t neff = GetEffectiveEntries();
7170  return ( neff > 0 ? TMath::Sqrt(6./neff ) : 0. );
7171  }
7172  else {
7173  Error("GetSkewness", "illegal value of parameter");
7174  return 0;
7175  }
7176 }
7177 
7178 
7179 ////////////////////////////////////////////////////////////////////////////////
7180 ///For axis =1, 2 or 3 returns kurtosis of the histogram along x, y or z axis.
7181 ///Kurtosis(gaussian(0, 1)) = 0.
7182 ///For axis =11, 12 or 13 returns the approximate standard error of kurtosis
7183 ///of the histogram along x, y or z axis
7184 ///Note, that since third and fourth moment are not calculated
7185 ///at the fill time, kurtosis and its standard error are computed bin by bin
7186 
7189  if (axis > 0 && axis <= 3){
7190 
7191  Double_t mean = GetMean(axis);
7192  Double_t stddev = GetStdDev(axis);
7193  Double_t stddev4 = stddev*stddev*stddev*stddev;
7194 
7195  Int_t firstBinX = fXaxis.GetFirst();
7196  Int_t lastBinX = fXaxis.GetLast();
7197  Int_t firstBinY = fYaxis.GetFirst();
7198  Int_t lastBinY = fYaxis.GetLast();
7199  Int_t firstBinZ = fZaxis.GetFirst();
7200  Int_t lastBinZ = fZaxis.GetLast();
7201  // include underflow/overflow if TH1::StatOverflows(kTRUE) in case no range is set on the axis
7202  if (fgStatOverflows) {
7203  if ( !fXaxis.TestBit(TAxis::kAxisRange) ) {
7204  if (firstBinX == 1) firstBinX = 0;
7205  if (lastBinX == fXaxis.GetNbins() ) lastBinX += 1;
7206  }
7207  if ( !fYaxis.TestBit(TAxis::kAxisRange) ) {
7208  if (firstBinY == 1) firstBinY = 0;
7209  if (lastBinY == fYaxis.GetNbins() ) lastBinY += 1;
7210  }
7211  if ( !fZaxis.TestBit(TAxis::kAxisRange) ) {
7212  if (firstBinZ == 1) firstBinZ = 0;
7213  if (lastBinZ == fZaxis.GetNbins() ) lastBinZ += 1;
7214  }
7215  }
7216 
7217  Double_t x = 0;
7218  Double_t sum=0;
7219  Double_t np=0;
7220  for (Int_t binx = firstBinX; binx <= lastBinX; binx++) {
7221  for (Int_t biny = firstBinY; biny <= lastBinY; biny++) {
7222  for (Int_t binz = firstBinZ; binz <= lastBinZ; binz++) {
7223  if (axis==1 ) x = fXaxis.GetBinCenter(binx);
7224  else if (axis==2 ) x = fYaxis.GetBinCenter(biny);
7225  else if (axis==3 ) x = fZaxis.GetBinCenter(binz);
7226  Double_t w = GetBinContent(binx,biny,binz);
7227  np+=w;
7228  sum+=w*(x-mean)*(x-mean)*(x-mean)*(x-mean);
7229  }
7230  }
7231  }
7232  sum/=(np*stddev4);
7233  return sum-3;
7234 
7235  } else if (axis > 10 && axis <= 13) {
7236  //compute standard error of skewness
7237  // assume parent normal distribution use formula from Kendall-Stuart, Vol 1 pag 243, second edition
7238  Double_t neff = GetEffectiveEntries();
7239  return ( neff > 0 ? TMath::Sqrt(24./neff ) : 0. );
7240  }
7241  else {
7242  Error("GetKurtosis", "illegal value of parameter");
7243  return 0;
7244  }
7245 }
7246 
7247 
7248 ////////////////////////////////////////////////////////////////////////////////
7249 /// fill the array stats from the contents of this histogram
7250 /// The array stats must be correctly dimensioned in the calling program.
7251 ///
7252 /// stats[0] = sumw
7253 /// stats[1] = sumw2
7254 /// stats[2] = sumwx
7255 /// stats[3] = sumwx2
7256 ///
7257 /// If no axis-subrange is specified (via TAxis::SetRange), the array stats
7258 /// is simply a copy of the statistics quantities computed at filling time.
7259 /// If a sub-range is specified, the function recomputes these quantities
7260 /// from the bin contents in the current axis range.
7261 ///
7262 /// Note that the mean value/StdDev is computed using the bins in the currently
7263 /// defined range (see TAxis::SetRange). By default the range includes
7264 /// all bins from 1 to nbins included, excluding underflows and overflows.
7265 /// To force the underflows and overflows in the computation, one must
7266 /// call the static function TH1::StatOverflows(kTRUE) before filling
7267 /// the histogram.
7268 
7269 void TH1::GetStats(Double_t *stats) const
7271  if (fBuffer) ((TH1*)this)->BufferEmpty();
7272 
7273  // Loop on bins (possibly including underflows/overflows)
7274  Int_t bin, binx;
7275  Double_t w,err;
7276  Double_t x;
7277  // case of labels with extension of axis range
7278  // statistics in x does not make any sense - set to zero
7279  if ((const_cast<TAxis&>(fXaxis)).GetLabels() && CanExtendAllAxes() ) {
7280  stats[0] = fTsumw;
7281  stats[1] = fTsumw2;
7282  stats[2] = 0;
7283  stats[3] = 0;
7284  }
7285  else if ((fTsumw == 0 && fEntries > 0) || fXaxis.TestBit(TAxis::kAxisRange)) {
7286  for (bin=0;bin<4;bin++) stats[bin] = 0;
7287 
7288  Int_t firstBinX = fXaxis.GetFirst();
7289  Int_t lastBinX = fXaxis.GetLast();
7290  // include underflow/overflow if TH1::StatOverflows(kTRUE) in case no range is set on the axis
7292  if (firstBinX == 1) firstBinX = 0;
7293  if (lastBinX == fXaxis.GetNbins() ) lastBinX += 1;
7294  }
7295  for (binx = firstBinX; binx <= lastBinX; binx++) {
7296  x = fXaxis.GetBinCenter(binx);
7297  //w = TMath::Abs(RetrieveBinContent(binx));
7298  // not sure what to do here if w < 0
7299  w = RetrieveBinContent(binx);
7300  err = TMath::Abs(GetBinError(binx));
7301  stats[0] += w;
7302  stats[1] += err*err;
7303  stats[2] += w*x;
7304  stats[3] += w*x*x;
7305  }
7306  // if (stats[0] < 0) {
7307  // // in case total is negative do something ??
7308  // stats[0] = 0;
7309  // }
7310  } else {
7311  stats[0] = fTsumw;
7312  stats[1] = fTsumw2;
7313  stats[2] = fTsumwx;
7314  stats[3] = fTsumwx2;
7315  }
7316 }
7317 
7318 
7319 ////////////////////////////////////////////////////////////////////////////////
7320 /// Replace current statistics with the values in array stats
7321 
7322 void TH1::PutStats(Double_t *stats)
7324  fTsumw = stats[0];
7325  fTsumw2 = stats[1];
7326  fTsumwx = stats[2];
7327  fTsumwx2 = stats[3];
7328 }
7329 
7330 
7331 ////////////////////////////////////////////////////////////////////////////////
7332 /// Reset the statistics including the number of entries
7333 /// and replace with values calculates from bin content
7334 /// The number of entries is set to the total bin content or (in case of weighted histogram)
7335 /// to number of effective entries
7336 
7337 void TH1::ResetStats()
7339  Double_t stats[kNstat] = {0};
7340  fTsumw = 0;
7341  fEntries = 1; // to force re-calculation of the statistics in TH1::GetStats
7342  GetStats(stats);
7343  PutStats(stats);
7344  fEntries = TMath::Abs(fTsumw);
7345  // use effective entries for weighted histograms: (sum_w) ^2 / sum_w2
7346  if (fSumw2.fN > 0 && fTsumw > 0 && stats[1] > 0 ) fEntries = stats[0]*stats[0]/ stats[1];
7347 }
7348 
7349 
7350 ////////////////////////////////////////////////////////////////////////////////
7351 /// Return the sum of weights excluding under/overflows.
7352 
7355  if (fBuffer) const_cast<TH1*>(this)->BufferEmpty();
7356 
7357  Int_t bin,binx,biny,binz;
7358  Double_t sum =0;
7359  for(binz=1; binz<=fZaxis.GetNbins(); binz++) {
7360  for(biny=1; biny<=fYaxis.GetNbins(); biny++) {
7361  for(binx=1; binx<=fXaxis.GetNbins(); binx++) {
7362  bin = GetBin(binx,biny,binz);
7363  sum += RetrieveBinContent(bin);
7364  }
7365  }
7366  }
7367  return sum;
7368 }
7369 
7370 
7371 ////////////////////////////////////////////////////////////////////////////////
7372 ///Return integral of bin contents. Only bins in the bins range are considered.
7373 /// By default the integral is computed as the sum of bin contents in the range.
7374 /// if option "width" is specified, the integral is the sum of
7375 /// the bin contents multiplied by the bin width in x.
7376 
7377 Double_t TH1::Integral(Option_t *option) const
7379  return Integral(fXaxis.GetFirst(),fXaxis.GetLast(),option);
7380 }
7381 
7382 
7383 ////////////////////////////////////////////////////////////////////////////////
7384 ///Return integral of bin contents in range [binx1,binx2]
7385 /// By default the integral is computed as the sum of bin contents in the range.
7386 /// if option "width" is specified, the integral is the sum of
7387 /// the bin contents multiplied by the bin width in x.
7388 
7389 Double_t TH1::Integral(Int_t binx1, Int_t binx2, Option_t *option) const
7391  double err = 0;
7392  return DoIntegral(binx1,binx2,0,-1,0,-1,err,option);
7393 }
7394 
7395 
7396 ////////////////////////////////////////////////////////////////////////////////
7397 ///Return integral of bin contents in range [binx1,binx2] and its error
7398 /// By default the integral is computed as the sum of bin contents in the range.
7399 /// if option "width" is specified, the integral is the sum of
7400 /// the bin contents multiplied by the bin width in x.
7401 /// the error is computed using error propagation from the bin errors assumming that
7402 /// all the bins are uncorrelated
7403 
7404 Double_t TH1::IntegralAndError(Int_t binx1, Int_t binx2, Double_t & error, Option_t *option) const
7406  return DoIntegral(binx1,binx2,0,-1,0,-1,error,option,kTRUE);
7407 }
7408 
7409 
7410 ////////////////////////////////////////////////////////////////////////////////
7411 /// internal function compute integral and optionally the error between the limits
7412 /// specified by the bin number values working for all histograms (1D, 2D and 3D)
7413 
7414 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 ,
7415  Option_t *option, Bool_t doError) const
7416 {
7417  if (fBuffer) ((TH1*)this)->BufferEmpty();
7418 
7419  Int_t nx = GetNbinsX() + 2;
7420  if (binx1 < 0) binx1 = 0;
7421  if (binx2 >= nx || binx2 < binx1) binx2 = nx - 1;
7422 
7423  if (GetDimension() > 1) {
7424  Int_t ny = GetNbinsY() + 2;
7425  if (biny1 < 0) biny1 = 0;
7426  if (biny2 >= ny || biny2 < biny1) biny2 = ny - 1;
7427  } else {
7428  biny1 = 0; biny2 = 0;
7429  }
7430 
7431  if (GetDimension() > 2) {
7432  Int_t nz = GetNbinsZ() + 2;
7433  if (binz1 < 0) binz1 = 0;
7434  if (binz2 >= nz || binz2 < binz1) binz2 = nz - 1;
7435  } else {
7436  binz1 = 0; binz2 = 0;
7437  }
7438 
7439  // - Loop on bins in specified range
7440  TString opt = option;
7441  opt.ToLower();
7442  Bool_t width = kFALSE;
7443  if (opt.Contains("width")) width = kTRUE;
7444 
7445 
7446  Double_t dx = 1., dy = .1, dz =.1;
7447  Double_t integral = 0;
7448  Double_t igerr2 = 0;
7449  for (Int_t binx = binx1; binx <= binx2; ++binx) {
7450  if (width) dx = fXaxis.GetBinWidth(binx);
7451  for (Int_t biny = biny1; biny <= biny2; ++biny) {
7452  if (width) dy = fYaxis.GetBinWidth(biny);
7453  for (Int_t binz = binz1; binz <= binz2; ++binz) {
7454  Int_t bin = GetBin(binx, biny, binz);
7455  Double_t dv = 0.0;
7456  if (width) {
7457  dz = fZaxis.GetBinWidth(binz);
7458  dv = dx * dy * dz;
7459  integral += RetrieveBinContent(bin) * dv;
7460  } else {
7461  integral += RetrieveBinContent(bin);
7462  }
7463  if (doError) {
7464  if (width) igerr2 += GetBinErrorSqUnchecked(bin) * dv * dv;
7465  else igerr2 += GetBinErrorSqUnchecked(bin);
7466  }
7467  }
7468  }
7469  }
7470 
7471  if (doError) error = TMath::Sqrt(igerr2);
7472  return integral;
7473 }
7474 
7475 
7476 ////////////////////////////////////////////////////////////////////////////////
7477 /// Statistical test of compatibility in shape between
7478 /// this histogram and h2, using the Anderson-Darling 2 sample test.
7479 /// The AD 2 sample test formula are derived from the paper
7480 /// F.W Scholz, M.A. Stephens "k-Sample Anderson-Darling Test".
7481 /// The test is implemented in root in the ROOT::Math::GoFTest class
7482 /// It is the same formula ( (6) in the paper), and also shown in this preprint
7483 /// http://arxiv.org/pdf/0804.0380v1.pdf
7484 /// Binned data are considered as un-binned data
7485 /// with identical observation happening in the bin center.
7486 ///
7487 /// \param[in] option is a character string to specify options
7488 /// - "D" Put out a line of "Debug" printout
7489 /// - "T" Return the normalized A-D test statistic
7490 ///
7491 /// - Note1: Underflow and overflow are not considered in the test
7492 /// - Note2: The test works only for un-weighted histogram (i.e. representing counts)
7493 /// - Note3: The histograms are not required to have the same X axis
7494 /// - Note4: The test works only for 1-dimensional histograms
7495 
7496 Double_t TH1::AndersonDarlingTest(const TH1 *h2, Option_t *option) const
7498  Double_t advalue = 0;
7499  Double_t pvalue = AndersonDarlingTest(h2, advalue);
7500 
7501  TString opt = option;
7502  opt.ToUpper();
7503  if (opt.Contains("D") ) {
7504  printf(" AndersonDarlingTest Prob = %g, AD TestStatistic = %g\n",pvalue,advalue);
7505  }
7506  if (opt.Contains("T") ) return advalue;
7507 
7508  return pvalue;
7509 }
7510 
7511 ////////////////////////////////////////////////////////////////////////////////
7512 /// Same funciton as above but returning also the test statistic value
7513 
7514 Double_t TH1::AndersonDarlingTest(const TH1 *h2, Double_t & advalue) const
7516  if (GetDimension() != 1 || h2->GetDimension() != 1) {
7517  Error("AndersonDarlingTest","Histograms must be 1-D");
7518  return -1;
7519  }
7520 
7521  // empty the buffer. Probably we could add as an unbinned test
7522  if (fBuffer) ((TH1*)this)->BufferEmpty();
7523 
7524  // use the BinData class
7525  ROOT::Fit::BinData data1;
7526  ROOT::Fit::BinData data2;
7527 
7528  ROOT::Fit::FillData(data1, this, 0);
7529  ROOT::Fit::FillData(data2, h2, 0);
7530 
7531  double pvalue;
7532  ROOT::Math::GoFTest::AndersonDarling2SamplesTest(data1,data2, pvalue,advalue);
7533 
7534  return pvalue;
7535 }
7536 
7537 ////////////////////////////////////////////////////////////////////////////////
7538 /// Statistical test of compatibility in shape between
7539 /// this histogram and h2, using Kolmogorov test.
7540 /// Note that the KolmogorovTest (KS) test should in theory be used only for unbinned data
7541 /// and not for binned data as in the case of the histogram (see NOTE 3 below).
7542 /// So, before using this method blindly, read the NOTE 3.
7543 ///
7544 /// Default: Ignore under- and overflow bins in comparison
7545 ///
7546 /// \param[in] option is a character string to specify options
7547 /// - "U" include Underflows in test (also for 2-dim)
7548 /// - "O" include Overflows (also valid for 2-dim)
7549 /// - "N" include comparison of normalizations
7550 /// - "D" Put out a line of "Debug" printout
7551 /// - "M" Return the Maximum Kolmogorov distance instead of prob
7552 /// - "X" Run the pseudo experiments post-processor with the following procedure:
7553 /// make pseudoexperiments based on random values from the parent
7554 /// distribution and compare the KS distance of the pseudoexperiment
7555 /// to the parent distribution. Bin the KS distances in a histogram,
7556 /// and then take the integral of all the KS values above the value
7557 /// obtained from the original data to Monte Carlo distribution.
7558 /// The number of pseudo-experiments nEXPT is currently fixed at 1000.
7559 /// The function returns the integral.
7560 /// (thanks to Ben Kilminster to submit this procedure). Note that
7561 /// this option "X" is much slower.
7562 ///
7563 /// The returned function value is the probability of test
7564 /// (much less than one means NOT compatible)
7565 ///
7566 /// Code adapted by Rene Brun from original HBOOK routine HDIFF
7567 ///
7568 /// NOTE1
7569 /// A good description of the Kolmogorov test can be seen at:
7570 /// http://www.itl.nist.gov/div898/handbook/eda/section3/eda35g.htm
7571 ///
7572 /// NOTE2
7573 /// see also alternative function TH1::Chi2Test
7574 /// The Kolmogorov test is assumed to give better results than Chi2Test
7575 /// in case of histograms with low statistics.
7576 ///
7577 /// NOTE3 (Jan Conrad, Fred James)
7578 /// "The returned value PROB is calculated such that it will be
7579 /// uniformly distributed between zero and one for compatible histograms,
7580 /// provided the data are not binned (or the number of bins is very large
7581 /// compared with the number of events). Users who have access to unbinned
7582 /// data and wish exact confidence levels should therefore not put their data
7583 /// into histograms, but should call directly TMath::KolmogorovTest. On
7584 /// the other hand, since TH1 is a convenient way of collecting data and
7585 /// saving space, this function has been provided. However, the values of
7586 /// PROB for binned data will be shifted slightly higher than expected,
7587 /// depending on the effects of the binning. For example, when comparing two
7588 /// uniform distributions of 500 events in 100 bins, the values of PROB,
7589 /// instead of being exactly uniformly distributed between zero and one, have
7590 /// a mean value of about 0.56. We can apply a useful
7591 /// rule: As long as the bin width is small compared with any significant
7592 /// physical effect (for example the experimental resolution) then the binning
7593 /// cannot have an important effect. Therefore, we believe that for all
7594 /// practical purposes, the probability value PROB is calculated correctly
7595 /// provided the user is aware that:
7596 /// 1. The value of PROB should not be expected to have exactly the correct
7597 /// distribution for binned data.
7598 /// 2. The user is responsible for seeing to it that the bin widths are
7599 /// small compared with any physical phenomena of interest.
7600 /// 3. The effect of binning (if any) is always to make the value of PROB
7601 /// slightly too big. That is, setting an acceptance criterion of (PROB>0.05
7602 /// will assure that at most 5% of truly compatible histograms are rejected,
7603 /// and usually somewhat less."
7604 ///
7605 /// Note also that for GoF test of unbinned data ROOT provides also the class
7606 /// ROOT::Math::GoFTest. The class has also method for doing one sample tests
7607 /// (i.e. comparing the data with a given distribution).
7608 
7609 Double_t TH1::KolmogorovTest(const TH1 *h2, Option_t *option) const
7611  TString opt = option;
7612  opt.ToUpper();
7613 
7614  Double_t prob = 0;
7615  TH1 *h1 = (TH1*)this;
7616  if (h2 == 0) return 0;
7617  const TAxis *axis1 = h1->GetXaxis();
7618  const TAxis *axis2 = h2->GetXaxis();
7619  Int_t ncx1 = axis1->GetNbins();
7620  Int_t ncx2 = axis2->GetNbins();
7621 
7622  // Check consistency of dimensions
7623  if (h1->GetDimension() != 1 || h2->GetDimension() != 1) {
7624  Error("KolmogorovTest","Histograms must be 1-D\n");
7625  return 0;
7626  }
7627 
7628  // Check consistency in number of channels
7629  if (ncx1 != ncx2) {
7630  Error("KolmogorovTest","Number of channels is different, %d and %d\n",ncx1,ncx2);
7631  return 0;
7632  }
7633 
7634  // empty the buffer. Probably we could add as an unbinned test
7635  if (fBuffer) ((TH1*)this)->BufferEmpty();
7636 
7637  // Check consistency in channel edges
7638  Double_t difprec = 1e-5;
7639  Double_t diff1 = TMath::Abs(axis1->GetXmin() - axis2->GetXmin());
7640  Double_t diff2 = TMath::Abs(axis1->GetXmax() - axis2->GetXmax());
7641  if (diff1 > difprec || diff2 > difprec) {
7642  Error("KolmogorovTest","histograms with different binning");
7643  return 0;
7644  }
7645 
7646  Bool_t afunc1 = kFALSE;
7647  Bool_t afunc2 = kFALSE;
7648  Double_t sum1 = 0, sum2 = 0;
7649  Double_t ew1, ew2, w1 = 0, w2 = 0;
7650  Int_t bin;
7651  Int_t ifirst = 1;
7652  Int_t ilast = ncx1;
7653  // integral of all bins (use underflow/overflow if option)
7654  if (opt.Contains("U")) ifirst = 0;
7655  if (opt.Contains("O")) ilast = ncx1 +1;
7656  for (bin = ifirst; bin <= ilast; bin++) {
7657  sum1 += h1->RetrieveBinContent(bin);
7658  sum2 += h2->RetrieveBinContent(bin);
7659  ew1 = h1->GetBinError(bin);
7660  ew2 = h2->GetBinError(bin);
7661  w1 += ew1*ew1;
7662  w2 += ew2*ew2;
7663  }
7664  if (sum1 == 0) {
7665  Error("KolmogorovTest","Histogram1 %s integral is zero\n",h1->GetName());
7666  return 0;
7667  }
7668  if (sum2 == 0) {
7669  Error("KolmogorovTest","Histogram2 %s integral is zero\n",h2->GetName());
7670  return 0;
7671  }
7672 
7673  // calculate the effective entries.
7674  // the case when errors are zero (w1 == 0 or w2 ==0) are equivalent to
7675  // compare to a function. In that case the rescaling is done only on sqrt(esum2) or sqrt(esum1)
7676  Double_t esum1 = 0, esum2 = 0;
7677  if (w1 > 0)
7678  esum1 = sum1 * sum1 / w1;
7679  else
7680  afunc1 = kTRUE; // use later for calculating z
7681 
7682  if (w2 > 0)
7683  esum2 = sum2 * sum2 / w2;
7684  else
7685  afunc2 = kTRUE; // use later for calculating z
7686 
7687  if (afunc2 && afunc1) {
7688  Error("KolmogorovTest","Errors are zero for both histograms\n");
7689  return 0;
7690  }
7691 
7692 
7693  Double_t s1 = 1/sum1;
7694  Double_t s2 = 1/sum2;
7695 
7696  // Find largest difference for Kolmogorov Test
7697  Double_t dfmax =0, rsum1 = 0, rsum2 = 0;
7698 
7699  for (bin=ifirst;bin<=ilast;bin++) {
7700  rsum1 += s1*h1->RetrieveBinContent(bin);
7701  rsum2 += s2*h2->RetrieveBinContent(bin);
7702  dfmax = TMath::Max(dfmax,TMath::Abs(rsum1-rsum2));
7703  }
7704 
7705  // Get Kolmogorov probability
7706  Double_t z, prb1=0, prb2=0, prb3=0;
7707 
7708  // case h1 is exact (has zero errors)
7709  if (afunc1)
7710  z = dfmax*TMath::Sqrt(esum2);
7711  // case h2 has zero errors
7712  else if (afunc2)
7713  z = dfmax*TMath::Sqrt(esum1);
7714  else
7715  // for comparison between two data sets
7716  z = dfmax*TMath::Sqrt(esum1*esum2/(esum1+esum2));
7717 
7718  prob = TMath::KolmogorovProb(z);
7719 
7720  // option N to combine normalization makes sense if both afunc1 and afunc2 are false
7721  if (opt.Contains("N") && !(afunc1 || afunc2 ) ) {
7722  // Combine probabilities for shape and normalization,
7723  prb1 = prob;
7724  Double_t d12 = esum1-esum2;
7725  Double_t chi2 = d12*d12/(esum1+esum2);
7726  prb2 = TMath::Prob(chi2,1);
7727  // see Eadie et al., section 11.6.2
7728  if (prob > 0 && prb2 > 0) prob *= prb2*(1-TMath::Log(prob*prb2));
7729  else prob = 0;
7730  }
7731  // X option. Pseudo-experiments post-processor to determine KS probability
7732  const Int_t nEXPT = 1000;
7733  if (opt.Contains("X") && !(afunc1 || afunc2 ) ) {
7734  Double_t dSEXPT;
7735  TH1 *hExpt = (TH1*)(gDirectory ? gDirectory->CloneObject(this,kFALSE) : gROOT->CloneObject(this,kFALSE));
7736  // make nEXPT experiments (this should be a parameter)
7737  prb3 = 0;
7738  for (Int_t i=0; i < nEXPT; i++) {
7739  hExpt->Reset();
7740  hExpt->FillRandom(h1,(Int_t)esum2);
7741  dSEXPT = KolmogorovTest(hExpt,"M");
7742  if (dSEXPT>dfmax) prb3 += 1.0;
7743  }
7744  prb3 /= (Double_t)nEXPT;
7745  delete hExpt;
7746  }
7747 
7748  // debug printout
7749  if (opt.Contains("D")) {
7750  printf(" Kolmo Prob h1 = %s, sum bin content =%g effective entries =%g\n",h1->GetName(),sum1,esum1);
7751  printf(" Kolmo Prob h2 = %s, sum bin content =%g effective entries =%g\n",h2->GetName(),sum2,esum2);
7752  printf(" Kolmo Prob = %g, Max Dist = %g\n",prob,dfmax);
7753  if (opt.Contains("N"))
7754  printf(" Kolmo Prob = %f for shape alone, =%f for normalisation alone\n",prb1,prb2);
7755  if (opt.Contains("X"))
7756  printf(" Kolmo Prob = %f with %d pseudo-experiments\n",prb3,nEXPT);
7757  }
7758  // This numerical error condition should never occur:
7759  if (TMath::Abs(rsum1-1) > 0.002) Warning("KolmogorovTest","Numerical problems with h1=%s\n",h1->GetName());
7760  if (TMath::Abs(rsum2-1) > 0.002) Warning("KolmogorovTest","Numerical problems with h2=%s\n",h2->GetName());
7761 
7762  if(opt.Contains("M")) return dfmax;
7763  else if(opt.Contains("X")) return prb3;
7764  else return prob;
7765 }
7766 
7767 
7768 ////////////////////////////////////////////////////////////////////////////////
7769 /// Replace bin contents by the contents of array content
7770 
7771 void TH1::SetContent(const Double_t *content)
7773  fEntries = fNcells;
7774  fTsumw = 0;
7775  for (Int_t i = 0; i < fNcells; ++i) UpdateBinContent(i, content[i]);
7776 }
7777 
7778 
7779 ////////////////////////////////////////////////////////////////////////////////
7780 /// Return contour values into array levels if pointer levels is non zero
7781 ///
7782 /// The function returns the number of contour levels.
7783 /// see GetContourLevel to return one contour only
7784 ///
7785 
7788  Int_t nlevels = fContour.fN;
7789  if (levels) {
7790  if (nlevels == 0) {
7791  nlevels = 20;
7792  SetContour(nlevels);
7793  } else {
7794  if (TestBit(kUserContour) == 0) SetContour(nlevels);
7795  }
7796  for (Int_t level=0; level<nlevels; level++) levels[level] = fContour.fArray[level];
7797  }
7798  return nlevels;
7799 }
7800 
7801 
7802 ////////////////////////////////////////////////////////////////////////////////
7803 /// Return value of contour number level
7804 /// use GetContour to return the array of all contour levels
7805 
7806 Double_t TH1::GetContourLevel(Int_t level) const
7808  return (level >= 0 && level < fContour.fN) ? fContour.fArray[level] : 0.0;
7809 }
7810 
7811 
7812 ////////////////////////////////////////////////////////////////////////////////
7813 /// Return the value of contour number "level" in Pad coordinates ie: if the Pad
7814 /// is in log scale along Z it returns le log of the contour level value.
7815 /// see GetContour to return the array of all contour levels
7816 
7819  if (level <0 || level >= fContour.fN) return 0;
7820  Double_t zlevel = fContour.fArray[level];
7821 
7822  // In case of user defined contours and Pad in log scale along Z,
7823  // fContour.fArray doesn't contain the log of the contour whereas it does
7824  // in case of equidistant contours.
7825  if (gPad && gPad->GetLogz() && TestBit(kUserContour)) {
7826  if (zlevel <= 0) return 0;
7827  zlevel = TMath::Log10(zlevel);
7828  }
7829  return zlevel;
7830 }
7831 
7832 
7833 ////////////////////////////////////////////////////////////////////////////////
7834 /// set the maximum number of entries to be kept in the buffer
7835 
7836 void TH1::SetBuffer(Int_t buffersize, Option_t * /*option*/)
7838  if (fBuffer) {
7839  BufferEmpty();
7840  delete [] fBuffer;
7841  fBuffer = 0;
7842  }
7843  if (buffersize <= 0) {
7844  fBufferSize = 0;
7845  return;
7846  }
7847  if (buffersize < 100) buffersize = 100;
7848  fBufferSize = 1 + buffersize*(fDimension+1);
7849  fBuffer = new Double_t[fBufferSize];
7850  memset(fBuffer,0,sizeof(Double_t)*fBufferSize);
7851 }
7852 
7853 
7854 ////////////////////////////////////////////////////////////////////////////////
7855 /// Set the number and values of contour levels.
7856 ///
7857 /// By default the number of contour levels is set to 20. The contours values
7858 /// in the array "levels" should be specified in increasing order.
7859 ///
7860 /// if argument levels = 0 or missing, equidistant contours are computed
7861 
7862 void TH1::SetContour(Int_t nlevels, const Double_t *levels)
7864  Int_t level;
7866  if (nlevels <=0 ) {
7867  fContour.Set(0);
7868  return;
7869  }
7870  fContour.Set(nlevels);
7871 
7872  // - Contour levels are specified
7873  if (levels) {
7875  for (level=0; level<nlevels; level++) fContour.fArray[level] = levels[level];
7876  } else {
7877  // - contour levels are computed automatically as equidistant contours
7878  Double_t zmin = GetMinimum();
7879  Double_t zmax = GetMaximum();
7880  if ((zmin == zmax) && (zmin != 0)) {
7881  zmax += 0.01*TMath::Abs(zmax);
7882  zmin -= 0.01*TMath::Abs(zmin);
7883  }
7884  Double_t dz = (zmax-zmin)/Double_t(nlevels);
7885  if (gPad && gPad->GetLogz()) {
7886  if (zmax <= 0) return;
7887  if (zmin <= 0) zmin = 0.001*zmax;
7888  zmin = TMath::Log10(zmin);
7889  zmax = TMath::Log10(zmax);
7890  dz = (zmax-zmin)/Double_t(nlevels);
7891  }
7892  for (level=0; level<nlevels; level++) {
7893  fContour.fArray[level] = zmin + dz*Double_t(level);
7894  }
7895  }
7896 }
7897 
7898 
7899 ////////////////////////////////////////////////////////////////////////////////
7900 /// Set value for one contour level.
7901 
7904  if (level < 0 || level >= fContour.fN) return;
7906  fContour.fArray[level] = value;
7907 }
7908 
7909 
7910 ////////////////////////////////////////////////////////////////////////////////
7911 /// Return maximum value smaller than maxval of bins in the range,
7912 /// unless the value has been overridden by TH1::SetMaximum,
7913 /// in which case it returns that value. (This happens, for example,
7914 /// when the histogram is drawn and the y or z axis limits are changed
7915 ///
7916 /// To get the maximum value of bins in the histogram regardless of
7917 /// whether the value has been overridden, use
7918 /// h->GetBinContent(h->GetMaximumBin())
7919 
7920 Double_t TH1::GetMaximum(Double_t maxval) const
7922  if (fMaximum != -1111) return fMaximum;
7923 
7924  // empty the buffer
7925  if (fBuffer) ((TH1*)this)->BufferEmpty();
7926 
7927  Int_t bin, binx, biny, binz;
7928  Int_t xfirst = fXaxis.GetFirst();
7929  Int_t xlast = fXaxis.GetLast();
7930  Int_t yfirst = fYaxis.GetFirst();
7931  Int_t ylast = fYaxis.GetLast();
7932  Int_t zfirst = fZaxis.GetFirst();
7933  Int_t zlast = fZaxis.GetLast();
7934  Double_t maximum = -FLT_MAX, value;
7935  for (binz=zfirst;binz<=zlast;binz++) {
7936  for (biny=yfirst;biny<=ylast;biny++) {
7937  for (binx=xfirst;binx<=xlast;binx++) {
7938  bin = GetBin(binx,biny,binz);
7939  value = RetrieveBinContent(bin);
7940  if (value > maximum && value < maxval) maximum = value;
7941  }
7942  }
7943  }
7944  return maximum;
7945 }
7946 
7947 
7948 ////////////////////////////////////////////////////////////////////////////////
7949 /// Return location of bin with maximum value in the range.
7950 
7951 Int_t TH1::GetMaximumBin() const
7953  Int_t locmax, locmay, locmaz;
7954  return GetMaximumBin(locmax, locmay, locmaz);
7955 }
7956 
7957 
7958 ////////////////////////////////////////////////////////////////////////////////
7959 /// Return location of bin with maximum value in the range.
7960 
7961 Int_t TH1::GetMaximumBin(Int_t &locmax, Int_t &locmay, Int_t &locmaz) const
7963  // empty the buffer
7964  if (fBuffer) ((TH1*)this)->BufferEmpty();
7965 
7966  Int_t bin, binx, biny, binz;
7967  Int_t locm;
7968  Int_t xfirst = fXaxis.GetFirst();
7969  Int_t xlast = fXaxis.GetLast();
7970  Int_t yfirst = fYaxis.GetFirst();
7971  Int_t ylast = fYaxis.GetLast();
7972  Int_t zfirst = fZaxis.GetFirst();
7973  Int_t zlast = fZaxis.GetLast();
7974  Double_t maximum = -FLT_MAX, value;
7975  locm = locmax = locmay = locmaz = 0;
7976  for (binz=zfirst;binz<=zlast;binz++) {
7977  for (biny=yfirst;biny<=ylast;biny++) {
7978  for (binx=xfirst;binx<=xlast;binx++) {
7979  bin = GetBin(binx,biny,binz);
7980  value = RetrieveBinContent(bin);
7981  if (value > maximum) {
7982  maximum = value;
7983  locm = bin;
7984  locmax = binx;
7985  locmay = biny;
7986  locmaz = binz;
7987  }
7988  }
7989  }
7990  }
7991  return locm;
7992 }
7993 
7994 
7995 ////////////////////////////////////////////////////////////////////////////////
7996 /// Return minimum value larger than minval of bins in the range,
7997 /// unless the value has been overridden by TH1::SetMinimum,
7998 /// in which case it returns that value. (This happens, for example,
7999 /// when the histogram is drawn and the y or z axis limits are changed
8000 ///
8001 /// To get the minimum value of bins in the histogram regardless of
8002 /// whether the value has been overridden, use
8003 /// h->GetBinContent(h->GetMinimumBin())
8004 
8005 Double_t TH1::GetMinimum(Double_t minval) const
8007  if (fMinimum != -1111) return fMinimum;
8008 
8009  // empty the buffer
8010  if (fBuffer) ((TH1*)this)->BufferEmpty();
8011 
8012  Int_t bin, binx, biny, binz;
8013  Int_t xfirst = fXaxis.GetFirst();
8014  Int_t xlast = fXaxis.GetLast();
8015  Int_t yfirst = fYaxis.GetFirst();
8016  Int_t ylast = fYaxis.GetLast();
8017  Int_t zfirst = fZaxis.GetFirst();
8018  Int_t zlast = fZaxis.GetLast();
8019  Double_t minimum=FLT_MAX, value;
8020  for (binz=zfirst;binz<=zlast;binz++) {
8021  for (biny=yfirst;biny<=ylast;biny++) {
8022  for (binx=xfirst;binx<=xlast;binx++) {
8023  bin = GetBin(binx,biny,binz);
8024  value = RetrieveBinContent(bin);
8025  if (value < minimum && value > minval) minimum = value;
8026  }
8027  }
8028  }
8029  return minimum;
8030 }
8031 
8032 
8033 ////////////////////////////////////////////////////////////////////////////////
8034 /// Return location of bin with minimum value in the range.
8035 
8036 Int_t TH1::GetMinimumBin() const
8038  Int_t locmix, locmiy, locmiz;
8039  return GetMinimumBin(locmix, locmiy, locmiz);
8040 }
8041 
8042 
8043 ////////////////////////////////////////////////////////////////////////////////
8044 /// Return location of bin with minimum value in the range.
8045 
8046 Int_t TH1::GetMinimumBin(Int_t &locmix, Int_t &locmiy, Int_t &locmiz) const
8048  // empty the buffer
8049  if (fBuffer) ((TH1*)this)->BufferEmpty();
8050 
8051  Int_t bin, binx, biny, binz;
8052  Int_t locm;
8053  Int_t xfirst = fXaxis.GetFirst();
8054  Int_t xlast = fXaxis.GetLast();
8055  Int_t yfirst = fYaxis.GetFirst();
8056  Int_t ylast = fYaxis.GetLast();
8057  Int_t zfirst = fZaxis.GetFirst();
8058  Int_t zlast = fZaxis.GetLast();
8059  Double_t minimum = FLT_MAX, value;
8060  locm = locmix = locmiy = locmiz = 0;
8061  for (binz=zfirst;binz<=zlast;binz++) {
8062  for (biny=yfirst;biny<=ylast;biny++) {
8063  for (binx=xfirst;binx<=xlast;binx++) {
8064  bin = GetBin(binx,biny,binz);
8065  value = RetrieveBinContent(bin);
8066  if (value < minimum) {
8067  minimum = value;
8068  locm = bin;
8069  locmix = binx;
8070  locmiy = biny;
8071  locmiz = binz;
8072  }
8073  }
8074  }
8075  }
8076  return locm;
8077 }
8078 
8079 
8080 ////////////////////////////////////////////////////////////////////////////////
8081 /// Redefine x axis parameters.
8082 ///
8083 /// The X axis parameters are modified.
8084 /// The bins content array is resized
8085 /// if errors (Sumw2) the errors array is resized
8086 /// The previous bin contents are lost
8087 /// To change only the axis limits, see TAxis::SetRange
8088 
8091  if (GetDimension() != 1) {
8092  Error("SetBins","Operation only valid for 1-d histograms");
8093  return;
8094  }
8095  fXaxis.SetRange(0,0);
8096  fXaxis.Set(nx,xmin,xmax);
8097  fYaxis.Set(1,0,1);
8098  fZaxis.Set(1,0,1);
8099  fNcells = nx+2;
8100  SetBinsLength(fNcells);
8101  if (fSumw2.fN) {
8102  fSumw2.Set(fNcells);
8103  }
8104 }
8105 
8106 
8107 ////////////////////////////////////////////////////////////////////////////////
8108 /// Redefine x axis parameters with variable bin sizes.
8109 ///
8110 /// The X axis parameters are modified.
8111 /// The bins content array is resized
8112 /// if errors (Sumw2) the errors array is resized
8113 /// The previous bin contents are lost
8114 /// To change only the axis limits, see TAxis::SetRange
8115 /// xBins is supposed to be of length nx+1
8116 
8117 void TH1::SetBins(Int_t nx, const Double_t *xBins)
8119  if (GetDimension() != 1) {
8120  Error("SetBins","Operation only valid for 1-d histograms");
8121  return;
8122  }
8123  fXaxis.SetRange(0,0);
8124  fXaxis.Set(nx,xBins);
8125  fYaxis.Set(1,0,1);
8126  fZaxis.Set(1,0,1);
8127  fNcells = nx+2;
8128  SetBinsLength(fNcells);
8129  if (fSumw2.fN) {
8130  fSumw2.Set(fNcells);
8131  }
8132 }
8133 
8134 
8135 ////////////////////////////////////////////////////////////////////////////////
8136 /// Redefine x and y axis parameters.
8137 ///
8138 /// The X and Y axis parameters are modified.
8139 /// The bins content array is resized
8140 /// if errors (Sumw2) the errors array is resized
8141 /// The previous bin contents are lost
8142 /// To change only the axis limits, see TAxis::SetRange
8143 
8146  if (GetDimension() != 2) {
8147  Error("SetBins","Operation only valid for 2-D histograms");
8148  return;
8149  }
8150  fXaxis.SetRange(0,0);
8151  fYaxis.SetRange(0,0);
8152  fXaxis.Set(nx,xmin,xmax);
8153  fYaxis.Set(ny,ymin,ymax);
8154  fZaxis.Set(1,0,1);
8155  fNcells = (nx+2)*(ny+2);
8156  SetBinsLength(fNcells);
8157  if (fSumw2.fN) {
8158  fSumw2.Set(fNcells);
8159  }
8160 }
8161 
8162 
8163 ////////////////////////////////////////////////////////////////////////////////
8164 /// Redefine x and y axis parameters with variable bin sizes.
8165 ///
8166 /// The X and Y axis parameters are modified.
8167 /// The bins content array is resized
8168 /// if errors (Sumw2) the errors array is resized
8169 /// The previous bin contents are lost
8170 /// To change only the axis limits, see TAxis::SetRange
8171 /// xBins is supposed to be of length nx+1, yBins is supposed to be of length ny+1
8172 
8173 void TH1::SetBins(Int_t nx, const Double_t *xBins, Int_t ny, const Double_t *yBins)
8175  if (GetDimension() != 2) {
8176  Error("SetBins","Operation only valid for 2-D histograms");
8177  return;
8178  }
8179  fXaxis.SetRange(0,0);
8180  fYaxis.SetRange(0,0);
8181  fXaxis.Set(nx,xBins);
8182  fYaxis.Set(ny,yBins);
8183  fZaxis.Set(1,0,1);
8184  fNcells = (nx+2)*(ny+2);
8185  SetBinsLength(fNcells);
8186  if (fSumw2.fN) {
8187  fSumw2.Set(fNcells);
8188  }
8189 }
8190 
8191 
8192 ////////////////////////////////////////////////////////////////////////////////
8193 /// Redefine x, y and z axis parameters.
8194 ///
8195 /// The X, Y and Z axis parameters are modified.
8196 /// The bins content array is resized
8197 /// if errors (Sumw2) the errors array is resized
8198 /// The previous bin contents are lost
8199 /// To change only the axis limits, see TAxis::SetRange
8200 
8203  if (GetDimension() != 3) {
8204  Error("SetBins","Operation only valid for 3-D histograms");
8205  return;
8206  }
8207  fXaxis.SetRange(0,0);
8208  fYaxis.SetRange(0,0);
8209  fZaxis.SetRange(0,0);
8210  fXaxis.Set(nx,xmin,xmax);
8211  fYaxis.Set(ny,ymin,ymax);
8212  fZaxis.Set(nz,zmin,zmax);
8213  fNcells = (nx+2)*(ny+2)*(nz+2);
8214  SetBinsLength(fNcells);
8215  if (fSumw2.fN) {
8216  fSumw2.Set(fNcells);
8217  }
8218 }
8219 
8220 
8221 ////////////////////////////////////////////////////////////////////////////////
8222 /// Redefine x, y and z axis parameters with variable bin sizes.
8223 ///
8224 /// The X, Y and Z axis parameters are modified.
8225 /// The bins content array is resized
8226 /// if errors (Sumw2) the errors array is resized
8227 /// The previous bin contents are lost
8228 /// To change only the axis limits, see TAxis::SetRange
8229 /// xBins is supposed to be of length nx+1, yBins is supposed to be of length ny+1,
8230 /// zBins is supposed to be of length nz+1
8231 
8232 void TH1::SetBins(Int_t nx, const Double_t *xBins, Int_t ny, const Double_t *yBins, Int_t nz, const Double_t *zBins)
8234  if (GetDimension() != 3) {
8235  Error("SetBins","Operation only valid for 3-D histograms");
8236  return;
8237  }
8238  fXaxis.SetRange(0,0);
8239  fYaxis.SetRange(0,0);
8240  fZaxis.SetRange(0,0);
8241  fXaxis.Set(nx,xBins);
8242  fYaxis.Set(ny,yBins);
8243  fZaxis.Set(nz,zBins);
8244  fNcells = (nx+2)*(ny+2)*(nz+2);
8245  SetBinsLength(fNcells);
8246  if (fSumw2.fN) {
8247  fSumw2.Set(fNcells);
8248  }
8249 }
8250 
8251 
8252 ////////////////////////////////////////////////////////////////////////////////
8253 /// By default when an histogram is created, it is added to the list
8254 /// of histogram objects in the current directory in memory.
8255 /// Remove reference to this histogram from current directory and add
8256 /// reference to new directory dir. dir can be 0 in which case the
8257 /// histogram does not belong to any directory.
8258 ///
8259 /// Note that the directory is not a real property of the histogram and
8260 /// it will not be copied when the histogram is copied or cloned.
8261 /// If the user wants to have the copied (cloned) histogram in the same
8262 /// directory, he needs to set again the directory using SetDirectory to the
8263 /// copied histograms
8264 
8267  if (fDirectory == dir) return;
8268  if (fDirectory) fDirectory->Remove(this);
8269  fDirectory = dir;
8270  if (fDirectory) fDirectory->Append(this);
8271 }
8272 
8273 
8274 ////////////////////////////////////////////////////////////////////////////////
8275 /// Replace bin errors by values in array error.
8276 
8277 void TH1::SetError(const Double_t *error)
8279  for (Int_t i = 0; i < fNcells; ++i) SetBinError(i, error[i]);
8280 }
8281 
8282 
8283 ////////////////////////////////////////////////////////////////////////////////
8284 /// Change the name of this histogram
8285 ///
8286 
8287 void TH1::SetName(const char *name)
8289  // Histograms are named objects in a THashList.
8290  // We must update the hashlist if we change the name
8291  // We protect this operation
8293  if (fDirectory) fDirectory->Remove(this);
8294  fName = name;
8295  if (fDirectory) fDirectory->Append(this);
8296 }
8297 
8298 
8299 ////////////////////////////////////////////////////////////////////////////////
8300 /// Change the name and title of this histogram
8301 
8302 void TH1::SetNameTitle(const char *name, const char *title)
8304  // Histograms are named objects in a THashList.
8305  // We must update the hashlist if we change the name
8306  SetName(name);
8307  SetTitle(title);
8308 }
8309 
8310 
8311 ////////////////////////////////////////////////////////////////////////////////
8312 /// Set statistics option on/off
8313 ///
8314 /// By default, the statistics box is drawn.
8315 /// The paint options can be selected via gStyle->SetOptStats.
8316 /// This function sets/resets the kNoStats bin in the histogram object.
8317 /// It has priority over the Style option.
8318 
8319 void TH1::SetStats(Bool_t stats)
8321  ResetBit(kNoStats);
8322  if (!stats) {
8323  SetBit(kNoStats);
8324  //remove the "stats" object from the list of functions
8325  if (fFunctions) {
8326  TObject *obj = fFunctions->FindObject("stats");
8327  if (obj) {
8328  fFunctions->Remove(obj);
8329  delete obj;
8330  }
8331  }
8332  }
8333 }
8334 
8335 
8336 ////////////////////////////////////////////////////////////////////////////////
8337 /// Create structure to store sum of squares of weights.
8338 ///
8339 /// if histogram is already filled, the sum of squares of weights
8340 /// is filled with the existing bin contents
8341 ///
8342 /// The error per bin will be computed as sqrt(sum of squares of weight)
8343 /// for each bin.
8344 ///
8345 /// This function is automatically called when the histogram is created
8346 /// if the static function TH1::SetDefaultSumw2 has been called before.
8347 /// If flag = false the structure is deleted
8348 
8349 void TH1::Sumw2(Bool_t flag)
8351  if (!flag) {
8352  // clear the array if existing - do nothing otherwise
8353  if (fSumw2.fN > 0 ) fSumw2.Set(0);
8354  return;
8355  }
8356 
8357  if (fSumw2.fN == fNcells) {
8358  if (!fgDefaultSumw2 )
8359  Warning("Sumw2","Sum of squares of weights structure already created");
8360  return;
8361  }
8362 
8363  fSumw2.Set(fNcells);
8364 
8365  // empty the buffer
8366  if (fBuffer) BufferEmpty();
8367 
8368  if (fEntries > 0)
8369  for (Int_t i = 0; i < fNcells; ++i)
8370  fSumw2.fArray[i] = TMath::Abs(RetrieveBinContent(i));
8371 }
8372 
8373 
8374 ////////////////////////////////////////////////////////////////////////////////
8375 /// Return pointer to function with name.
8376 ///
8377 ///
8378 /// Functions such as TH1::Fit store the fitted function in the list of
8379 /// functions of this histogram.
8380 
8381 TF1 *TH1::GetFunction(const char *name) const
8383  return (TF1*)fFunctions->FindObject(name);
8384 }
8385 
8386 
8387 ////////////////////////////////////////////////////////////////////////////////
8388 /// Return value of error associated to bin number bin.
8389 ///
8390 /// if the sum of squares of weights has been defined (via Sumw2),
8391 /// this function returns the sqrt(sum of w2).
8392 /// otherwise it returns the sqrt(contents) for this bin.
8393 
8394 Double_t TH1::GetBinError(Int_t bin) const
8396  if (bin < 0) bin = 0;
8397  if (bin >= fNcells) bin = fNcells-1;
8398  if (fBuffer) ((TH1*)this)->BufferEmpty();
8399  if (fSumw2.fN) return TMath::Sqrt(fSumw2.fArray[bin]);
8400 
8401  return TMath::Sqrt(TMath::Abs(RetrieveBinContent(bin)));
8402 }
8403 
8404 
8405 ////////////////////////////////////////////////////////////////////////////////
8406 /// Return lower error associated to bin number bin.
8407 ///
8408 /// The error will depend on the statistic option used will return
8409 /// the binContent - lower interval value
8410 
8413  if (fBinStatErrOpt == kNormal || fSumw2.fN) return GetBinError(bin);
8414  if (bin < 0) bin = 0;
8415  if (bin >= fNcells) bin = fNcells-1;
8416  if (fBuffer) ((TH1*)this)->BufferEmpty();
8417 
8418  Double_t alpha = 1.- 0.682689492;
8419  if (fBinStatErrOpt == kPoisson2) alpha = 0.05;
8420 
8421  Double_t c = RetrieveBinContent(bin);
8422  Int_t n = int(c);
8423  if (n < 0) {
8424  Warning("GetBinErrorLow","Histogram has negative bin content-force usage to normal errors");
8425  ((TH1*)this)->fBinStatErrOpt = kNormal;
8426  return GetBinError(bin);
8427  }
8428 
8429  if (n == 0) return 0;
8430  return c - ROOT::Math::gamma_quantile( alpha/2, n, 1.);
8431 }
8432 
8433 
8434 ////////////////////////////////////////////////////////////////////////////////
8435 /// Return upper error associated to bin number bin.
8436 ///
8437 /// The error will depend on the statistic option used will return
8438 /// the binContent - upper interval value
8439 
8442  if (fBinStatErrOpt == kNormal || fSumw2.fN) return GetBinError(bin);
8443  if (bin < 0) bin = 0;
8444  if (bin >= fNcells) bin = fNcells-1;
8445  if (fBuffer) ((TH1*)this)->BufferEmpty();
8446 
8447  Double_t alpha = 1.- 0.682689492;
8448  if (fBinStatErrOpt == kPoisson2) alpha = 0.05;
8449 
8450  Double_t c = RetrieveBinContent(bin);
8451  Int_t n = int(c);
8452  if (n < 0) {
8453  Warning("GetBinErrorUp","Histogram has negative bin content-force usage to normal errors");
8454  ((TH1*)this)->fBinStatErrOpt = kNormal;
8455  return GetBinError(bin);
8456  }
8457 
8458  // for N==0 return an upper limit at 0.68 or (1-alpha)/2 ?
8459  // decide to return always (1-alpha)/2 upper interval
8460  //if (n == 0) return ROOT::Math::gamma_quantile_c(alpha,n+1,1);
8461  return ROOT::Math::gamma_quantile_c( alpha/2, n+1, 1) - c;
8462 }
8463 
8464 //L.M. These following getters are useless and should be probably deprecated
8465 ////////////////////////////////////////////////////////////////////////////////
8466 /// return bin center for 1D historam
8467 /// Better to use h1.GetXaxis().GetBinCenter(bin)
8468 
8469 Double_t TH1::GetBinCenter(Int_t bin) const
8471  if (fDimension == 1) return fXaxis.GetBinCenter(bin);
8472  Error("GetBinCenter","Invalid method for a %d-d histogram - return a NaN",fDimension);
8473  return TMath::QuietNaN();
8474 }
8475 
8476 ////////////////////////////////////////////////////////////////////////////////
8477 /// return bin lower edge for 1D historam
8478 /// Better to use h1.GetXaxis().GetBinLowEdge(bin)
8479 
8482  if (fDimension == 1) return fXaxis.GetBinLowEdge(bin);
8483  Error("GetBinLowEdge","Invalid method for a %d-d histogram - return a NaN",fDimension);
8484  return TMath::QuietNaN();
8485 }
8486 
8487 ////////////////////////////////////////////////////////////////////////////////
8488 /// return bin width for 1D historam
8489 /// Better to use h1.GetXaxis().GetBinWidth(bin)
8490 
8491 Double_t TH1::GetBinWidth(Int_t bin) const
8493  if (fDimension == 1) return fXaxis.GetBinWidth(bin);
8494  Error("GetBinWidth","Invalid method for a %d-d histogram - return a NaN",fDimension);
8495  return TMath::QuietNaN();
8496 }
8497 
8498 ////////////////////////////////////////////////////////////////////////////////
8499 /// Fill array with center of bins for 1D histogram
8500 /// Better to use h1.GetXaxis().GetCenter(center)
8501 
8502 void TH1::GetCenter(Double_t *center) const
8504  if (fDimension == 1) {
8505  fXaxis.GetCenter(center);
8506  return;
8507  }
8508  Error("GetCenter","Invalid method for a %d-d histogram ",fDimension);
8509 }
8510 
8511 ////////////////////////////////////////////////////////////////////////////////
8512 /// Fill array with low edge of bins for 1D histogram
8513 /// Better to use h1.GetXaxis().GetLowEdge(edge)
8514 
8515 void TH1::GetLowEdge(Double_t *edge) const
8517  if (fDimension == 1) {
8518  fXaxis.GetLowEdge(edge);
8519  return;
8520  }
8521  Error("GetLowEdge","Invalid method for a %d-d histogram ",fDimension);
8522 }
8523 
8524 ////////////////////////////////////////////////////////////////////////////////
8525 /// see convention for numbering bins in TH1::GetBin
8526 
8527 void TH1::SetBinError(Int_t bin, Double_t error)
8529  if (!fSumw2.fN) Sumw2();
8530  if (bin < 0 || bin>= fSumw2.fN) return;
8531  fSumw2.fArray[bin] = error * error;
8532 }
8533 
8534 
8535 ////////////////////////////////////////////////////////////////////////////////
8536 /// Set bin content
8537 /// see convention for numbering bins in TH1::GetBin
8538 /// In case the bin number is greater than the number of bins and
8539 /// the timedisplay option is set or CanExtendAllAxes(),
8540 /// the number of bins is automatically doubled to accommodate the new bin
8541 
8542 void TH1::SetBinContent(Int_t bin, Double_t content)
8544  fEntries++;
8545  fTsumw = 0;
8546  if (bin < 0) return;
8547  if (bin >= fNcells-1) {
8548  if (fXaxis.GetTimeDisplay() || CanExtendAllAxes() ) {
8549  while (bin >= fNcells-1) LabelsInflate();
8550  } else {
8551  if (bin == fNcells-1) UpdateBinContent(bin, content);
8552  return;
8553  }
8554  }
8555  UpdateBinContent(bin, content);
8556 }
8557 
8558 
8559 ////////////////////////////////////////////////////////////////////////////////
8560 /// see convention for numbering bins in TH1::GetBin
8561 
8562 void TH1::SetBinError(Int_t binx, Int_t biny, Double_t error)
8564  if (binx < 0 || binx > fXaxis.GetNbins() + 1) return;
8565  if (biny < 0 || biny > fYaxis.GetNbins() + 1) return;
8566  SetBinError(GetBin(binx, biny), error);
8567 }
8568 
8569 
8570 ////////////////////////////////////////////////////////////////////////////////
8571 /// see convention for numbering bins in TH1::GetBin
8572 
8573 void TH1::SetBinError(Int_t binx, Int_t biny, Int_t binz, Double_t error)
8575  if (binx < 0 || binx > fXaxis.GetNbins() + 1) return;
8576  if (biny < 0 || biny > fYaxis.GetNbins() + 1) return;
8577  if (binz < 0 || binz > fZaxis.GetNbins() + 1) return;
8578  SetBinError(GetBin(binx, biny, binz), error);
8579 }
8580 
8581 
8582 ////////////////////////////////////////////////////////////////////////////////
8583 /// This function calculates the background spectrum in this histogram.
8584 /// The background is returned as a histogram.
8585 ///
8586 /// \param[in] niter number of iterations (default value = 2)
8587 /// Increasing niter make the result smoother and lower.
8588 /// \param[in] option may contain one of the following options
8589 /// - to set the direction parameter
8590 /// "BackDecreasingWindow". By default the direction is BackIncreasingWindow
8591 /// - filterOrder-order of clipping filter (default "BackOrder2")
8592 /// possible values= "BackOrder4" "BackOrder6" "BackOrder8"
8593 /// - "nosmoothing" - if selected, the background is not smoothed
8594 /// By default the background is smoothed.
8595 /// - smoothWindow - width of smoothing window, (default is "BackSmoothing3")
8596 /// possible values= "BackSmoothing5" "BackSmoothing7" "BackSmoothing9"
8597 /// "BackSmoothing11" "BackSmoothing13" "BackSmoothing15"
8598 /// - "nocompton" - if selected the estimation of Compton edge
8599 /// will be not be included (by default the compton estimation is set)
8600 /// - "same" if this option is specified, the resulting background
8601 /// histogram is superimposed on the picture in the current pad.
8602 /// This option is given by default.
8603 ///
8604 /// NOTE that the background is only evaluated in the current range of this histogram.
8605 /// i.e., if this has a bin range (set via h->GetXaxis()->SetRange(binmin, binmax),
8606 /// the returned histogram will be created with the same number of bins
8607 /// as this input histogram, but only bins from binmin to binmax will be filled
8608 /// with the estimated background.
8609 ///
8610 
8611 TH1 *TH1::ShowBackground(Int_t niter, Option_t *option)
8613 
8614  return (TH1*)gROOT->ProcessLineFast(Form("TSpectrum::StaticBackground((TH1*)0x%lx,%d,\"%s\")",
8615  (ULong_t)this, niter, option));
8616 }
8617 
8618 
8619 ////////////////////////////////////////////////////////////////////////////////
8620 /// Interface to TSpectrum::Search.
8621 /// The function finds peaks in this histogram where the width is > sigma
8622 /// and the peak maximum greater than threshold*maximum bin content of this.
8623 /// For more details see TSpectrum::Search.
8624 /// Note the difference in the default value for option compared to TSpectrum::Search
8625 /// option="" by default (instead of "goff").
8626 
8627 Int_t TH1::ShowPeaks(Double_t sigma, Option_t *option, Double_t threshold)
8629  return (Int_t)gROOT->ProcessLineFast(Form("TSpectrum::StaticSearch((TH1*)0x%lx,%g,\"%s\",%g)",
8630  (ULong_t)this, sigma, option, threshold));
8631 }
8632 
8633 
8634 
8635 ////////////////////////////////////////////////////////////////////////////////
8636 /// For a given transform (first parameter), fills the histogram (second parameter)
8637 /// with the transform output data, specified in the third parameter
8638 /// If the 2nd parameter h_output is empty, a new histogram (TH1D or TH2D) is created
8639 /// and the user is responsible for deleting it.
8640 /// Available options:
8641 /// - "RE" - real part of the output
8642 /// - "IM" - imaginary part of the output
8643 /// - "MAG" - magnitude of the output
8644 /// - "PH" - phase of the output
8645 
8646 TH1* TH1::TransformHisto(TVirtualFFT *fft, TH1* h_output, Option_t *option)
8648  if (!fft || !fft->GetN() ) {
8649  ::Error("TransformHisto","Invalid FFT transform class");
8650  return 0;
8651  }
8652 
8653  if (fft->GetNdim()>2){
8654  ::Error("TransformHisto","Only 1d and 2D transform are supported");
8655  return 0;
8656  }
8657  Int_t binx,biny;
8658  TString opt = option;
8659  opt.ToUpper();
8660  Int_t *n = fft->GetN();
8661  TH1 *hout=0;
8662  if (h_output) {
8663  hout = h_output;
8664  }
8665  else {
8666  TString name = TString::Format("out_%s", opt.Data());
8667  if (fft->GetNdim()==1)
8668  hout = new TH1D(name, name,n[0], 0, n[0]);
8669  else if (fft->GetNdim()==2)
8670  hout = new TH2D(name, name, n[0], 0, n[0], n[1], 0, n[1]);
8671  }
8672  R__ASSERT(hout != 0);
8673  TString type=fft->GetType();
8674  Int_t ind[2];
8675  if (opt.Contains("RE")){
8676  if (type.Contains("2C") || type.Contains("2HC")) {
8677  Double_t re, im;
8678  for (binx = 1; binx<=hout->GetNbinsX(); binx++) {
8679  for (biny=1; biny<=hout->GetNbinsY(); biny++) {
8680  ind[0] = binx-1; ind[1] = biny-1;
8681  fft->GetPointComplex(ind, re, im);
8682  hout->SetBinContent(binx, biny, re);
8683  }
8684  }
8685  } else {
8686  for (binx = 1; binx<=hout->GetNbinsX(); binx++) {
8687  for (biny=1; biny<=hout->GetNbinsY(); biny++) {
8688  ind[0] = binx-1; ind[1] = biny-1;
8689  hout->SetBinContent(binx, biny, fft->GetPointReal(ind));
8690  }
8691  }
8692  }
8693  }
8694  if (opt.Contains("IM")) {
8695  if (type.Contains("2C") || type.Contains("2HC")) {
8696  Double_t re, im;
8697  for (binx = 1; binx<=hout->GetNbinsX(); binx++) {
8698  for (biny=1; biny<=hout->GetNbinsY(); biny++) {
8699  ind[0] = binx-1; ind[1] = biny-1;
8700  fft->GetPointComplex(ind, re, im);
8701  hout->SetBinContent(binx, biny, im);
8702  }
8703  }
8704  } else {
8705  ::Error("TransformHisto","No complex numbers in the output");
8706  return 0;
8707  }
8708  }
8709  if (opt.Contains("MA")) {
8710  if (type.Contains("2C") || type.Contains("2HC")) {
8711  Double_t re, im;
8712  for (binx = 1; binx<=hout->GetNbinsX(); binx++) {
8713  for (biny=1; biny<=hout->GetNbinsY(); biny++) {
8714  ind[0] = binx-1; ind[1] = biny-1;
8715  fft->GetPointComplex(ind, re, im);
8716  hout->SetBinContent(binx, biny, TMath::Sqrt(re*re + im*im));
8717  }
8718  }
8719  } else {
8720  for (binx = 1; binx<=hout->GetNbinsX(); binx++) {
8721  for (biny=1; biny<=hout->GetNbinsY(); biny++) {
8722  ind[0] = binx-1; ind[1] = biny-1;
8723  hout->SetBinContent(binx, biny, TMath::Abs(fft->GetPointReal(ind)));
8724  }
8725  }
8726  }
8727  }
8728  if (opt.Contains("PH")) {
8729  if (type.Contains("2C") || type.Contains("2HC")){
8730  Double_t re, im, ph;
8731  for (binx = 1; binx<=hout->GetNbinsX(); binx++){
8732  for (biny=1; biny<=hout->GetNbinsY(); biny++){
8733  ind[0] = binx-1; ind[1] = biny-1;
8734  fft->GetPointComplex(ind, re, im);
8735  if (TMath::Abs(re) > 1e-13){
8736  ph = TMath::ATan(im/re);
8737  //find the correct quadrant
8738  if (re<0 && im<0)
8739  ph -= TMath::Pi();
8740  if (re<0 && im>=0)
8741  ph += TMath::Pi();
8742  } else {
8743  if (TMath::Abs(im) < 1e-13)
8744  ph = 0;
8745  else if (im>0)
8746  ph = TMath::Pi()*0.5;
8747  else
8748  ph = -TMath::Pi()*0.5;
8749  }
8750  hout->SetBinContent(binx, biny, ph);
8751  }
8752  }
8753  } else {
8754  printf("Pure real output, no phase");
8755  return 0;
8756  }
8757  }
8758 
8759  return hout;
8760 }
8761 
8762 
8763 ////////////////////////////////////////////////////////////////////////////////
8764 /// raw retrieval of bin content on internal data structure
8765 /// see convention for numbering bins in TH1::GetBin
8766 
8767 Double_t TH1::RetrieveBinContent(Int_t) const
8768 {
8769  AbstractMethod("RetrieveBinContent");
8770  return 0;
8771 }
8772 
8773 
8774 ////////////////////////////////////////////////////////////////////////////////
8775 /// raw update of bin content on internal data structure
8776 /// see convention for numbering bins in TH1::GetBin
8777 
8780  AbstractMethod("UpdateBinContent");
8781 }
8782 
8783 ////////////////////////////////////////////////////////////////////////////////
8784 /// Print value overload
8785 
8786 std::string cling::printValue(TH1 *val) {
8787  std::ostringstream strm;
8788  strm << cling::printValue((TObject*)val) << " NbinsX: " << val->GetNbinsX();
8789  return strm.str();
8790 }
8791 
8792 
8793 //______________________________________________________________________________
8794 // TH1C methods
8795 // TH1C : histograms with one byte per channel. Maximum bin content = 127
8796 //______________________________________________________________________________
8797 
8798 ClassImp(TH1C)
8800 
8801 ////////////////////////////////////////////////////////////////////////////////
8802 /// Constructor.
8803 
8804 TH1C::TH1C(): TH1(), TArrayC()
8805 {
8806  fDimension = 1;
8807  SetBinsLength(3);
8808  if (fgDefaultSumw2) Sumw2();
8809 }
8810 
8811 
8812 ////////////////////////////////////////////////////////////////////////////////
8813 /// Create a 1-Dim histogram with fix bins of type char (one byte per channel)
8814 /// (see TH1::TH1 for explanation of parameters)
8815 
8816 TH1C::TH1C(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
8817 : TH1(name,title,nbins,xlow,xup)
8818 {
8819  fDimension = 1;
8820  TArrayC::Set(fNcells);
8821 
8822  if (xlow >= xup) SetBuffer(fgBufferSize);
8823  if (fgDefaultSumw2) Sumw2();
8824 }
8825 
8826 
8827 ////////////////////////////////////////////////////////////////////////////////
8828 /// Create a 1-Dim histogram with variable bins of type char (one byte per channel)
8829 /// (see TH1::TH1 for explanation of parameters)
8830 
8831 TH1C::TH1C(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
8832 : TH1(name,title,nbins,xbins)
8833 {
8834  fDimension = 1;
8835  TArrayC::Set(fNcells);
8836  if (fgDefaultSumw2) Sumw2();
8837 }
8838 
8839 
8840 ////////////////////////////////////////////////////////////////////////////////
8841 /// Create a 1-Dim histogram with variable bins of type char (one byte per channel)
8842 /// (see TH1::TH1 for explanation of parameters)
8843 
8844 TH1C::TH1C(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
8845 : TH1(name,title,nbins,xbins)
8846 {
8847  fDimension = 1;
8848  TArrayC::Set(fNcells);
8849  if (fgDefaultSumw2) Sumw2();
8850 }
8851 
8852 
8853 ////////////////////////////////////////////////////////////////////////////////
8854 /// Destructor.
8855 
8856 TH1C::~TH1C()
8858 }
8859 
8860 
8861 ////////////////////////////////////////////////////////////////////////////////
8862 /// Copy constructor.
8863 
8864 TH1C::TH1C(const TH1C &h1c) : TH1(), TArrayC()
8866  ((TH1C&)h1c).Copy(*this);
8867 }
8868 
8869 
8870 ////////////////////////////////////////////////////////////////////////////////
8871 /// Increment bin content by 1.
8872 
8873 void TH1C::AddBinContent(Int_t bin)
8875  if (fArray[bin] < 127) fArray[bin]++;
8876 }
8877 
8878 
8879 ////////////////////////////////////////////////////////////////////////////////
8880 /// Increment bin content by w.
8881 
8884  Int_t newval = fArray[bin] + Int_t(w);
8885  if (newval > -128 && newval < 128) {fArray[bin] = Char_t(newval); return;}
8886  if (newval < -127) fArray[bin] = -127;
8887  if (newval > 127) fArray[bin] = 127;
8888 }
8889 
8890 
8891 ////////////////////////////////////////////////////////////////////////////////
8892 /// Copy this to newth1
8893 
8894 void TH1C::Copy(TObject &newth1) const
8896  TH1::Copy(newth1);
8897 }
8898 
8899 
8900 ////////////////////////////////////////////////////////////////////////////////
8901 /// Reset.
8902 
8903 void TH1C::Reset(Option_t *option)
8905  TH1::Reset(option);
8906  TArrayC::Reset();
8907 }
8908 
8909 
8910 ////////////////////////////////////////////////////////////////////////////////
8911 /// Set total number of bins including under/overflow
8912 /// Reallocate bin contents array
8913 
8914 void TH1C::SetBinsLength(Int_t n)
8916  if (n < 0) n = fXaxis.GetNbins() + 2;
8917  fNcells = n;
8918  TArrayC::Set(n);
8919 }
8920 
8921 
8922 ////////////////////////////////////////////////////////////////////////////////
8923 /// Operator =
8924 
8925 TH1C& TH1C::operator=(const TH1C &h1)
8927  if (this != &h1) ((TH1C&)h1).Copy(*this);
8928  return *this;
8929 }
8930 
8931 
8932 
8933 ////////////////////////////////////////////////////////////////////////////////
8934 /// Operator *
8935 
8936 TH1C operator*(Double_t c1, const TH1C &h1)
8938  TH1C hnew = h1;
8939  hnew.Scale(c1);
8940  hnew.SetDirectory(0);
8941  return hnew;
8942 }
8943 
8944 
8945 ////////////////////////////////////////////////////////////////////////////////
8946 /// Operator +
8947 
8948 TH1C operator+(const TH1C &h1, const TH1C &h2)
8950  TH1C hnew = h1;
8951  hnew.Add(&h2,1);
8952  hnew.SetDirectory(0);
8953  return hnew;
8954 }
8955 
8956 
8957 ////////////////////////////////////////////////////////////////////////////////
8958 /// Operator -
8959 
8960 TH1C operator-(const TH1C &h1, const TH1C &h2)
8962  TH1C hnew = h1;
8963  hnew.Add(&h2,-1);
8964  hnew.SetDirectory(0);
8965  return hnew;
8966 }
8967 
8968 
8969 ////////////////////////////////////////////////////////////////////////////////
8970 /// Operator *
8971 
8972 TH1C operator*(const TH1C &h1, const TH1C &h2)
8974  TH1C hnew = h1;
8975  hnew.Multiply(&h2);
8976  hnew.SetDirectory(0);
8977  return hnew;
8978 }
8979 
8980 
8981 ////////////////////////////////////////////////////////////////////////////////
8982 /// Operator /
8983 
8984 TH1C operator/(const TH1C &h1, const TH1C &h2)
8986  TH1C hnew = h1;
8987  hnew.Divide(&h2);
8988  hnew.SetDirectory(0);
8989  return hnew;
8990 }
8991 
8992 
8993 
8994 //______________________________________________________________________________
8995 // TH1S methods
8996 // TH1S : histograms with one short per channel. Maximum bin content = 32767
8997 //______________________________________________________________________________
8998 
8999 ClassImp(TH1S)
9001 
9002 ////////////////////////////////////////////////////////////////////////////////
9003 /// Constructor.
9004 
9005 TH1S::TH1S(): TH1(), TArrayS()
9006 {
9007  fDimension = 1;
9008  SetBinsLength(3);
9009  if (fgDefaultSumw2) Sumw2();
9010 }
9011 
9012 
9013 ////////////////////////////////////////////////////////////////////////////////
9014 /// Create a 1-Dim histogram with fix bins of type short
9015 /// (see TH1::TH1 for explanation of parameters)
9016 
9017 TH1S::TH1S(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
9018 : TH1(name,title,nbins,xlow,xup)
9019 {
9020  fDimension = 1;
9021  TArrayS::Set(fNcells);
9022 
9023  if (xlow >= xup) SetBuffer(fgBufferSize);
9024  if (fgDefaultSumw2) Sumw2();
9025 }
9026 
9027 
9028 ////////////////////////////////////////////////////////////////////////////////
9029 /// Create a 1-Dim histogram with variable bins of type short
9030 /// (see TH1::TH1 for explanation of parameters)
9031 
9032 TH1S::TH1S(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
9033 : TH1(name,title,nbins,xbins)
9034 {
9035  fDimension = 1;
9036  TArrayS::Set(fNcells);
9037  if (fgDefaultSumw2) Sumw2();
9038 }
9039 
9040 
9041 ////////////////////////////////////////////////////////////////////////////////
9042 /// Create a 1-Dim histogram with variable bins of type short
9043 /// (see TH1::TH1 for explanation of parameters)
9044 
9045 TH1S::TH1S(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
9046 : TH1(name,title,nbins,xbins)
9047 {
9048  fDimension = 1;
9049  TArrayS::Set(fNcells);
9050  if (fgDefaultSumw2) Sumw2();
9051 }
9052 
9053 
9054 ////////////////////////////////////////////////////////////////////////////////
9055 /// Destructor.
9056 
9057 TH1S::~TH1S()
9059 }
9060 
9061 
9062 ////////////////////////////////////////////////////////////////////////////////
9063 /// Copy constructor.
9064 
9065 TH1S::TH1S(const TH1S &h1s) : TH1(), TArrayS()
9067  ((TH1S&)h1s).Copy(*this);
9068 }
9069 
9070 
9071 ////////////////////////////////////////////////////////////////////////////////
9072 /// Increment bin content by 1.
9073 
9074 void TH1S::AddBinContent(Int_t bin)
9076  if (fArray[bin] < 32767) fArray[bin]++;
9077 }
9078 
9079 
9080 ////////////////////////////////////////////////////////////////////////////////
9081 /// Increment bin content by w
9082 
9085  Int_t newval = fArray[bin] + Int_t(w);
9086  if (newval > -32768 && newval < 32768) {fArray[bin] = Short_t(newval); return;}
9087  if (newval < -32767) fArray[bin] = -32767;
9088  if (newval > 32767) fArray[bin] = 32767;
9089 }
9090 
9091 
9092 ////////////////////////////////////////////////////////////////////////////////
9093 /// Copy this to newth1
9094 
9095 void TH1S::Copy(TObject &newth1) const
9097  TH1::Copy(newth1);
9098 }
9099 
9100 
9101 ////////////////////////////////////////////////////////////////////////////////
9102 /// Reset.
9103 
9104 void TH1S::Reset(Option_t *option)
9106  TH1::Reset(option);
9107  TArrayS::Reset();
9108 }
9109 
9110 
9111 ////////////////////////////////////////////////////////////////////////////////
9112 /// Set total number of bins including under/overflow
9113 /// Reallocate bin contents array
9114 
9115 void TH1S::SetBinsLength(Int_t n)
9117  if (n < 0) n = fXaxis.GetNbins() + 2;
9118  fNcells = n;
9119  TArrayS::Set(n);
9120 }
9121 
9122 
9123 ////////////////////////////////////////////////////////////////////////////////
9124 /// Operator =
9125 
9126 TH1S& TH1S::operator=(const TH1S &h1)
9128  if (this != &h1) ((TH1S&)h1).Copy(*this);
9129  return *this;
9130 }
9131 
9132 
9133 ////////////////////////////////////////////////////////////////////////////////
9134 /// Operator *
9135 
9136 TH1S operator*(Double_t c1, const TH1S &h1)
9138  TH1S hnew = h1;
9139  hnew.Scale(c1);
9140  hnew.SetDirectory(0);
9141  return hnew;
9142 }
9143 
9144 
9145 ////////////////////////////////////////////////////////////////////////////////
9146 /// Operator +
9147 
9148 TH1S operator+(const TH1S &h1, const TH1S &h2)
9150  TH1S hnew = h1;
9151  hnew.Add(&h2,1);
9152  hnew.SetDirectory(0);
9153  return hnew;
9154 }
9155 
9156 
9157 ////////////////////////////////////////////////////////////////////////////////
9158 /// Operator -
9159 
9160 TH1S operator-(const TH1S &h1, const TH1S &h2)
9162  TH1S hnew = h1;
9163  hnew.Add(&h2,-1);
9164  hnew.SetDirectory(0);
9165  return hnew;
9166 }
9167 
9168 
9169 ////////////////////////////////////////////////////////////////////////////////
9170 /// Operator *
9171 
9172 TH1S operator*(const TH1S &h1, const TH1S &h2)
9174  TH1S hnew = h1;
9175  hnew.Multiply(&h2);
9176  hnew.SetDirectory(0);
9177  return hnew;
9178 }
9179 
9180 
9181 ////////////////////////////////////////////////////////////////////////////////
9182 /// Operator /
9183 
9184 TH1S operator/(const TH1S &h1, const TH1S &h2)
9186  TH1S hnew = h1;
9187  hnew.Divide(&h2);
9188  hnew.SetDirectory(0);
9189  return hnew;
9190 }
9191 
9192 
9193 //______________________________________________________________________________
9194 // TH1I methods
9195 // TH1I : histograms with one int per channel. Maximum bin content = 2147483647
9196 //______________________________________________________________________________
9197 
9198 ClassImp(TH1I)
9200 
9201 ////////////////////////////////////////////////////////////////////////////////
9202 /// Constructor.
9203 
9204 TH1I::TH1I(): TH1(), TArrayI()
9205 {
9206  fDimension = 1;
9207  SetBinsLength(3);
9208  if (fgDefaultSumw2) Sumw2();
9209 }
9210 
9211 
9212 ////////////////////////////////////////////////////////////////////////////////
9213 /// Create a 1-Dim histogram with fix bins of type integer
9214 /// (see TH1::TH1 for explanation of parameters)
9215 
9216 TH1I::TH1I(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
9217 : TH1(name,title,nbins,xlow,xup)
9218 {
9219  fDimension = 1;
9220  TArrayI::Set(fNcells);
9221 
9222  if (xlow >= xup) SetBuffer(fgBufferSize);
9223  if (fgDefaultSumw2) Sumw2();
9224 }
9225 
9226 
9227 ////////////////////////////////////////////////////////////////////////////////
9228 /// Create a 1-Dim histogram with variable bins of type integer
9229 /// (see TH1::TH1 for explanation of parameters)
9230 
9231 TH1I::TH1I(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
9232 : TH1(name,title,nbins,xbins)
9233 {
9234  fDimension = 1;
9235  TArrayI::Set(fNcells);
9236  if (fgDefaultSumw2) Sumw2();
9237 }
9238 
9239 
9240 ////////////////////////////////////////////////////////////////////////////////
9241 /// Create a 1-Dim histogram with variable bins of type integer
9242 /// (see TH1::TH1 for explanation of parameters)
9243 
9244 TH1I::TH1I(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
9245 : TH1(name,title,nbins,xbins)
9246 {
9247  fDimension = 1;
9248  TArrayI::Set(fNcells);
9249  if (fgDefaultSumw2) Sumw2();
9250 }
9251 
9252 
9253 ////////////////////////////////////////////////////////////////////////////////
9254 /// Destructor.
9255 
9256 TH1I::~TH1I()
9258 }
9259 
9260 
9261 ////////////////////////////////////////////////////////////////////////////////
9262 /// Copy constructor.
9263 
9264 TH1I::TH1I(const TH1I &h1i) : TH1(), TArrayI()
9266  ((TH1I&)h1i).Copy(*this);
9267 }
9268 
9269 
9270 ////////////////////////////////////////////////////////////////////////////////
9271 /// Increment bin content by 1.
9272 
9273 void TH1I::AddBinContent(Int_t bin)
9275  if (fArray[bin] < 2147483647) fArray[bin]++;
9276 }
9277 
9278 
9279 ////////////////////////////////////////////////////////////////////////////////
9280 /// Increment bin content by w
9281 
9284  Int_t newval = fArray[bin] + Int_t(w);
9285  if (newval > -2147483647 && newval < 2147483647) {fArray[bin] = Int_t(newval); return;}
9286  if (newval < -2147483647) fArray[bin] = -2147483647;
9287  if (newval > 2147483647) fArray[bin] = 2147483647;
9288 }
9289 
9290 
9291 ////////////////////////////////////////////////////////////////////////////////
9292 /// Copy this to newth1
9293 
9294 void TH1I::Copy(TObject &newth1) const
9296  TH1::Copy(newth1);
9297 }
9298 
9299 
9300 ////////////////////////////////////////////////////////////////////////////////
9301 /// Reset.
9302 
9303 void TH1I::Reset(Option_t *option)
9305  TH1::Reset(option);
9306  TArrayI::Reset();
9307 }
9308 
9309 
9310 ////////////////////////////////////////////////////////////////////////////////
9311 /// Set total number of bins including under/overflow
9312 /// Reallocate bin contents array
9313 
9314 void TH1I::SetBinsLength(Int_t n)
9316  if (n < 0) n = fXaxis.GetNbins() + 2;
9317  fNcells = n;
9318  TArrayI::Set(n);
9319 }
9320 
9321 
9322 ////////////////////////////////////////////////////////////////////////////////
9323 /// Operator =
9324 
9325 TH1I& TH1I::operator=(const TH1I &h1)
9327  if (this != &h1) ((TH1I&)h1).Copy(*this);
9328  return *this;
9329 }
9330 
9331 
9332 
9333 ////////////////////////////////////////////////////////////////////////////////
9334 /// Operator *
9335 
9336 TH1I operator*(Double_t c1, const TH1I &h1)
9338  TH1I hnew = h1;
9339  hnew.Scale(c1);
9340  hnew.SetDirectory(0);
9341  return hnew;
9342 }
9343 
9344 
9345 ////////////////////////////////////////////////////////////////////////////////
9346 /// Operator +
9347 
9348 TH1I operator+(const TH1I &h1, const TH1I &h2)
9350  TH1I hnew = h1;
9351  hnew.Add(&h2,1);
9352  hnew.SetDirectory(0);
9353  return hnew;
9354 }
9355 
9356 
9357 ////////////////////////////////////////////////////////////////////////////////
9358 /// Operator -
9359 
9360 TH1I operator-(const TH1I &h1, const TH1I &h2)
9362  TH1I hnew = h1;
9363  hnew.Add(&h2,-1);
9364  hnew.SetDirectory(0);
9365  return hnew;
9366 }
9367 
9368 
9369 ////////////////////////////////////////////////////////////////////////////////
9370 /// Operator *
9371 
9372 TH1I operator*(const TH1I &h1, const TH1I &h2)
9374  TH1I hnew = h1;
9375  hnew.Multiply(&h2);
9376  hnew.SetDirectory(0);
9377  return hnew;
9378 }
9379 
9380 
9381 ////////////////////////////////////////////////////////////////////////////////
9382 /// Operator /
9383 
9384 TH1I operator/(const TH1I &h1, const TH1I &h2)
9386  TH1I hnew = h1;
9387  hnew.Divide(&h2);
9388  hnew.SetDirectory(0);
9389  return hnew;
9390 }
9391 
9392 
9393 //______________________________________________________________________________
9394 // TH1F methods
9395 // TH1F : histograms with one float per channel. Maximum precision 7 digits
9396 //______________________________________________________________________________
9397 
9398 ClassImp(TH1F)
9400 
9401 ////////////////////////////////////////////////////////////////////////////////
9402 /// Constructor.
9403 
9404 TH1F::TH1F(): TH1(), TArrayF()
9405 {
9406  fDimension = 1;
9407  SetBinsLength(3);
9408  if (fgDefaultSumw2) Sumw2();
9409 }
9410 
9411 
9412 ////////////////////////////////////////////////////////////////////////////////
9413 /// Create a 1-Dim histogram with fix bins of type float
9414 /// (see TH1::TH1 for explanation of parameters)
9415 
9416 TH1F::TH1F(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
9417 : TH1(name,title,nbins,xlow,xup)
9418 {
9419  fDimension = 1;
9420  TArrayF::Set(fNcells);
9421 
9422  if (xlow >= xup) SetBuffer(fgBufferSize);
9423  if (fgDefaultSumw2) Sumw2();
9424 }
9425 
9426 
9427 ////////////////////////////////////////////////////////////////////////////////
9428 /// Create a 1-Dim histogram with variable bins of type float
9429 /// (see TH1::TH1 for explanation of parameters)
9430 
9431 TH1F::TH1F(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
9432 : TH1(name,title,nbins,xbins)
9433 {
9434  fDimension = 1;
9435  TArrayF::Set(fNcells);
9436  if (fgDefaultSumw2) Sumw2();
9437 }
9438 
9439 
9440 ////////////////////////////////////////////////////////////////////////////////
9441 /// Create a 1-Dim histogram with variable bins of type float
9442 /// (see TH1::TH1 for explanation of parameters)
9443 
9444 TH1F::TH1F(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
9445 : TH1(name,title,nbins,xbins)
9446 {
9447  fDimension = 1;
9448  TArrayF::Set(fNcells);
9449  if (fgDefaultSumw2) Sumw2();
9450 }
9451 
9452 
9453 ////////////////////////////////////////////////////////////////////////////////
9454 /// Create a histogram from a TVectorF
9455 /// by default the histogram name is "TVectorF" and title = ""
9456 
9457 TH1F::TH1F(const TVectorF &v)
9458 : TH1("TVectorF","",v.GetNrows(),0,v.GetNrows())
9459 {
9460  TArrayF::Set(fNcells);
9461  fDimension = 1;
9462  Int_t ivlow = v.GetLwb();
9463  for (Int_t i=0;i<fNcells-2;i++) {
9464  SetBinContent(i+1,v(i+ivlow));
9465  }
9466  TArrayF::Set(fNcells);
9467  if (fgDefaultSumw2) Sumw2();
9468 }
9469 
9470 
9471 ////////////////////////////////////////////////////////////////////////////////
9472 /// Copy Constructor.
9473 
9474 TH1F::TH1F(const TH1F &h) : TH1(), TArrayF()
9476  ((TH1F&)h).Copy(*this);
9477 }
9478 
9479 
9480 ////////////////////////////////////////////////////////////////////////////////
9481 /// Destructor.
9482 
9483 TH1F::~TH1F()
9485 }
9486 
9487 
9488 ////////////////////////////////////////////////////////////////////////////////
9489 /// Copy this to newth1.
9490 
9491 void TH1F::Copy(TObject &newth1) const
9493  TH1::Copy(newth1);
9494 }
9495 
9496 
9497 ////////////////////////////////////////////////////////////////////////////////
9498 /// Reset.
9499 
9500 void TH1F::Reset(Option_t *option)
9502  TH1::Reset(option);
9503  TArrayF::Reset();
9504 }
9505 
9506 
9507 ////////////////////////////////////////////////////////////////////////////////
9508 /// Set total number of bins including under/overflow
9509 /// Reallocate bin contents array
9510 
9511 void TH1F::SetBinsLength(Int_t n)
9513  if (n < 0) n = fXaxis.GetNbins() + 2;
9514  fNcells = n;
9515  TArrayF::Set(n);
9516 }
9517 
9518 
9519 ////////////////////////////////////////////////////////////////////////////////
9520 /// Operator =
9521 
9522 TH1F& TH1F::operator=(const TH1F &h1)
9524  if (this != &h1) ((TH1F&)h1).Copy(*this);
9525  return *this;
9526 }
9527 
9528 
9529 ////////////////////////////////////////////////////////////////////////////////
9530 /// Operator *
9531 
9532 TH1F operator*(Double_t c1, const TH1F &h1)
9534  TH1F hnew = h1;
9535  hnew.Scale(c1);
9536  hnew.SetDirectory(0);
9537  return hnew;
9538 }
9539 
9540 
9541 ////////////////////////////////////////////////////////////////////////////////
9542 /// Operator +
9543 
9544 TH1F operator+(const TH1F &h1, const TH1F &h2)
9546  TH1F hnew = h1;
9547  hnew.Add(&h2,1);
9548  hnew.SetDirectory(0);
9549  return hnew;
9550 }
9551 
9552 
9553 ////////////////////////////////////////////////////////////////////////////////
9554 /// Operator -
9555 
9556 TH1F operator-(const TH1F &h1, const TH1F &h2)
9558  TH1F hnew = h1;
9559  hnew.Add(&h2,-1);
9560  hnew.SetDirectory(0);
9561  return hnew;
9562 }
9563 
9564 
9565 ////////////////////////////////////////////////////////////////////////////////
9566 /// Operator *
9567 
9568 TH1F operator*(const TH1F &h1, const TH1F &h2)
9570  TH1F hnew = h1;
9571  hnew.Multiply(&h2);
9572  hnew.SetDirectory(0);
9573  return hnew;
9574 }
9575 
9576 
9577 ////////////////////////////////////////////////////////////////////////////////
9578 /// Operator /
9579 
9580 TH1F operator/(const TH1F &h1, const TH1F &h2)
9582  TH1F hnew = h1;
9583  hnew.Divide(&h2);
9584  hnew.SetDirectory(0);
9585  return hnew;
9586 }
9587 
9588 
9589 
9590 //______________________________________________________________________________
9591 // TH1D methods
9592 // TH1D : histograms with one double per channel. Maximum precision 14 digits
9593 //______________________________________________________________________________
9594 
9595 ClassImp(TH1D)
9597 
9598 ////////////////////////////////////////////////////////////////////////////////
9599 /// Constructor.
9600 
9601 TH1D::TH1D(): TH1(), TArrayD()
9602 {
9603  fDimension = 1;
9604  SetBinsLength(3);
9605  if (fgDefaultSumw2) Sumw2();
9606 }
9607 
9608 
9609 ////////////////////////////////////////////////////////////////////////////////
9610 /// Create a 1-Dim histogram with fix bins of type double
9611 /// (see TH1::TH1 for explanation of parameters)
9612 
9613 TH1D::TH1D(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
9614 : TH1(name,title,nbins,xlow,xup)
9615 {
9616  fDimension = 1;
9617  TArrayD::Set(fNcells);
9618 
9619  if (xlow >= xup) SetBuffer(fgBufferSize);
9620  if (fgDefaultSumw2) Sumw2();
9621 }
9622 
9623 
9624 ////////////////////////////////////////////////////////////////////////////////
9625 /// Create a 1-Dim histogram with variable bins of type double
9626 /// (see TH1::TH1 for explanation of parameters)
9627 
9628 TH1D::TH1D(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
9629 : TH1(name,title,nbins,xbins)
9630 {
9631  fDimension = 1;
9632  TArrayD::Set(fNcells);
9633  if (fgDefaultSumw2) Sumw2();
9634 }
9635 
9636 
9637 ////////////////////////////////////////////////////////////////////////////////
9638 /// Create a 1-Dim histogram with variable bins of type double
9639 /// (see TH1::TH1 for explanation of parameters)
9640 
9641 TH1D::TH1D(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
9642 : TH1(name,title,nbins,xbins)
9643 {
9644  fDimension = 1;
9645  TArrayD::Set(fNcells);
9646  if (fgDefaultSumw2) Sumw2();
9647 }
9648 
9649 
9650 ////////////////////////////////////////////////////////////////////////////////
9651 /// Create a histogram from a TVectorD
9652 /// by default the histogram name is "TVectorD" and title = ""
9653 
9654 TH1D::TH1D(const TVectorD &v)
9655 : TH1("TVectorD","",v.GetNrows(),0,v.GetNrows())
9656 {
9657  TArrayD::Set(fNcells);
9658  fDimension = 1;
9659  Int_t ivlow = v.GetLwb();
9660  for (Int_t i=0;i<fNcells-2;i++) {
9661  SetBinContent(i+1,v(i+ivlow));
9662  }
9663  TArrayD::Set(fNcells);
9664  if (fgDefaultSumw2) Sumw2();
9665 }
9666 
9667 
9668 ////////////////////////////////////////////////////////////////////////////////
9669 /// Destructor.
9670 
9671 TH1D::~TH1D()
9673 }
9674 
9675 
9676 ////////////////////////////////////////////////////////////////////////////////
9677 /// Constructor.
9678 
9679 TH1D::TH1D(const TH1D &h1d) : TH1(), TArrayD()
9681  ((TH1D&)h1d).Copy(*this);
9682 }
9683 
9684 
9685 ////////////////////////////////////////////////////////////////////////////////
9686 /// Copy this to newth1
9687 
9688 void TH1D::Copy(TObject &newth1) const
9690  TH1::Copy(newth1);
9691 }
9692 
9693 
9694 ////////////////////////////////////////////////////////////////////////////////
9695 /// Reset.
9696 
9697 void TH1D::Reset(Option_t *option)
9699  TH1::Reset(option);
9700  TArrayD::Reset();
9701 }
9702 
9703 
9704 ////////////////////////////////////////////////////////////////////////////////
9705 /// Set total number of bins including under/overflow
9706 /// Reallocate bin contents array
9707 
9708 void TH1D::SetBinsLength(Int_t n)
9710  if (n < 0) n = fXaxis.GetNbins() + 2;
9711  fNcells = n;
9712  TArrayD::Set(n);
9713 }
9714 
9715 
9716 ////////////////////////////////////////////////////////////////////////////////
9717 /// Operator =
9718 
9719 TH1D& TH1D::operator=(const TH1D &h1)
9721  if (this != &h1) ((TH1D&)h1).Copy(*this);
9722  return *this;
9723 }
9724 
9725 
9726 ////////////////////////////////////////////////////////////////////////////////
9727 /// Operator *
9728 
9729 TH1D operator*(Double_t c1, const TH1D &h1)
9731  TH1D hnew = h1;
9732  hnew.Scale(c1);
9733  hnew.SetDirectory(0);
9734  return hnew;
9735 }
9736 
9737 
9738 ////////////////////////////////////////////////////////////////////////////////
9739 /// Operator +
9740 
9741 TH1D operator+(const TH1D &h1, const TH1D &h2)
9743  TH1D hnew = h1;
9744  hnew.Add(&h2,1);
9745  hnew.SetDirectory(0);
9746  return hnew;
9747 }
9748 
9749 
9750 ////////////////////////////////////////////////////////////////////////////////
9751 /// Operator -
9752 
9753 TH1D operator-(const TH1D &h1, const TH1D &h2)
9755  TH1D hnew = h1;
9756  hnew.Add(&h2,-1);
9757  hnew.SetDirectory(0);
9758  return hnew;
9759 }
9760 
9761 
9762 ////////////////////////////////////////////////////////////////////////////////
9763 /// Operator *
9764 
9765 TH1D operator*(const TH1D &h1, const TH1D &h2)
9767  TH1D hnew = h1;
9768  hnew.Multiply(&h2);
9769  hnew.SetDirectory(0);
9770  return hnew;
9771 }
9772 
9773 
9774 ////////////////////////////////////////////////////////////////////////////////
9775 /// Operator /
9776 
9777 TH1D operator/(const TH1D &h1, const TH1D &h2)
9779  TH1D hnew = h1;
9780  hnew.Divide(&h2);
9781  hnew.SetDirectory(0);
9782  return hnew;
9783 }
9784 
9785 
9786 ////////////////////////////////////////////////////////////////////////////////
9787 ///return pointer to histogram with name
9788 ///hid if id >=0
9789 ///h_id if id <0
9790 
9791 TH1 *R__H(Int_t hid)
9793  TString hname;
9794  if(hid >= 0) hname.Form("h%d",hid);
9795  else hname.Form("h_%d",hid);
9796  return (TH1*)gDirectory->Get(hname);
9797 }
9798 
9799 
9800 ////////////////////////////////////////////////////////////////////////////////
9801 ///return pointer to histogram with name hname
9802 
9803 TH1 *R__H(const char * hname)
9805  return (TH1*)gDirectory->Get(hname);
9806 }
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:6487
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)
Browe the Histogram object.
Definition: TH1.cxx:718
for(Int_t i=0;i< n;i++)
Definition: legend1.C:18
Int_t GetFirst() const
Return first bin on the axis i.e.
Definition: TAxis.cxx:429
virtual void SavePrimitive(std::ostream &out, Option_t *option="")
Save primitive as a C++ statement(s) on output stream out.
Definition: TH1.cxx:6723
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:245
tuple labels
Definition: mrt.py:18
virtual Int_t GetEntries() const
Definition: TCollection.h:92
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:9709
void Copy(TAttMarker &attmarker) const
Copy this marker attributes to a new TAttMarker.
Definition: TAttMarker.cxx:191
virtual Style_t GetLineStyle() const
Definition: TAttLine.h:48
virtual Style_t GetFillStyle() const
Definition: TAttFill.h:44
virtual void SetNameTitle(const char *name, const char *title)
Change the name and title of this histogram.
Definition: TH1.cxx:8303
virtual void SetLineWidth(Width_t lwidth)
Definition: TAttLine.h:57
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:3478
Double_t fNormFactor
Definition: TH1.h:114
virtual void SetBarOffset(Float_t offset=0.25)
Definition: TH1.h:356
virtual void Scale(Double_t c1=1, Option_t *option="")
Multiply this histogram by a constant c1.
Definition: TH1.cxx:6174
virtual Color_t GetAxisColor() const
Definition: TAttAxis.h:51
virtual Int_t Fill(Double_t x)
Increment bin with abscissa X by 1.
Definition: TH1.cxx:3159
virtual Int_t ShowPeaks(Double_t sigma=2, Option_t *option="", Double_t threshold=0.05)
Interface to TSpectrum::Search.
Definition: TH1.cxx:8628
virtual Double_t GetBinErrorLow(Int_t bin) const
Return lower error associated to bin number bin.
Definition: TH1.cxx:8412
TList * GetListOfFunctions() const
Definition: TH1.h:244
TH1D & operator=(const TH1D &h1)
Operator =.
Definition: TH1.cxx:9720
void SetBarWidth(Float_t barwidth=0.5)
Definition: TStyle.h:332
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:631
virtual void Paint(Option_t *option="")
Control routine to paint any kind of histograms.
Definition: TH1.cxx:5798
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:2954
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:52
virtual void GetLowEdge(Double_t *edge) const
Return an array with the lod edge of all bins.
Definition: TAxis.cxx:533
tuple buffer
Definition: tree.py:99
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:9257
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:4629
Bool_t IsBinOverflow(Int_t bin) const
Definition: TH1.cxx:4732
static float fu(float x)
Definition: main.cpp:53
virtual void SetMaximum(Double_t maximum=-1111)
Definition: TH1.h:394
void UseCurrentStyle()
Copy current attributes from/to current style.
Definition: TH1.cxx:6950
Bool_t CanExtend() const
Definition: TAxis.h:90
virtual void LabelsOption(Option_t *option="h", Option_t *axis="X")
Set option(s) to draw axis with labels.
Definition: TH1.cxx:4901
short Style_t
Definition: RtypesCore.h:76
virtual void SetLimits(Double_t xmin, Double_t xmax)
Definition: TAxis.h:154
virtual Double_t Chi2TestX(const TH1 *h2, Double_t &chi2, Int_t &ndf, Int_t &igood, Option_t *option="UU", Double_t *res=0) const
The computation routine of the Chisquare test.
Definition: TH1.cxx:1909
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:3559
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
Definition: TH1.h:106
virtual Bool_t InheritsFrom(const char *classname) const
Returns kTRUE if object inherits from class "classname".
Definition: TObject.cxx:487
short Version_t
Definition: RtypesCore.h:61
static Bool_t fgDefaultSumw2
flag to use under/overflows in statistics
Definition: TH1.h:129
ClassImp(TSeqCollection) Int_t TSeqCollection TIter next(this)
Return index of object in collection.
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 if painter does not exist, it is created
Definition: TH1.cxx:4096
virtual void FitPanel()
Display a panel with all histogram fit options.
Definition: TH1.cxx:3912
float Float_t
Definition: RtypesCore.h:53
virtual Double_t Rndm(Int_t i=0)
Machine independent random number generator.
Definition: TRandom.cxx:512
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:8266
Bool_t GetCanvasPreferGL() const
Definition: TStyle.h:197
Short_t * fArray
Definition: TArrayS.h:32
Style_t GetHistLineStyle() const
Definition: TStyle.h:244
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:7270
return c
virtual Int_t GetMaximumBin() const
Return location of bin with maximum value in the range.
Definition: TH1.cxx:7952
const char Option_t
Definition: RtypesCore.h:62
const char * GetBinLabel(Int_t bin) const
Return label for bin.
Definition: TAxis.cxx:411
Double_t KolmogorovProb(Double_t z)
Calculates the Kolmogorov distribution function, Begin_Html.
Definition: TMath.cxx:635
TCanvas * c1
Definition: legend1.C:2
void Reset()
Definition: TArrayD.h:49
float ymin
Definition: THbookFile.cxx:93
virtual Double_t Chi2Test(const TH1 *h2, Option_t *option="UU", Double_t *res=0) const
chi^{2} test for comparing weighted and unweighted histograms
Definition: TH1.cxx:1850
virtual void Set(Int_t n)=0
virtual void ResetAttAxis(Option_t *option="")
Reset axis attributes.
Definition: TAttAxis.cxx:62
Double_t QuietNaN()
Definition: TMath.h:635
virtual void SetError(const Double_t *error)
Replace bin errors by values in array error.
Definition: TH1.cxx:8278
Bool_t IsBinUnderflow(Int_t bin) const
Definition: TH1.cxx:4754
TString & ReplaceAll(const TString &s1, const TString &s2)
Definition: TString.h:635
#define assert(cond)
Definition: unittest.h:542
TAxis fYaxis
Definition: TH1.h:103
virtual Int_t BufferFill(Double_t x, Double_t w)
accumulate arguments in buffer.
Definition: TH1.cxx:1334
virtual void SetContour(Int_t nlevels, const Double_t *levels=0)
Set the number and values of contour levels.
Definition: TH1.cxx:7863
R__EXTERN TStyle * gStyle
Definition: TStyle.h:423
virtual void PutStats(Double_t *stats)
Replace current statistics with the values in array stats.
Definition: TH1.cxx:7323
void SetHistLineWidth(Width_t width=1)
Definition: TStyle.h:378
virtual Int_t GetDimension() const
Definition: TH1.h:283
TList * fFunctions
Definition: TH1.h:118
virtual void SetBins(Int_t nx, Double_t xmin, Double_t xmax)
Redefine x axis parameters.
Definition: TH1.cxx:8090
virtual void SetName(const char *name)
Change (i.e.
Definition: TNamed.cxx:128
tuple f2
Definition: surfaces.py:24
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:3964
static Bool_t fgStatOverflows
flag to add histograms to the directory
Definition: TH1.h:128
static Bool_t SameLimitsAndNBins(const TAxis &axis1, const TAxis &axis2)
Same limits and bins.
Definition: TH1.cxx:5184
virtual ~TH1F()
Destructor.
Definition: TH1.cxx:9484
virtual void SetLabelColor(Color_t color=1, Float_t alpha=1.)
Set color of labels.
Definition: TAttAxis.cxx:156
void Build()
Creates histogram basic data structure.
Definition: TH1.cxx:728
virtual void Info(const char *method, const char *msgfmt,...) const
Issue info message.
Definition: TObject.cxx:892
void f3()
Definition: na49.C:50
virtual void SetNdivisions(Int_t n=510, Bool_t optim=kTRUE)
Set the number of divisions for this axis.
Definition: TAttAxis.cxx:212
virtual Bool_t GetTimeDisplay() const
Definition: TAxis.h:130
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:4182
void Copy(TAttLine &attline) const
Copy this line attributes to a new TAttLine.
Definition: TAttLine.cxx:159
virtual void AddFirst(TObject *obj)
Add object at the beginning of the list.
Definition: TList.cxx:93
tuple label2
Definition: h1draw.py:46
void ToUpper()
Change string to upper case.
Definition: TString.cxx:1088
virtual void Reset(Option_t *option="")
Reset.
Definition: TH1.cxx:8904
static bool CheckAxisLimits(const TAxis *a1, const TAxis *a2)
Check that the axis limits of the histograms are the same if a first and last bin is passed the axis ...
Definition: TH1.cxx:1429
Buffer base class used for serializing objects.
Definition: TBuffer.h:42
virtual Double_t GetBinLowEdge(Int_t bin) const
Return low edge of bin.
Definition: TAxis.cxx:489
virtual void Copy(TObject &hnew) const
Copy this to newth1.
Definition: TH1.cxx:8895
virtual void Copy(TObject &hnew) const
Copy this to newth1.
Definition: TH1.cxx:9096
#define R__ASSERT(e)
Definition: TError.h:98
virtual void SetMinimum(Double_t minimum=-1111)
Definition: TH1.h:395
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:344
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...
void Copy(TArrayS &array) const
Definition: TArrayS.h:44
Basic string class.
Definition: TString.h:137
static Bool_t AddDirectoryStatus()
static function: cannot be inlined on Windows/NT
Definition: TH1.cxx:709
1-D histogram with a float per channel (see TH1 documentation)}
Definition: TH1.h:570
virtual TObject * GetUserFunc() const
1-D histogram with a short per channel (see TH1 documentation)
Definition: TH1.h:488
void H1InitExpo()
Compute Initial values of parameters for an exponential.
Definition: TH1.cxx:4291
Array of floats (32 bits per element).
Definition: TArrayF.h:29
virtual Double_t GetNormFactor() const
Definition: TH1.h:300
void Copy(TAttFill &attfill) const
Copy this fill attributes to a new TAttFill.
Definition: TAttFill.cxx:197
virtual void SetTitleFont(Style_t font=62)
Set the title font.
Definition: TAttAxis.cxx:273
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:2445
Short_t Min(Short_t a, Short_t b)
Definition: TMathBase.h:170
void ToLower()
Change string to lower-case.
Definition: TString.cxx:1075
int Int_t
Definition: RtypesCore.h:41
ROOT::NewFunc_t GetNew() const
Return the wrapper around new ThisClass().
Definition: TClass.cxx:6793
bool Bool_t
Definition: RtypesCore.h:59
void SetBarOffset(Float_t baroff=0.5)
Definition: TStyle.h:331
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:59
virtual Double_t GetBinWidth(Int_t bin) const
Return bin width.
Definition: TAxis.cxx:511
Int_t GetOptStat() const
Definition: TStyle.h:253
virtual void SetFillStyle(Style_t fstyle)
Definition: TAttFill.h:52
virtual void Smooth(Int_t ntimes=1, Option_t *option="")
Smooth bin contents of this histogram.
Definition: TH1.cxx:6440
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:502
int nbins[3]
virtual Double_t GetStdDevError(Int_t axis=1) const
Return error of standard deviation estimation for Normal distribution.
Definition: TH1.cxx:7105
TArrayD fSumw2
Definition: TH1.h:116
virtual Style_t GetTitleFont() const
Definition: TAttAxis.h:60
virtual void UseCurrentStyle()
Set current style settings in this object This function is called when either TCanvas::UseCurrentStyl...
Definition: TObject.cxx:753
virtual Int_t GetNbinsX() const
Definition: TH1.h:296
const TKDTreeBinning * bins
static Bool_t AlmostInteger(Double_t a, Double_t epsilon=0.00000001)
Definition: TH1.cxx:5157
void Reset()
Definition: TArrayF.h:49
Float_t py
Definition: hprod.C:33
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:8516
virtual Double_t Integral(Double_t a, Double_t b, Double_t epsrel=1.e-12)
IntegralOneDim or analytical integral.
Definition: TF1.cxx:2241
Style_t GetHistFillStyle() const
Definition: TStyle.h:243
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:5195
TAxis fZaxis
Definition: TH1.h:104
virtual Double_t GetEntries() const
return the current number of entries
Definition: TH1.cxx:4051
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:5620
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:9512
virtual Float_t GetTitleSize() const
Definition: TAttAxis.h:57
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:8503
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:176
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
void Reset()
Definition: TCollection.h:161
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:619
static bool CheckBinLimits(const TAxis *a1, const TAxis *a2)
Definition: TH1.cxx:1369
virtual TH1 * GetHistogram() const
Return a pointer to the histogram used to vusualize the function.
Definition: TF1.cxx:1274
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:732
virtual void SetBuffer(Int_t buffersize, Option_t *option="")
set the maximum number of entries to be kept in the buffer
Definition: TH1.cxx:7837
Double_t fTsumwx2
Definition: TH1.h:111
virtual void Reset(Option_t *option="")
Reset this histogram: contents, errors, etc.
Definition: TH1.cxx:6669
static void AddDirectory(Bool_t add=kTRUE)
Sets the flag controlling the automatic add of histograms in memory.
Definition: TH1.cxx:1231
TObject * Clone(const char *newname=0) const
Make a complete copy of the underlying object.
Definition: TH1.cxx:2565
virtual void SetBarWidth(Float_t width=0.5)
Definition: TH1.h:357
virtual void SetLabelFont(Style_t font=62)
Set labels' font.
Definition: TAttAxis.cxx:166
virtual void AppendPad(Option_t *option="")
Append graphics object to current pad.
Definition: TObject.cxx:164
virtual void SetPoint(Int_t ipoint, Double_t re, Double_t im=0)=0
TSocket * s1
Definition: hserv2.C:36
TDirectory * fDirectory
Definition: TH1.h:121
static void SetDefaultSumw2(Bool_t sumw2=kTRUE)
static function.
Definition: TH1.cxx:6253
virtual Double_t GetBinWidth(Int_t bin) const
return bin width for 1D historam Better to use h1.GetXaxis().GetBinWidth(bin)
Definition: TH1.cxx:8492
Marker Attributes class.
Definition: TAttMarker.h:32
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
For axis = 1, 2 or 3 returns skewness of the histogram along x, y or z axis.
Definition: TH1.cxx:7118
virtual void Fatal(const char *method, const char *msgfmt,...) const
Issue fatal error message.
Definition: TObject.cxx:946
TH1C operator/(const TH1C &h1, const TH1C &h2)
Operator /.
Definition: TH1.cxx:8985
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 the limits are defined by first bin and last bin N...
Definition: TH1.cxx:1480
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:4682
virtual Int_t GetContour(Double_t *levels=0)
Return contour values into array levels if pointer levels is non zero.
Definition: TH1.cxx:7787
TH1C & operator=(const TH1C &h1)
Operator =.
Definition: TH1.cxx:8926
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:4583
Fill Area Attributes class.
Definition: TAttFill.h:32
Double_t x[n]
Definition: legend1.C:17
static Int_t FitOptionsMake(Option_t *option, Foption_t &Foption)
flag to call TH1::Sumw2 automatically at histogram creation time
Definition: TH1.cxx:4224
virtual Double_t GetBinErrorUp(Int_t bin) const
Return upper error associated to bin number bin.
Definition: TH1.cxx:8441
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:2321
virtual void Eval(TF1 *f1, Option_t *option="")
Evaluate function f1 at the center of bins of this histogram.
Definition: TH1.cxx:3004
virtual Double_t GetBinLowEdge(Int_t bin) const
return bin lower edge for 1D historam Better to use h1.GetXaxis().GetBinLowEdge(bin) ...
Definition: TH1.cxx:8481
Float_t GetBarOffset() const
Definition: TStyle.h:192
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:4042
void SetHistFillColor(Color_t color=1)
Definition: TStyle.h:374
static void SetDefaultBufferSize(Int_t buffersize=1000)
static function to set the default buffer size for automatic histograms.
Definition: TH1.cxx:6241
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:257
The TNamed class is the base class for all named ROOT classes.
Definition: TNamed.h:33
void Class()
Definition: Class.C:29
virtual ~TH1()
Histogram default destructor.
Definition: TH1.cxx:584
const int ny
Definition: kalman.C:17
virtual Bool_t IsEmpty() const
Definition: TCollection.h:99
UChar_t mod R__LOCKGUARD2(gSrvAuthenticateMutex)
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:7415
void * New(ENewType defConstructor=kClassNew, Bool_t quiet=kFALSE) const
Return a pointer to a newly allocated object of this class.
Definition: TClass.cxx:4602
virtual void Copy(TObject &named) const
Copy this to obj.
Definition: TNamed.cxx:83
TLine l1(2.5, 4.5, 15.5, 4.5)
virtual TObject * FindObject(const char *name) const
search object named name in the list of functions
Definition: TH1.cxx:3578
Double_t Log10(Double_t x)
Definition: TMath.h:529
virtual void AddAll(const TCollection *col)
virtual void SetContourLevel(Int_t level, Double_t value)
Set value for one contour level.
Definition: TH1.cxx:7903
Abstract interface to a histogram painter.
virtual void SetMarkerColor(Color_t mcolor=1)
Definition: TAttMarker.h:51
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:4535
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:1002
Double_t * fArray
Definition: TArrayD.h:32
void H1InitGaus()
Compute Initial values of parameters for a gaussian.
Definition: TH1.cxx:4234
tuple np
Definition: multifit.py:30
TH2D * h2
Definition: fit2dHist.C:45
virtual void DrawPanel()=0
const Double_t sigma
TString fOption
Definition: TH1.h:117
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:226
Float_t GetBarWidth() const
Definition: TStyle.h:193
virtual Int_t * GetN() const =0
virtual void GetRange(Double_t *xmin, Double_t *xmax) const
Return range of a generic N-D function.
Definition: TF1.cxx:1953
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
Definition: TObject.cxx:918
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:6037
virtual TH1 * DrawCopy(Option_t *option="", const char *name_postfix="_copy") const
Copy this histogram and Draw in the current pad.
Definition: TH1.cxx:2925
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:7772
virtual void AddBinContent(Int_t bin)
Increment bin content by 1.
Definition: TH1.cxx:1204
virtual void ResetStats()
Reset the statistics including the number of entries and replace with values calculates from bin cont...
Definition: TH1.cxx:7338
Float_t z[5]
Definition: Ifit.C:16
void Set(Int_t n)
Set size of this array to n ints.
Definition: TArrayI.cxx:105
TArrayD fContour
Definition: TH1.h:115
virtual void SetBinError(Int_t bin, Double_t error)
see convention for numbering bins in TH1::GetBin
Definition: TH1.cxx:8528
Double_t GetXmin() const
Definition: TAxis.h:137
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:2373
virtual void LabelsInflate(Option_t *axis="X")
Double the number of bins for axis.
Definition: TH1.cxx:4843
void AndersonDarling2SamplesTest(Double_t &pvalue, Double_t &testStat) const
Definition: GoFTest.cxx:646
virtual Float_t GetTitleOffset() const
Definition: TAttAxis.h:56
char * out
Definition: TBase64.cxx:29
Int_t GetOptFit() const
Definition: TStyle.h:252
short Color_t
Definition: RtypesCore.h:79
virtual void SetTimeDisplay(Int_t value)
Definition: TAxis.h:161
Double_t fTsumwx
Definition: TH1.h:110
void H1LeastSquareFit(Int_t n, Int_t m, Double_t *a)
Least squares lpolynomial fitting without weights.
Definition: TH1.cxx:4343
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:2630
virtual Double_t GetEffectiveEntries() const
number of effective entries of the histogram, neff = (Sum of weights )^2 / (Sum of weight^2 ) In case...
Definition: TH1.cxx:4073
static Bool_t fgAddDirectory
default buffer size for automatic histograms
Definition: TH1.h:127
virtual void SetUniqueID(UInt_t uid)
Set the unique object id.
Definition: TObject.cxx:743
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
Double_t fMinimum
Definition: TH1.h:113
virtual void ExtendAxis(Double_t x, TAxis *axis)
Histogram is resized along axis such that x is in the axis range.
Definition: TH1.cxx:6091
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:3098
virtual Int_t DistancetoPrimitive(Int_t px, Int_t py)
Compute distance from point px,py to a line.
Definition: TH1.cxx:2612
std::string printValue(const TDatime &val)
Print a TDatime at the prompt.
Definition: TDatime.cxx:447
void Reset()
Definition: TArrayS.h:49
void Copy(TArrayF &array) const
Definition: TArrayF.h:44
virtual void AddBinContent(Int_t bin)
Increment bin content by 1.
Definition: TH1.cxx:9075
virtual void SetLineColor(Color_t lcolor)
Definition: TAttLine.h:54
Bool_t IsReading() const
Definition: TStyle.h:296
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:3053
Int_t fN
Definition: TArray.h:40
virtual Double_t * GetIntegral()
Return a pointer to the array of bins integral.
Definition: TH1.cxx:2422
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:7497
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:831
virtual Double_t GetBinCenter(Int_t bin) const
return bin center for 1D historam Better to use h1.GetXaxis().GetBinCenter(bin)
Definition: TH1.cxx:8470
virtual Size_t GetMarkerSize() const
Definition: TAttMarker.h:46
TThread * t[5]
Definition: threadsh1.C:13
void Clear(Option_t *option="")
Remove all objects from the list.
Definition: THashList.cxx:168
float ymax
Definition: THbookFile.cxx:93
virtual void SetParLimits(Int_t ipar, Double_t parmin, Double_t parmax)
Set limits for parameter ipar.
Definition: TF1.cxx:3183
Color_t GetHistFillColor() const
Definition: TStyle.h:241
ClassImp(TH1) TH1
Histogram default constructor.
Definition: TH1.cxx:550
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:6573
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:7014
Width_t GetHistLineWidth() const
Definition: TStyle.h:245
virtual void FillRandom(const char *fname, Int_t ntimes=5000)
Fill histogram following distribution in function fname.
Definition: TH1.cxx:3330
virtual Double_t Integral(Option_t *option="") const
Return integral of bin contents.
Definition: TH1.cxx:7378
void SetHistFillStyle(Style_t styl=0)
Definition: TStyle.h:376
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:6318
Class to manage histogram axis.
Definition: TAxis.h:36
virtual void Draw(Option_t *option="")
Draw this histogram with options.
Definition: TH1.cxx:2878
static bool CheckBinLabels(const TAxis *a1, const TAxis *a2)
check that axis have same labels
Definition: TH1.cxx:1396
Array of shorts (16 bits per element).
Definition: TArrayS.h:29
virtual Double_t GetPointReal(Int_t ipoint, Bool_t fromInput=kFALSE) const =0
SVector< double, 2 > v
Definition: Dict.h:5
TH1 * R__H(Int_t hid)
return pointer to histogram with name hid if id >=0 h_id if id <0
Definition: TH1.cxx:9792
TPaveLabel title(3, 27.1, 15, 28.7,"ROOT Environment and Tools")
virtual void SetFillColor(Color_t fcolor)
Definition: TAttFill.h:50
Int_t GetNbins() const
Definition: TAxis.h:125
virtual char * GetObjectInfo(Int_t px, Int_t py) const
Redefines TObject::GetObjectInfo.
Definition: TH1.cxx:4086
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:499
void SetCanExtend(Bool_t canExtend)
Definition: TAxis.h:91
1-D histogram with a int per channel (see TH1 documentation)}
Definition: TH1.h:529
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 By default the integral is compu...
Definition: TH1.cxx:7405
virtual const char * ClassName() const
Returns name of class to which the object belongs.
Definition: TObject.cxx:187
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:9295
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:8647
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:8543
virtual Color_t GetFillColor() const
Definition: TAttFill.h:43
Collection abstract base class.
Definition: TCollection.h:48
TClass * IsA() const
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:7610
static Int_t fgBufferSize
Definition: TH1.h:126
TH1C operator-(const TH1C &h1, const TH1C &h2)
Operator -.
Definition: TH1.cxx:8961
virtual TH1 * Rebin(Int_t ngroup=2, const char *newname="", const Double_t *xbins=0)
Rebin this histogram.
Definition: TH1.cxx:5859
void Copy(TArrayI &array) const
Definition: TArrayI.h:44
void Form(const char *fmt,...)
Formats a string using a printf style format descriptor.
Definition: TString.cxx:2308
Double_t fEntries
Definition: TH1.h:107
virtual Double_t GetMeanError(Int_t axis=1) const
Return standard error of mean of this histogram along the X axis.
Definition: TH1.cxx:7045
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:229
Bool_t TestBit(UInt_t f) const
Definition: TObject.h:173
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:4776
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:3289
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:151
bool first
Definition: line3Dfit.C:48
static TVirtualFitter * GetFitter()
static: return the current Fitter
virtual Double_t GetSumOfWeights() const
Return the sum of weights excluding under/overflows.
Definition: TH1.cxx:7354
Double_t E()
Definition: TMath.h:54
tuple w
Definition: qtexample.py:51
virtual TH1 * ShowBackground(Int_t niter=20, Option_t *option="same")
This function calculates the background spectrum in this histogram.
Definition: TH1.cxx:8612
virtual void SetBinsLength(Int_t n=-1)
Set total number of bins including under/overflow Reallocate bin contents array.
Definition: TH1.cxx:9315
virtual ~TH1C()
Destructor.
Definition: TH1.cxx:8857
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:3367
virtual Int_t GetNbinsZ() const
Definition: TH1.h:298
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't want to leave purely abstract...
Definition: TObject.cxx:960
virtual const char * GetName() const
Returns name of object.
Definition: TNamed.h:51
virtual Int_t GetSumw2N() const
Definition: TH1.h:314
virtual void SetMarkerStyle(Style_t mstyle=1)
Definition: TAttMarker.h:53
virtual Double_t GetKurtosis(Int_t axis=1) const
For axis =1, 2 or 3 returns kurtosis of the histogram along x, y or z axis.
Definition: TH1.cxx:7188
double Chisquare(const TH1 &h1, TF1 &f1, bool useRange)
compute the chi2 value for an histogram given a function (see TH1::Chisquare for the documentation) ...
Definition: HFitImpl.cxx:990
TAxis * GetYaxis()
Definition: TH1.h:320
Class describing the binned data sets : vectors of x coordinates, y values and optionally error on y ...
Definition: BinData.h:61
float xmax
Definition: THbookFile.cxx:93
Double_t * fIntegral
Histogram dimension (1, 2 or 3 dim)
Definition: TH1.h:123
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:1516
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:4450
R__EXTERN TRandom * gRandom
Definition: TRandom.h:62
virtual Color_t GetLineColor() const
Definition: TAttLine.h:47
1-D histogram with a double per channel (see TH1 documentation)}
Definition: TH1.h:613
static Int_t GetDefaultBufferSize()
static function return the default buffer size for automatic histograms the parameter fgBufferSize ma...
Definition: TH1.cxx:4032
virtual void SetAxisColor(Color_t color=1, Float_t alpha=1.)
Set color of the line axis and tick marks.
Definition: TAttAxis.cxx:146
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:6652
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:187
virtual void SetMarkerSize(Size_t msize=1)
Definition: TAttMarker.h:54
REAL epsilon
Definition: triangle.c:617
virtual void SetTitleColor(Color_t color=1)
Set color of axis title.
Definition: TAttAxis.cxx:264
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:255
#define Printf
Definition: TGeoToOCC.h:18
virtual void RecursiveRemove(TObject *obj)
Recursively remove object from the list of functions.
Definition: TH1.cxx:6147
EBinErrorOpt fBinStatErrOpt
pointer to histogram painter
Definition: TH1.h:125
virtual Int_t GetXlast() const
const Double_t * GetArray() const
Definition: TArrayD.h:45
Int_t GetSize() const
Definition: TArray.h:49
virtual void Copy(TObject &hnew) const
Copy this to newth1.
Definition: TH1.cxx:9689
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:264
virtual void SetName(const char *name)
Change the name of this histogram.
Definition: TH1.cxx:8288
void Copy(TArrayC &array) const
Definition: TArrayC.h:44
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
Definition: TH1.h:109
virtual void GetPointComplex(Int_t ipoint, Double_t &re, Double_t &im, Bool_t fromInput=kFALSE) const =0
virtual Int_t GetSize() const
Definition: TCollection.h:95
return c2
Definition: legend2.C:14
TH1F * s2
Definition: threadsh2.C:15
static const double x1[5]
virtual TObject * Remove(TObject *)
Remove an object from the in-memory list.
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:415
double Double_t
Definition: RtypesCore.h:55
Int_t * fArray
Definition: TArrayI.h:32
void SetHistLineStyle(Style_t styl=0)
Definition: TStyle.h:377
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:6864
Double_t fTsumw
Definition: TH1.h:108
virtual void Copy(TObject &axis) const
Copy axis structure to another axis.
Definition: TAxis.cxx:198
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:1077
ClassImp(TMCParticle) void TMCParticle printf(": p=(%7.3f,%7.3f,%9.3f) ;", fPx, fPy, fPz)
void dir(char *path=0)
Definition: rootalias.C:30
virtual Style_t GetLabelFont() const
Definition: TAttAxis.h:53
unsigned long ULong_t
Definition: RtypesCore.h:51
Double_t GetXmax() const
Definition: TAxis.h:138
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:50
TH1I & operator=(const TH1I &h1)
Operator =.
Definition: TH1.cxx:9326
The TH1 histogram class.
Definition: TH1.h:80
Color_t GetHistLineColor() const
Definition: TStyle.h:242
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:3512
virtual Int_t GetMinimumBin() const
Return location of bin with minimum value in the range.
Definition: TH1.cxx:8037
static bool IsEquidistantBinning(const TAxis &axis)
Definition: TH1.cxx:5163
Short_t fBarOffset
Definition: TH1.h:105
virtual void SetLineStyle(Style_t lstyle)
Definition: TAttLine.h:56
double Stat_t
Definition: RtypesCore.h:73
Array of doubles (64 bits per element).
Definition: TArrayD.h:29
void FitOptionsMake(EFitObjectType type, const char *option, Foption_t &fitOption)
Decode list of options into fitOption.
Definition: HFitImpl.cxx:674
virtual void InitArgs(const Double_t *x, const Double_t *params)
Initialize parameters addresses.
Definition: TF1.cxx:2198
#define name(a, b)
Definition: linkTestLib0.cpp:5
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:780
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:440
TAxis * GetZaxis()
Definition: TH1.h:321
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:6211
TH1C operator+(const TH1C &h1, const TH1C &h2)
Operator +.
Definition: TH1.cxx:8949
virtual Double_t GetBinCenter(Int_t bin) const
Return center of bin.
Definition: TAxis.cxx:449
Mother of all ROOT objects.
Definition: TObject.h:58
virtual void SetBinsLength(Int_t n=-1)
Set total number of bins including under/overflow Reallocate bin contents array.
Definition: TH1.cxx:9116
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:3539
virtual void ClearUnderflowAndOverflow()
Remove all the content from the underflow and overflow bins, without changing the number of entries A...
Definition: TH1.cxx:2354
tuple label1
Definition: h1draw.py:38
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:55
char Char_t
Definition: RtypesCore.h:29
Float_t px
Definition: hprod.C:33
virtual Int_t GetNbinsY() const
Definition: TH1.h:297
TH1S & operator=(const TH1S &h1)
Operator =.
Definition: TH1.cxx:9127
virtual Double_t GetBinErrorSqUnchecked(Int_t bin) const
Definition: TH1.h:438
THashList * GetLabels() const
Definition: TAxis.h:122
Bool_t axis
Definition: geodemo.C:37
Double_t fMaximum
Definition: TH1.h:112
virtual Color_t GetMarkerColor() const
Definition: TAttMarker.h:44
virtual void DirectoryAutoAdd(TDirectory *)
Perform the automatic addition of the histogram to the given directory.
Definition: TH1.cxx:2589
TVirtualHistPainter * fPainter
Integral of bins used by GetRandom.
Definition: TH1.h:124
static TVirtualHistPainter * HistPainter(TH1 *obj)
virtual void GetCenter(Double_t *center) const
Return an array with the center of all bins.
Definition: TAxis.cxx:524
static Bool_t RejectedPoint()
See TF1::RejectPoint above.
Definition: TF1.cxx:3376
virtual void DrawPanel()
Display a panel with all histogram drawing options.
Definition: TH1.cxx:2986
virtual Int_t FindFixBin(Double_t x) const
Find bin number corresponding to abscissa x.
Definition: TAxis.cxx:390
virtual void Add(TObject *obj)
Definition: TList.h:81
Int_t fBufferSize
Definition: TH1.h:119
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:2488
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:3265
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:2336
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:9492
1-Dim function class
Definition: TF1.h:149
virtual void SetBinsLength(Int_t=-1)
Definition: TH1.h:372
Int_t IsNaN(Double_t x)
Definition: TMath.h:617
virtual TObject * GetObjectFit() const
Char_t * fArray
Definition: TArrayC.h:32
1-D histogram with a bype per channel (see TH1 documentation)
Definition: TH1.h:447
virtual void Sumw2(Bool_t flag=kTRUE)
Create structure to store sum of squares of weights.
Definition: TH1.cxx:8350
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:1162
TF1 * f1
Definition: legend1.C:11
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:1252
virtual Bool_t CanExtendAllAxes() const
returns true if all axes are extendable
Definition: TH1.cxx:6197
#define NULL
Definition: Rtypes.h:82
Int_t fDimension
Pointer to directory holding this histogram.
Definition: TH1.h:122
#define gPad
Definition: TVirtualPad.h:288
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:232
virtual Int_t BufferEmpty(Int_t action=0)
Fill histogram with all entries in the buffer.
Definition: TH1.cxx:1251
virtual void SetParent(TObject *obj)
Definition: TAxis.h:157
void Set(Int_t n)
Set size of this array to n floats.
Definition: TArrayF.cxx:105
virtual ~TH1D()
Destructor.
Definition: TH1.cxx:9672
virtual void SetEntries(Double_t n)
Definition: TH1.h:382
std::vector< double > errors
Definition: TwoHistoFit2D.C:33
TAxis fXaxis
Definition: TH1.h:102
#define gDirectory
Definition: TDirectory.h:221
const TArrayD * GetXbins() const
Definition: TAxis.h:134
void ResetBit(UInt_t f)
Definition: TObject.h:172
virtual void SetParameter(Int_t param, Double_t value)
Definition: TF1.h:424
virtual void AddBinContent(Int_t bin)
Increment bin content by 1.
Definition: TH1.cxx:9274
virtual void SetTitle(const char *title)
Change (i.e.
Definition: TH1.cxx:6268
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:936
virtual Int_t GetNdim() const =0
virtual Double_t GetStdDev(Int_t axis=1) const
Returns the Standard Deviation (Sigma).
Definition: TH1.cxx:7067
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 AddBinContent(Int_t bin)
Increment bin content by 1.
Definition: TH1.cxx:8874
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:404
virtual void Set(Int_t nbins, Double_t xmin, Double_t xmax)
Initialize axis with fix bins.
Definition: TAxis.cxx:701
virtual Double_t GetBinError(Int_t bin) const
Return value of error associated to bin number bin.
Definition: TH1.cxx:8395
virtual Style_t GetMarkerStyle() const
Definition: TAttMarker.h:45
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:7921
const Bool_t kTRUE
Definition: Rtypes.h:91
float * q
Definition: THbookFile.cxx:87
virtual Width_t GetLineWidth() const
Definition: TAttLine.h:49
static Bool_t AlmostEqual(Double_t a, Double_t b, Double_t epsilon=0.00000001)
Definition: TH1.cxx:5149
virtual Double_t EvalPar(const Double_t *x, const Double_t *params=0)
Evaluate function with given coordinates and parameters.
Definition: TF1.cxx:1192
virtual Float_t GetTickLength() const
Definition: TAttAxis.h:58
virtual void SetTitle(const char *title="")
Change (i.e. set) the title of the TNamed.
Definition: TNamed.cxx:152
void SetHistLineColor(Color_t color=1)
Definition: TStyle.h:375
TObject * obj
virtual Float_t GetBarWidth() const
Definition: TH1.h:257
Double_t * fBuffer
Definition: TH1.h:120
float value
Definition: math.cpp:443
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:4549
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:3607
double norm(double *x, double *p)
Definition: unuranDistr.cxx:40
Int_t Nint(T x)
Definition: TMath.h:480
TH1C operator*(Double_t c1, const TH1C &h1)
Operator *.
Definition: TH1.cxx:8937
virtual ClassDef(TH1, 7) protected 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:8779
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:8382
static bool CheckEqualAxes(const TAxis *a1, const TAxis *a2)
Check that the axis are the same.
Definition: TH1.cxx:1443
tuple all
Definition: na49view.py:13
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:9058
const Int_t n
Definition: legend1.C:16
Line Attributes class.
Definition: TAttLine.h:32
virtual Int_t GetNpar() const
Definition: TF1.h:342
void H1InitPolynom()
Compute Initial values of parameters for a polynom.
Definition: TH1.cxx:4312
virtual void SetStats(Bool_t stats=kTRUE)
Set statistics option on/off.
Definition: TH1.cxx:8320
TH1F & operator=(const TH1F &h1)
Operator =.
Definition: TH1.cxx:9523
Long64_t BinarySearch(Long64_t n, const T *array, T value)
Definition: TMath.h:944
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:8006
virtual Double_t GetContourLevel(Int_t level) const
Return value of contour number level use GetContour to return the array of all contour levels...
Definition: TH1.cxx:7807
virtual Double_t GetContourLevelPad(Int_t level) const
Return the value of contour number "level" in Pad coordinates ie: if the Pad is in log scale along Z ...
Definition: TH1.cxx:7818
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 In case...
Definition: TH1.cxx:4653
virtual Float_t GetBarOffset() const
Definition: TH1.h:256
TAxis * GetXaxis()
Definition: TH1.h:319
virtual void SetBinsLength(Int_t n=-1)
Set total number of bins including under/overflow Reallocate bin contents array.
Definition: TH1.cxx:8915
virtual Long64_t Merge(TCollection *list)
Add all histograms in the collection to this histogram.
Definition: TH1.cxx:5305
virtual Version_t ReadVersion(UInt_t *start=0, UInt_t *bcnt=0, const TClass *cl=0)=0
virtual Option_t * GetType() const =0
virtual Int_t ReadArray(Bool_t *&b)=0
Int_t fNcells
Definition: TH1.h:101
T MinElement(Long64_t n, const T *a)
Definition: TMath.h:681
virtual Float_t GetLabelOffset() const
Definition: TAttAxis.h:54
2-D histogram with a double per channel (see TH1 documentation)}
Definition: TH2.h:297
void H1LeastSquareLinearFit(Int_t ndata, Double_t &a0, Double_t &a1, Int_t &ifail)
Least square linear fit without weights.
Definition: TH1.cxx:4403
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:702
Double_t ATan(Double_t)
Definition: TMath.h:451
int ii
Definition: hprod.C:34
virtual void Warning(const char *method, const char *msgfmt,...) const
Issue warning message.
Definition: TObject.cxx:904