/
TH1.cxx
9707 lines (8606 loc) · 334 KB
/
TH1.cxx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// @(#)root/hist:$Id$
// Author: Rene Brun 26/12/94
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <sstream>
#include <cmath>
#include "Riostream.h"
#include "TROOT.h"
#include "TEnv.h"
#include "TClass.h"
#include "TMath.h"
#include "THashList.h"
#include "TH1.h"
#include "TH2.h"
#include "TH3.h"
#include "TF2.h"
#include "TF3.h"
#include "TPluginManager.h"
#include "TVirtualPad.h"
#include "TRandom.h"
#include "TVirtualFitter.h"
#include "THLimitsFinder.h"
#include "TProfile.h"
#include "TStyle.h"
#include "TVectorF.h"
#include "TVectorD.h"
#include "TBrowser.h"
#include "TObjString.h"
#include "TError.h"
#include "TVirtualHistPainter.h"
#include "TVirtualFFT.h"
#include "TSystem.h"
#include "HFitInterface.h"
#include "Fit/DataRange.h"
#include "Fit/BinData.h"
#include "Math/GoFTest.h"
#include "Math/MinimizerOptions.h"
#include "Math/QuantFuncMathCore.h"
#include "TH1Merger.h"
/** \addtogroup Hist
@{
\class TH1C
\brief 1-D histogram with a byte per channel (see TH1 documentation)
\class TH1S
\brief 1-D histogram with a short per channel (see TH1 documentation)
\class TH1I
\brief 1-D histogram with an int per channel (see TH1 documentation)}
\class TH1F
\brief 1-D histogram with a float per channel (see TH1 documentation)}
\class TH1D
\brief 1-D histogram with a double per channel (see TH1 documentation)}
@}
*/
/** \class TH1
The TH1 histogram class.
### The Histogram classes
ROOT supports the following histogram types:
- 1-D histograms:
- TH1C : histograms with one byte per channel. Maximum bin content = 127
- TH1S : histograms with one short per channel. Maximum bin content = 32767
- TH1I : histograms with one int per channel. Maximum bin content = 2147483647
- TH1F : histograms with one float per channel. Maximum precision 7 digits
- TH1D : histograms with one double per channel. Maximum precision 14 digits
- 2-D histograms:
- TH2C : histograms with one byte per channel. Maximum bin content = 127
- TH2S : histograms with one short per channel. Maximum bin content = 32767
- TH2I : histograms with one int per channel. Maximum bin content = 2147483647
- TH2F : histograms with one float per channel. Maximum precision 7 digits
- TH2D : histograms with one double per channel. Maximum precision 14 digits
- 3-D histograms:
- TH3C : histograms with one byte per channel. Maximum bin content = 127
- TH3S : histograms with one short per channel. Maximum bin content = 32767
- TH3I : histograms with one int per channel. Maximum bin content = 2147483647
- TH3F : histograms with one float per channel. Maximum precision 7 digits
- TH3D : histograms with one double per channel. Maximum precision 14 digits
- Profile histograms: See classes TProfile, TProfile2D and TProfile3D.
Profile histograms are used to display the mean value of Y and its standard deviation
for each bin in X. Profile histograms are in many cases an elegant
replacement of two-dimensional histograms : the inter-relation of two
measured quantities X and Y can always be visualized by a two-dimensional
histogram or scatter-plot; If Y is an unknown (but single-valued)
approximate function of X, this function is displayed by a profile
histogram with much better precision than by a scatter-plot.
All histogram classes are derived from the base class TH1
~~~ {.cpp}
TH1
^
|
|
|
+----------------+-------+------+------+-----+-----+
| | | | | | |
| | TH1C TH1S TH1I TH1F TH1D
| | |
| | |
| TH2 TProfile
| |
| |
| +-------+------+------+-----+-----+
| | | | | |
| TH2C TH2S TH2I TH2F TH2D
| |
TH3 |
| TProfile2D
|
+-------+------+------+------+------+
| | | | |
TH3C TH3S TH3I TH3F TH3D
|
|
TProfile3D
The TH*C classes also inherit from the array class TArrayC.
The TH*S classes also inherit from the array class TArrayS.
The TH*I classes also inherit from the array class TArrayI.
The TH*F classes also inherit from the array class TArrayF.
The TH*D classes also inherit from the array class TArrayD.
~~~
#### Creating histograms
Histograms are created by invoking one of the constructors, e.g.
~~~ {.cpp}
TH1F *h1 = new TH1F("h1", "h1 title", 100, 0, 4.4);
TH2F *h2 = new TH2F("h2", "h2 title", 40, 0, 4, 30, -3, 3);
~~~
Histograms may also be created by:
- calling the Clone function, see below
- making a projection from a 2-D or 3-D histogram, see below
- reading an histogram from a file
When an histogram is created, a reference to it is automatically added
to the list of in-memory objects for the current file or directory.
This default behaviour can be changed by:
~~~ {.cpp}
h->SetDirectory(0); for the current histogram h
TH1::AddDirectory(kFALSE); sets a global switch disabling the reference
~~~
When the histogram is deleted, the reference to it is removed from
the list of objects in memory.
When a file is closed, all histograms in memory associated with this file
are automatically deleted.
#### Fix or variable bin size
All histogram types support either fix or variable bin sizes.
2-D histograms may have fix size bins along X and variable size bins
along Y or vice-versa. The functions to fill, manipulate, draw or access
histograms are identical in both cases.
Each histogram always contains 3 objects TAxis: fXaxis, fYaxis and fZaxis
o access the axis parameters, do:
~~~ {.cpp}
TAxis *xaxis = h->GetXaxis(); etc.
Double_t binCenter = xaxis->GetBinCenter(bin), etc.
~~~
See class TAxis for a description of all the access functions.
The axis range is always stored internally in double precision.
#### Convention for numbering bins
For all histogram types: nbins, xlow, xup
~~~ {.cpp}
bin = 0; underflow bin
bin = 1; first bin with low-edge xlow INCLUDED
bin = nbins; last bin with upper-edge xup EXCLUDED
bin = nbins+1; overflow bin
~~~
In case of 2-D or 3-D histograms, a "global bin" number is defined.
For example, assuming a 3-D histogram with (binx, biny, binz), the function
~~~ {.cpp}
Int_t gbin = h->GetBin(binx, biny, binz);
~~~
returns a global/linearized gbin number. This global gbin is useful
to access the bin content/error information independently of the dimension.
Note that to access the information other than bin content and errors
one should use the TAxis object directly with e.g.:
~~~ {.cpp}
Double_t xcenter = h3->GetZaxis()->GetBinCenter(27);
~~~
returns the center along z of bin number 27 (not the global bin)
in the 3-D histogram h3.
#### Alphanumeric Bin Labels
By default, an histogram axis is drawn with its numeric bin labels.
One can specify alphanumeric labels instead with:
- call TAxis::SetBinLabel(bin, label);
This can always be done before or after filling.
When the histogram is drawn, bin labels will be automatically drawn.
See examples labels1.C and labels2.C
- call to a Fill function with one of the arguments being a string, e.g.
~~~ {.cpp}
hist1->Fill(somename, weight);
hist2->Fill(x, somename, weight);
hist2->Fill(somename, y, weight);
hist2->Fill(somenamex, somenamey, weight);
~~~
See examples hlabels1.C and hlabels2.C
- via TTree::Draw. see for example cernstaff.C
~~~ {.cpp}
tree.Draw("Nation::Division");
~~~
where "Nation" and "Division" are two branches of a Tree.
When using the options 2 or 3 above, the labels are automatically
added to the list (THashList) of labels for a given axis.
By default, an axis is drawn with the order of bins corresponding
to the filling sequence. It is possible to reorder the axis
- alphabetically
- by increasing or decreasing values
The reordering can be triggered via the TAxis context menu by selecting
the menu item "LabelsOption" or by calling directly
TH1::LabelsOption(option, axis) where
- axis may be "X", "Y" or "Z"
- option may be:
- "a" sort by alphabetic order
- ">" sort by decreasing values
- "<" sort by increasing values
- "h" draw labels horizontal
- "v" draw labels vertical
- "u" draw labels up (end of label right adjusted)
- "d" draw labels down (start of label left adjusted)
When using the option 2 above, new labels are added by doubling the current
number of bins in case one label does not exist yet.
When the Filling is terminated, it is possible to trim the number
of bins to match the number of active labels by calling
~~~ {.cpp}
TH1::LabelsDeflate(axis) with axis = "X", "Y" or "Z"
~~~
This operation is automatic when using TTree::Draw.
Once bin labels have been created, they become persistent if the histogram
is written to a file or when generating the C++ code via SavePrimitive.
#### Histograms with automatic bins
When an histogram is created with an axis lower limit greater or equal
to its upper limit, the SetBuffer is automatically called with an
argument fBufferSize equal to fgBufferSize (default value=1000).
fgBufferSize may be reset via the static function TH1::SetDefaultBufferSize.
The axis limits will be automatically computed when the buffer will
be full or when the function BufferEmpty is called.
#### Filling histograms
An histogram is typically filled with statements like:
~~~ {.cpp}
h1->Fill(x);
h1->Fill(x, w); //fill with weight
h2->Fill(x, y)
h2->Fill(x, y, w)
h3->Fill(x, y, z)
h3->Fill(x, y, z, w)
~~~
or via one of the Fill functions accepting names described above.
The Fill functions compute the bin number corresponding to the given
x, y or z argument and increment this bin by the given weight.
The Fill functions return the bin number for 1-D histograms or global
bin number for 2-D and 3-D histograms.
If TH1::Sumw2 has been called before filling, the sum of squares of
weights is also stored.
One can also increment directly a bin number via TH1::AddBinContent
or replace the existing content via TH1::SetBinContent.
To access the bin content of a given bin, do:
~~~ {.cpp}
Double_t binContent = h->GetBinContent(bin);
~~~
By default, the bin number is computed using the current axis ranges.
If the automatic binning option has been set via
~~~ {.cpp}
h->SetCanExtend(TH1::kAllAxes);
~~~
then, the Fill Function will automatically extend the axis range to
accomodate the new value specified in the Fill argument. The method
used is to double the bin size until the new value fits in the range,
merging bins two by two. This automatic binning options is extensively
used by the TTree::Draw function when histogramming Tree variables
with an unknown range.
This automatic binning option is supported for 1-D, 2-D and 3-D histograms.
During filling, some statistics parameters are incremented to compute
the mean value and Root Mean Square with the maximum precision.
In case of histograms of type TH1C, TH1S, TH2C, TH2S, TH3C, TH3S
a check is made that the bin contents do not exceed the maximum positive
capacity (127 or 32767). Histograms of all types may have positive
or/and negative bin contents.
#### Rebinning
At any time, an histogram can be rebinned via TH1::Rebin. This function
returns a new histogram with the rebinned contents.
If bin errors were stored, they are recomputed during the rebinning.
#### Associated errors
By default, for each bin, the sum of weights is computed at fill time.
One can also call TH1::Sumw2 to force the storage and computation
of the sum of the square of weights per bin.
If Sumw2 has been called, the error per bin is computed as the
sqrt(sum of squares of weights), otherwise the error is set equal
to the sqrt(bin content).
To return the error for a given bin number, do:
~~~ {.cpp}
Double_t error = h->GetBinError(bin);
~~~
#### Associated functions
One or more object (typically a TF1*) can be added to the list
of functions (fFunctions) associated to each histogram.
When TH1::Fit is invoked, the fitted function is added to this list.
Given an histogram h, one can retrieve an associated function
with:
~~~ {.cpp}
TF1 *myfunc = h->GetFunction("myfunc");
~~~
#### Operations on histograms
Many types of operations are supported on histograms or between histograms
- Addition of an histogram to the current histogram.
- Additions of two histograms with coefficients and storage into the current
histogram.
- Multiplications and Divisions are supported in the same way as additions.
- The Add, Divide and Multiply functions also exist to add, divide or multiply
an histogram by a function.
If an histogram has associated error bars (TH1::Sumw2 has been called),
the resulting error bars are also computed assuming independent histograms.
In case of divisions, Binomial errors are also supported.
One can mark a histogram to be an "average" histogram by setting its bit kIsAverage via
myhist.SetBit(TH1::kIsAverage);
When adding (see TH1::Add) average histograms, the histograms are averaged and not summed.
#### Fitting histograms
Histograms (1-D, 2-D, 3-D and Profiles) can be fitted with a user
specified function via TH1::Fit. When an histogram is fitted, the
resulting function with its parameters is added to the list of functions
of this histogram. If the histogram is made persistent, the list of
associated functions is also persistent. Given a pointer (see above)
to an associated function myfunc, one can retrieve the function/fit
parameters with calls such as:
~~~ {.cpp}
Double_t chi2 = myfunc->GetChisquare();
Double_t par0 = myfunc->GetParameter(0); value of 1st parameter
Double_t err0 = myfunc->GetParError(0); error on first parameter
~~~
#### Projections of histograms
One can:
- make a 1-D projection of a 2-D histogram or Profile
see functions TH2::ProjectionX,Y, TH2::ProfileX,Y, TProfile::ProjectionX
- make a 1-D, 2-D or profile out of a 3-D histogram
see functions TH3::ProjectionZ, TH3::Project3D.
One can fit these projections via:
~~~ {.cpp}
TH2::FitSlicesX,Y, TH3::FitSlicesZ.
~~~
#### Random Numbers and histograms
TH1::FillRandom can be used to randomly fill an histogram using
the contents of an existing TF1 function or another
TH1 histogram (for all dimensions).
For example the following two statements create and fill an histogram
10000 times with a default gaussian distribution of mean 0 and sigma 1:
~~~ {.cpp}
TH1F h1("h1", "histo from a gaussian", 100, -3, 3);
h1.FillRandom("gaus", 10000);
~~~
TH1::GetRandom can be used to return a random number distributed
according the contents of an histogram.
#### Making a copy of an histogram
Like for any other ROOT object derived from TObject, one can use
the Clone() function. This makes an identical copy of the original
histogram including all associated errors and functions, e.g.:
~~~ {.cpp}
TH1F *hnew = (TH1F*)h->Clone("hnew");
~~~
#### Normalizing histograms
One can scale an histogram such that the bins integral is equal to
the normalization parameter via TH1::Scale(Double_t norm), where norm
is the desired normalization divided by the integral of the histogram.
#### Drawing histograms
Histograms are drawn via the THistPainter class. Each histogram has
a pointer to its own painter (to be usable in a multithreaded program).
Many drawing options are supported.
See THistPainter::Paint() for more details.
The same histogram can be drawn with different options in different pads.
When an histogram drawn in a pad is deleted, the histogram is
automatically removed from the pad or pads where it was drawn.
If an histogram is drawn in a pad, then filled again, the new status
of the histogram will be automatically shown in the pad next time
the pad is updated. One does not need to redraw the histogram.
To draw the current version of an histogram in a pad, one can use
~~~ {.cpp}
h->DrawCopy();
~~~
This makes a clone (see Clone below) of the histogram. Once the clone
is drawn, the original histogram may be modified or deleted without
affecting the aspect of the clone.
One can use TH1::SetMaximum() and TH1::SetMinimum() to force a particular
value for the maximum or the minimum scale on the plot. (For 1-D
histograms this means the y-axis, while for 2-D histograms these
functions affect the z-axis).
TH1::UseCurrentStyle() can be used to change all histogram graphics
attributes to correspond to the current selected style.
This function must be called for each histogram.
In case one reads and draws many histograms from a file, one can force
the histograms to inherit automatically the current graphics style
by calling before gROOT->ForceStyle().
#### Setting Drawing histogram contour levels (2-D hists only)
By default contours are automatically generated at equidistant
intervals. A default value of 20 levels is used. This can be modified
via TH1::SetContour() or TH1::SetContourLevel().
the contours level info is used by the drawing options "cont", "surf",
and "lego".
#### Setting histogram graphics attributes
The histogram classes inherit from the attribute classes:
TAttLine, TAttFill, and TAttMarker.
See the member functions of these classes for the list of options.
#### Giving titles to the X, Y and Z axis
~~~ {.cpp}
h->GetXaxis()->SetTitle("X axis title");
h->GetYaxis()->SetTitle("Y axis title");
~~~
The histogram title and the axis titles can be any TLatex string.
The titles are part of the persistent histogram.
It is also possible to specify the histogram title and the axis
titles at creation time. These titles can be given in the "title"
parameter. They must be separated by ";":
~~~ {.cpp}
TH1F* h=new TH1F("h", "Histogram title;X Axis;Y Axis;Z Axis", 100, 0, 1);
~~~
Any title can be omitted:
~~~ {.cpp}
TH1F* h=new TH1F("h", "Histogram title;;Y Axis", 100, 0, 1);
TH1F* h=new TH1F("h", ";;Y Axis", 100, 0, 1);
~~~
The method SetTitle has the same syntax:
~~~ {.cpp}
h->SetTitle("Histogram title;Another X title Axis");
~~~
#### Saving/Reading histograms to/from a ROOT file
The following statements create a ROOT file and store an histogram
on the file. Because TH1 derives from TNamed, the key identifier on
the file is the histogram name:
~~~ {.cpp}
TFile f("histos.root", "new");
TH1F h1("hgaus", "histo from a gaussian", 100, -3, 3);
h1.FillRandom("gaus", 10000);
h1->Write();
~~~
To read this histogram in another Root session, do:
~~~ {.cpp}
TFile f("histos.root");
TH1F *h = (TH1F*)f.Get("hgaus");
~~~
One can save all histograms in memory to the file by:
~~~ {.cpp}
file->Write();
~~~
#### Miscellaneous operations
~~~ {.cpp}
TH1::KolmogorovTest(): statistical test of compatibility in shape
between two histograms
TH1::Smooth() smooths the bin contents of a 1-d histogram
TH1::Integral() returns the integral of bin contents in a given bin range
TH1::GetMean(int axis) returns the mean value along axis
TH1::GetStdDev(int axis) returns the sigma distribution along axis
TH1::GetEntries() returns the number of entries
TH1::Reset() resets the bin contents and errors of an histogram
~~~
*/
TF1 *gF1=0; //left for back compatibility (use TVirtualFitter::GetUserFunc instead)
Int_t TH1::fgBufferSize = 1000;
Bool_t TH1::fgAddDirectory = kTRUE;
Bool_t TH1::fgDefaultSumw2 = kFALSE;
Bool_t TH1::fgStatOverflows= kFALSE;
extern void H1InitGaus();
extern void H1InitExpo();
extern void H1InitPolynom();
extern void H1LeastSquareFit(Int_t n, Int_t m, Double_t *a);
extern void H1LeastSquareLinearFit(Int_t ndata, Double_t &a0, Double_t &a1, Int_t &ifail);
extern void H1LeastSquareSeqnd(Int_t n, Double_t *a, Int_t idim, Int_t &ifail, Int_t k, Double_t *b);
// Internal exceptions for the CheckConsistency method
class DifferentDimension: public std::exception {};
class DifferentNumberOfBins: public std::exception {};
class DifferentAxisLimits: public std::exception {};
class DifferentBinLimits: public std::exception {};
class DifferentLabels: public std::exception {};
ClassImp(TH1);
////////////////////////////////////////////////////////////////////////////////
/// Histogram default constructor.
TH1::TH1(): TNamed(), TAttLine(), TAttFill(), TAttMarker()
{
fDirectory = 0;
fFunctions = new TList;
fNcells = 0;
fIntegral = 0;
fPainter = 0;
fEntries = 0;
fNormFactor = 0;
fTsumw = fTsumw2=fTsumwx=fTsumwx2=0;
fMaximum = -1111;
fMinimum = -1111;
fBufferSize = 0;
fBuffer = 0;
fBinStatErrOpt = kNormal;
fStatOverflows = EStatOverflows::kNeutral;
fXaxis.SetName("xaxis");
fYaxis.SetName("yaxis");
fZaxis.SetName("zaxis");
fXaxis.SetParent(this);
fYaxis.SetParent(this);
fZaxis.SetParent(this);
UseCurrentStyle();
}
////////////////////////////////////////////////////////////////////////////////
/// Histogram default destructor.
TH1::~TH1()
{
if (!TestBit(kNotDeleted)) {
return;
}
delete[] fIntegral;
fIntegral = 0;
delete[] fBuffer;
fBuffer = 0;
if (fFunctions) {
R__WRITE_LOCKGUARD(ROOT::gCoreMutex);
fFunctions->SetBit(kInvalidObject);
TObject* obj = 0;
//special logic to support the case where the same object is
//added multiple times in fFunctions.
//This case happens when the same object is added with different
//drawing modes
//In the loop below we must be careful with objects (eg TCutG) that may
// have been added to the list of functions of several histograms
//and may have been already deleted.
while ((obj = fFunctions->First())) {
while(fFunctions->Remove(obj)) { }
if (!obj->TestBit(kNotDeleted)) {
break;
}
delete obj;
obj = 0;
}
delete fFunctions;
fFunctions = 0;
}
if (fDirectory) {
fDirectory->Remove(this);
fDirectory = 0;
}
delete fPainter;
fPainter = 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Normal constructor for fix bin size histograms.
/// Creates the main histogram structure.
///
/// \param[in] name name of histogram (avoid blanks)
/// \param[in] title histogram title.
/// If title is of the form stringt;stringx;stringy;stringz`
/// the histogram title is set to `stringt`,
/// the x axis title to `stringy`, the y axis title to `stringy`, etc.
/// \param[in] nbins number of bins
/// \param[in] xlow low edge of first bin
/// \param[in] xup upper edge of last bin (not included in last bin)
///
/// When an histogram is created, it is automatically added to the list
/// of special objects in the current directory.
/// To find the pointer to this histogram in the current directory
/// by its name, do:
/// ~~~ {.cpp}
/// TH1F *h1 = (TH1F*)gDirectory->FindObject(name);
/// ~~~
TH1::TH1(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
:TNamed(name,title), TAttLine(), TAttFill(), TAttMarker()
{
Build();
if (nbins <= 0) {Warning("TH1","nbins is <=0 - set to nbins = 1"); nbins = 1; }
fXaxis.Set(nbins,xlow,xup);
fNcells = fXaxis.GetNbins()+2;
}
////////////////////////////////////////////////////////////////////////////////
/// Normal constructor for variable bin size histograms.
/// Creates the main histogram structure.
///
/// \param[in] name name of histogram (avoid blanks)
/// \param[in] title histogram title.
/// If title is of the form `stringt;stringx;stringy;stringz`
/// the histogram title is set to `stringt`,
/// the x axis title to `stringy`, the y axis title to `stringy`, etc.
/// \param[in] nbins number of bins
/// \param[in] xbins array of low-edges for each bin.
/// This is an array of size nbins+1
TH1::TH1(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
:TNamed(name,title), TAttLine(), TAttFill(), TAttMarker()
{
Build();
if (nbins <= 0) {Warning("TH1","nbins is <=0 - set to nbins = 1"); nbins = 1; }
if (xbins) fXaxis.Set(nbins,xbins);
else fXaxis.Set(nbins,0,1);
fNcells = fXaxis.GetNbins()+2;
}
////////////////////////////////////////////////////////////////////////////////
/// Normal constructor for variable bin size histograms.
///
/// \param[in] name name of histogram (avoid blanks)
/// \param[in] title histogram title.
/// If title is of the form `stringt;stringx;stringy;stringz`
/// the histogram title is set to `stringt`,
/// the x axis title to `stringy`, the y axis title to `stringy`, etc.
/// \param[in] nbins number of bins
/// \param[in] xbins array of low-edges for each bin.
/// This is an array of size nbins+1
TH1::TH1(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
:TNamed(name,title), TAttLine(), TAttFill(), TAttMarker()
{
Build();
if (nbins <= 0) {Warning("TH1","nbins is <=0 - set to nbins = 1"); nbins = 1; }
if (xbins) fXaxis.Set(nbins,xbins);
else fXaxis.Set(nbins,0,1);
fNcells = fXaxis.GetNbins()+2;
}
////////////////////////////////////////////////////////////////////////////////
/// Copy constructor.
/// The list of functions is not copied. (Use Clone if needed)
TH1::TH1(const TH1 &h) : TNamed(), TAttLine(), TAttFill(), TAttMarker()
{
((TH1&)h).Copy(*this);
}
////////////////////////////////////////////////////////////////////////////////
/// Static function: cannot be inlined on Windows/NT.
Bool_t TH1::AddDirectoryStatus()
{
return fgAddDirectory;
}
////////////////////////////////////////////////////////////////////////////////
/// Browse the Histogram object.
void TH1::Browse(TBrowser *b)
{
Draw(b ? b->GetDrawOption() : "");
gPad->Update();
}
////////////////////////////////////////////////////////////////////////////////
/// Creates histogram basic data structure.
void TH1::Build()
{
fDirectory = 0;
fPainter = 0;
fIntegral = 0;
fEntries = 0;
fNormFactor = 0;
fTsumw = fTsumw2=fTsumwx=fTsumwx2=0;
fMaximum = -1111;
fMinimum = -1111;
fBufferSize = 0;
fBuffer = 0;
fBinStatErrOpt = kNormal;
fStatOverflows = EStatOverflows::kNeutral;
fXaxis.SetName("xaxis");
fYaxis.SetName("yaxis");
fZaxis.SetName("zaxis");
fYaxis.Set(1,0.,1.);
fZaxis.Set(1,0.,1.);
fXaxis.SetParent(this);
fYaxis.SetParent(this);
fZaxis.SetParent(this);
SetTitle(fTitle.Data());
fFunctions = new TList;
UseCurrentStyle();
if (TH1::AddDirectoryStatus()) {
fDirectory = gDirectory;
if (fDirectory) {
fFunctions->UseRWLock();
fDirectory->Append(this,kTRUE);
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// Performs the operation: `this = this + c1*f1`
/// if errors are defined (see TH1::Sumw2), errors are also recalculated.
///
/// By default, the function is computed at the centre of the bin.
/// if option "I" is specified (1-d histogram only), the integral of the
/// function in each bin is used instead of the value of the function at
/// the centre of the bin.
///
/// Only bins inside the function range are recomputed.
///
/// IMPORTANT NOTE: If you intend to use the errors of this histogram later
/// you should call Sumw2 before making this operation.
/// This is particularly important if you fit the histogram after TH1::Add
///
/// The function return kFALSE if the Add operation failed
Bool_t TH1::Add(TF1 *f1, Double_t c1, Option_t *option)
{
if (!f1) {
Error("Add","Attempt to add a non-existing function");
return kFALSE;
}
TString opt = option;
opt.ToLower();
Bool_t integral = kFALSE;
if (opt.Contains("i") && fDimension == 1) integral = kTRUE;
Int_t ncellsx = GetNbinsX() + 2; // cells = normal bins + underflow bin + overflow bin
Int_t ncellsy = GetNbinsY() + 2;
Int_t ncellsz = GetNbinsZ() + 2;
if (fDimension < 2) ncellsy = 1;
if (fDimension < 3) ncellsz = 1;
// delete buffer if it is there since it will become invalid
if (fBuffer) BufferEmpty(1);
// - Add statistics
Double_t s1[10];
for (Int_t i = 0; i < 10; ++i) s1[i] = 0;
PutStats(s1);
SetMinimum();
SetMaximum();
// - Loop on bins (including underflows/overflows)
Int_t bin, binx, biny, binz;
Double_t cu=0;
Double_t xx[3];
Double_t *params = 0;
f1->InitArgs(xx,params);
for (binz = 0; binz < ncellsz; ++binz) {
xx[2] = fZaxis.GetBinCenter(binz);
for (biny = 0; biny < ncellsy; ++biny) {
xx[1] = fYaxis.GetBinCenter(biny);
for (binx = 0; binx < ncellsx; ++binx) {
xx[0] = fXaxis.GetBinCenter(binx);
if (!f1->IsInside(xx)) continue;
TF1::RejectPoint(kFALSE);
bin = binx + ncellsx * (biny + ncellsy * binz);
if (integral) {
cu = c1*f1->Integral(fXaxis.GetBinLowEdge(binx), fXaxis.GetBinUpEdge(binx), 0.) / fXaxis.GetBinWidth(binx);
} else {
cu = c1*f1->EvalPar(xx);
}
if (TF1::RejectedPoint()) continue;
AddBinContent(bin,cu);
}
}
}
return kTRUE;
}
////////////////////////////////////////////////////////////////////////////////
/// Performs the operation: `this = this + c1*h1`
/// If errors are defined (see TH1::Sumw2), errors are also recalculated.
///
/// Note that if h1 has Sumw2 set, Sumw2 is automatically called for this
/// if not already set.
///
/// Note also that adding histogram with labels is not supported, histogram will be
/// added merging them by bin number independently of the labels.
/// For adding histogram with labels one should use TH1::Merge
///
/// SPECIAL CASE (Average/Efficiency histograms)
/// For histograms representing averages or efficiencies, one should compute the average
/// of the two histograms and not the sum. One can mark a histogram to be an average
/// histogram by setting its bit kIsAverage with
/// myhist.SetBit(TH1::kIsAverage);
/// Note that the two histograms must have their kIsAverage bit set
///
/// IMPORTANT NOTE1: If you intend to use the errors of this histogram later
/// you should call Sumw2 before making this operation.
/// This is particularly important if you fit the histogram after TH1::Add
///
/// IMPORTANT NOTE2: if h1 has a normalisation factor, the normalisation factor
/// is used , ie this = this + c1*factor*h1
/// Use the other TH1::Add function if you do not want this feature
///
/// The function return kFALSE if the Add operation failed
Bool_t TH1::Add(const TH1 *h1, Double_t c1)
{
if (!h1) {
Error("Add","Attempt to add a non-existing histogram");
return kFALSE;
}
// delete buffer if it is there since it will become invalid
if (fBuffer) BufferEmpty(1);
bool useMerge = (c1 == 1. && !this->TestBit(kIsAverage) && !h1->TestBit(kIsAverage) );
try {
CheckConsistency(this,h1);
useMerge = kFALSE;
} catch(DifferentNumberOfBins&) {
if (useMerge)
Info("Add","Attempt to add histograms with different number of bins - trying to use TH1::Merge");
else {
Error("Add","Attempt to add histograms with different number of bins : nbins h1 = %d , nbins h2 = %d",GetNbinsX(), h1->GetNbinsX());
return kFALSE;
}
} catch(DifferentAxisLimits&) {
if (useMerge)
Info("Add","Attempt to add histograms with different axis limits - trying to use TH1::Merge");
else
Warning("Add","Attempt to add histograms with different axis limits");
} catch(DifferentBinLimits&) {
if (useMerge)
Info("Add","Attempt to add histograms with different bin limits - trying to use TH1::Merge");
else
Warning("Add","Attempt to add histograms with different bin limits");
} catch(DifferentLabels&) {
// in case of different labels -
if (useMerge)
Info("Add","Attempt to add histograms with different labels - trying to use TH1::Merge");
else
Info("Warning","Attempt to add histograms with different labels");
}
if (useMerge) {
TList l;
l.Add(const_cast<TH1*>(h1));
auto iret = Merge(&l);
return (iret >= 0);
}
// Create Sumw2 if h1 has Sumw2 set
if (fSumw2.fN == 0 && h1->GetSumw2N() != 0) Sumw2();
// - Add statistics
Double_t entries = TMath::Abs( GetEntries() + c1 * h1->GetEntries() );
// statistics can be preserved only in case of positive coefficients
// otherwise with negative c1 (histogram subtraction) one risks to get negative variances
Bool_t resetStats = (c1 < 0);
Double_t s1[kNstat] = {0};
Double_t s2[kNstat] = {0};
if (!resetStats) {
// need to initialize to zero s1 and s2 since
// GetStats fills only used elements depending on dimension and type
GetStats(s1);
h1->GetStats(s2);
}
SetMinimum();
SetMaximum();
// - Loop on bins (including underflows/overflows)
Double_t factor = 1;
if (h1->GetNormFactor() != 0) factor = h1->GetNormFactor()/h1->GetSumOfWeights();;
Double_t c1sq = c1 * c1;
Double_t factsq = factor * factor;
for (Int_t bin = 0; bin < fNcells; ++bin) {
//special case where histograms have the kIsAverage bit set
if (this->TestBit(kIsAverage) && h1->TestBit(kIsAverage)) {
Double_t y1 = h1->RetrieveBinContent(bin);
Double_t y2 = this->RetrieveBinContent(bin);
Double_t e1sq = h1->GetBinErrorSqUnchecked(bin);
Double_t e2sq = this->GetBinErrorSqUnchecked(bin);
Double_t w1 = 1., w2 = 1.;
// consider all special cases when bin errors are zero
// see http://root-forum.cern.ch/viewtopic.php?f=3&t=13299
if (e1sq) w1 = 1. / e1sq;
else if (h1->fSumw2.fN) {
w1 = 1.E200; // use an arbitrary huge value
if (y1 == 0) {
// use an estimated error from the global histogram scale
double sf = (s2[0] != 0) ? s2[1]/s2[0] : 1;
w1 = 1./(sf*sf);
}
}
if (e2sq) w2 = 1. / e2sq;
else if (fSumw2.fN) {
w2 = 1.E200; // use an arbitrary huge value
if (y2 == 0) {
// use an estimated error from the global histogram scale
double sf = (s1[0] != 0) ? s1[1]/s1[0] : 1;
w2 = 1./(sf*sf);
}
}
double y = (w1*y1 + w2*y2)/(w1 + w2);
UpdateBinContent(bin, y);
if (fSumw2.fN) {
double err2 = 1./(w1 + w2);
if (err2 < 1.E-200) err2 = 0; // to remove arbitrary value when e1=0 AND e2=0
fSumw2.fArray[bin] = err2;
}
} else { // normal case of addition between histograms
AddBinContent(bin, c1 * factor * h1->RetrieveBinContent(bin));
if (fSumw2.fN) fSumw2.fArray[bin] += c1sq * factsq * h1->GetBinErrorSqUnchecked(bin);
}
}
// update statistics (do here to avoid changes by SetBinContent)
if (resetStats) {
// statistics need to be reset in case coefficient are negative
ResetStats();
}
else {
for (Int_t i=0;i<kNstat;i++) {
if (i == 1) s1[i] += c1*c1*s2[i];
else s1[i] += c1*s2[i];
}
PutStats(s1);
SetEntries(entries);
}
return kTRUE;
}
////////////////////////////////////////////////////////////////////////////////
/// Replace contents of this histogram by the addition of h1 and h2.
///
/// `this = c1*h1 + c2*h2`
/// if errors are defined (see TH1::Sumw2), errors are also recalculated
///
/// Note that if h1 or h2 have Sumw2 set, Sumw2 is automatically called for this