-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathRooPlot.cxx
More file actions
1409 lines (1145 loc) · 47.8 KB
/
RooPlot.cxx
File metadata and controls
1409 lines (1145 loc) · 47.8 KB
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
/*****************************************************************************
* Project: RooFit *
* Package: RooFitCore *
* @(#)root/roofitcore:$Id$
* Authors: *
* WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu *
* DK, David Kirkby, UC Irvine, dkirkby@uci.edu *
* *
* Copyright (c) 2000-2005, Regents of the University of California *
* and Stanford University. All rights reserved. *
* *
* Redistribution and use in source and binary forms, *
* with or without modification, are permitted according to the terms *
* listed in LICENSE (http://roofit.sourceforge.net/license.txt) *
*****************************************************************************/
/**
\file RooPlot.cxx
\class RooPlot
\ingroup Roofitcore
Plot frame and a container for graphics objects
within that frame. As a frame, it provides the TH1-style public interface
for setting plot ranges, configuring axes, etc. As a container, it
holds an arbitrary set of objects that might be histograms of data,
curves representing a fit model, or text labels. Use the Draw()
method to draw a frame and the objects it contains. Use the various
add...() methods to add objects to be drawn. In general, the
add...() methods create a private copy of the object you pass them
and return a pointer to this copy. The caller owns the input object
and this class owns the returned object.
All RooAbsReal and RooAbsData derived classes implement plotOn()
functions that facilitate to plot themselves on a given RooPlot, e.g.
~~~ {.cpp}
RooPlot *frame = x.frame() ;
data.plotOn(frame) ;
pdf.plotOn(frame) ;
~~~
These high level functions also take care of any projections
or other mappings that need to be made to plot a multi-dimensional
object onto a one-dimensional plot.
**/
#include "RooPlot.h"
#include "RooAbsReal.h"
#include "RooAbsRealLValue.h"
#include "RooPlotable.h"
#include "RooArgSet.h"
#include "RooCurve.h"
#include "RooHist.h"
#include "RooMsgService.h"
#include "TClass.h"
#include "TBuffer.h"
#include "TH1D.h"
#include "TBrowser.h"
#include "TVirtualPad.h"
#include "TROOT.h"
#include "TAttLine.h"
#include "TAttFill.h"
#include "TAttMarker.h"
#include "TAttText.h"
#include "TDirectoryFile.h"
#include "TLegend.h"
#include "strlcpy.h"
#include <algorithm>
#include <cstring>
#include <iostream>
bool RooPlot::_addDirStatus = true ;
bool RooPlot::addDirectoryStatus()
{
return ROOT::Experimental::IsImplicitObjectOwnershipEnabled() && _addDirStatus;
}
bool RooPlot::setAddDirectoryStatus(bool flag) { bool ret = flag ; _addDirStatus = flag ; return ret ; }
////////////////////////////////////////////////////////////////////////////////
/// Default constructor
/// coverity[UNINIT_CTOR]
RooPlot::RooPlot()
{
if (gDirectory && addDirectoryStatus()) {
SetDirectory(gDirectory);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Constructor of RooPlot with range [xmin,xmax]
RooPlot::RooPlot(double xmin, double xmax, int nBins)
: _normBinWidth((xmax - xmin) / nBins)
{
_hist = new TH1D(histName(),"A RooPlot",nBins,xmin,xmax) ;
_hist->Sumw2(false) ;
_hist->GetSumw2()->Set(0) ;
_hist->SetDirectory(nullptr);
// Create an empty frame with the specified x-axis limits.
initialize();
}
namespace {
const RooAbsRealLValue& validateFiniteLimits(const RooAbsRealLValue &var)
{
if (!var.hasMin() || !var.hasMax()) {
std::stringstream ss;
ss << "RooPlot::RooPlot: cannot create plot for variable without finite limits: " << var.GetName();
oocoutE(nullptr, InputArguments) << ss.str() << std::endl;
throw std::runtime_error(ss.str());
}
return var;
}
} // namespace
////////////////////////////////////////////////////////////////////////////////
/// Construct a two-dimensional RooPlot with ranges and properties taken
/// from variables var1 and var2
RooPlot::RooPlot(const RooAbsRealLValue &var1, const RooAbsRealLValue &var2)
: RooPlot{validateFiniteLimits(var1),
validateFiniteLimits(var2),
var1.getMin(),
var1.getMax(),
var2.getMin(),
var2.getMax()}
{
}
////////////////////////////////////////////////////////////////////////////////
/// Construct a two-dimensional RooPlot with ranges and properties taken
/// from variables var1 and var2 but with an overriding range definition
/// of [xmin,xmax] x [ymin,ymax]
RooPlot::RooPlot(const RooAbsRealLValue &var1, const RooAbsRealLValue &var2, double xmin, double xmax, double ymin,
double ymax)
: RooPlot{xmin, xmax}
{
SetMinimum(ymin);
SetMaximum(ymax);
SetXTitle(var1.getTitle(true));
SetYTitle(var2.getTitle(true));
}
////////////////////////////////////////////////////////////////////////////////
/// Create an 1-dimensional with all properties taken from 'var', but
/// with an explicit range [xmin,xmax] and a default binning of 'nbins'
RooPlot::RooPlot(const RooAbsRealLValue &var, double xmin, double xmax, Int_t nbins)
: _plotVar(const_cast<RooAbsRealLValue *>(&var)), _normBinWidth((xmax - xmin) / nbins)
{
_hist = new TH1D(histName(),"RooPlot",nbins,xmin,xmax) ;
_hist->Sumw2(false) ;
_hist->GetSumw2()->Set(0) ;
_hist->SetDirectory(nullptr);
// In the past, the plot variable was cloned, but there was no apparent reason for doing so.
TString xtitle= var.getTitle(true);
SetXTitle(xtitle.Data());
SetTitle("A RooPlot of \"" + var.getTitle() + "\"");
initialize();
}
////////////////////////////////////////////////////////////////////////////////
/// Create a new frame for a given variable in x. This is just a
/// wrapper for the RooPlot constructor with the same interface.
///
/// More details.
/// \param[in] var The variable on the x-axis
/// \param[in] xmin Left edge of the x-axis
/// \param[in] xmax Right edge of the x-axis
/// \param[in] nBins number of bins on the x-axis
RooPlot* RooPlot::frame(const RooAbsRealLValue &var, double xmin, double xmax, Int_t nBins){
return new RooPlot(var,xmin,xmax,nBins);
}
////////////////////////////////////////////////////////////////////////////////
/// Create a new frame for a given variable in x, adding bin labels.
/// The binning will be extracted from the variable given. The bin
/// labels will be set as "%g-%g" for the left and right edges of each
/// bin of the given variable.
///
/// More details.
/// \param[in] var The variable on the x-axis
RooPlot* RooPlot::frameWithLabels(const RooAbsRealLValue &var){
RooPlot* pl = new RooPlot();
int nbins = var.getBinning().numBins();
pl->_hist = new TH1D(pl->histName(),"RooPlot",nbins,var.getMin(),var.getMax()) ;
pl->_hist->Sumw2(false) ;
pl->_hist->GetSumw2()->Set(0) ;
pl->_hist->SetDirectory(nullptr);
pl->_hist->SetNdivisions(-nbins);
for(int i=0; i<nbins; ++i){
TString s = TString::Format("%g-%g",var.getBinning().binLow(i),var.getBinning().binHigh(i));
pl->_hist->GetXaxis()->SetBinLabel(i+1,s);
}
// In the past, the plot variable was cloned, but there was no apparent reason for doing so.
pl->_plotVar = const_cast<RooAbsRealLValue*>(&var);
TString xtitle= var.getTitle(true);
pl->SetXTitle(xtitle.Data());
TString title("A RooPlot of \"");
title.Append(var.getTitle());
title.Append("\"");
pl->SetTitle(title.Data());
pl->initialize();
pl->_normBinWidth = 1.;
return pl;
}
////////////////////////////////////////////////////////////////////////////////
/// Return empty clone of current RooPlot
RooPlot* RooPlot::emptyClone(const char* name)
{
RooPlot* clone = new RooPlot(*_plotVar,_hist->GetXaxis()->GetXmin(),_hist->GetXaxis()->GetXmax(),_hist->GetNbinsX()) ;
clone->SetName(name) ;
return clone ;
}
////////////////////////////////////////////////////////////////////////////////
/// Perform initialization that is common to all constructors.
void RooPlot::initialize()
{
SetName(histName()) ;
if (gDirectory && addDirectoryStatus()) {
SetDirectory(gDirectory);
}
// We do not have useful stats of our own
_hist->SetStats(false);
_hist->SetDirectory(nullptr);
// Default vertical padding of our enclosed objects
setPadFactor(0.05);
}
////////////////////////////////////////////////////////////////////////////////
/// Construct automatic name of internal TH1
TString RooPlot::histName() const
{
if (_plotVar) {
return TString(Form("frame_%s_%zx",_plotVar->GetName(),reinterpret_cast<size_t>(this))) ;
} else {
return TString(Form("frame_%zx",reinterpret_cast<size_t>(this))) ;
}
}
////////////////////////////////////////////////////////////////////////////////
/// Destructor
RooPlot::~RooPlot()
{
// Delete the items in our container and our iterator.
if (_dir) {
_dir->GetList()->RecursiveRemove(this) ;
}
for(auto& item : _items) delete item.first;
if(_plotVarSet) delete _plotVarSet;
if(_normVars) delete _normVars;
delete _hist ;
}
////////////////////////////////////////////////////////////////////////////////
/// Set the directory that this plot is associated to.
/// Setting it to `nullptr` will remove the object from all directories.
/// Like TH1::SetDirectory.
void RooPlot::SetDirectory(TDirectory *dir) {
if (_dir) {
_dir->GetList()->RecursiveRemove(this);
}
_dir = dir;
if (_dir) {
_dir->Append(this);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Install the given set of observables are reference normalization
/// variables for this frame. These observables are e.g. later used
/// to automatically project out observables when plotting functions
/// on this frame. This function is only effective when called the
/// first time on a frame
void RooPlot::updateNormVars(const RooArgSet &vars)
{
if(_normVars == nullptr) {
_normVars = new RooArgSet;
vars.snapshot(*_normVars, true);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Add a generic object to this plot. The specified options will be
/// used to Draw() this object later. The caller transfers ownership
/// of the object with this call, and the object will be deleted
/// when its containing plot object is destroyed.
void RooPlot::addObject(TObject *obj, Option_t *drawOptions, bool invisible)
{
if(nullptr == obj) {
coutE(InputArguments) << fName << "::addObject: called with a null pointer" << std::endl;
return;
}
DrawOpt opt(drawOptions) ;
opt.invisible = invisible ;
_items.emplace_back(obj,opt.rawOpt());
}
////////////////////////////////////////////////////////////////////////////////
/// Add a TH1 histogram object to this plot. The specified options
/// will be used to Draw() this object later. "SAME" will be added to
/// the options if they are not already present. The caller transfers
/// ownership of the object with this call, and the object will be
/// deleted when its containing plot object is destroyed.
void RooPlot::addTH1(TH1 *hist, Option_t *drawOptions, bool invisible)
{
if(nullptr == hist) {
coutE(InputArguments) << fName << "::addTH1: called with a null pointer" << std::endl;
return;
}
// check that this histogram is really 1D
if(1 != hist->GetDimension()) {
coutE(InputArguments) << fName << "::addTH1: cannot plot histogram with "
<< hist->GetDimension() << " dimensions" << std::endl;
return;
}
// add option "SAME" if necessary
TString options(drawOptions);
options.ToUpper();
if(!options.Contains("SAME")) options.Append("SAME");
// update our y-axis label and limits
updateYAxis(hist->GetMinimum(),hist->GetMaximum(),hist->GetYaxis()->GetTitle());
// use this histogram's normalization if necessary
updateFitRangeNorm(hist);
// add the histogram to our list
addObject(hist,options.Data(),invisible);
}
namespace {
// this helper function is intended to translate a graph from a regular axis to a labelled axis
// this version uses TGraph, which is a parent of RooCurve
void translateGraph(TH1* hist, RooAbsRealLValue* xvar, TGraph* graph){
// if the graph already has a labelled axis, don't do anything
if(graph->GetXaxis()->IsAlphanumeric()) return;
double xmin = hist->GetXaxis()->GetXmin();
double xmax = hist->GetXaxis()->GetXmax();
if(graph->TestBit(TGraph::kIsSortedX)){
// sorted graphs are "line graphs"
// evaluate the graph at the lower and upper edge as well as the center of each bin
std::vector<double> x;
std::vector<double> y;
x.push_back(xmin);
y.push_back(graph->Eval(xvar->getBinning().binLow(0)));
for(int i=0; i<hist->GetNbinsX(); ++i){
x.push_back(hist->GetXaxis()->GetBinUpEdge(i+1));
y.push_back(graph->Eval(xvar->getBinning().binHigh(i)));
x.push_back(hist->GetXaxis()->GetBinCenter(i+1));
y.push_back(graph->Eval(xvar->getBinning().binCenter(i)));
}
int n = x.size();
graph->Set(n);
for(int i=0; i<n; ++i){
graph->SetPoint(i,x[i],y[i]);
}
graph->Sort();
} else {
// unsorted graphs are "area graphs"
std::map<int,double> minValues;
std::map<int,double> maxValues;
int n = graph->GetN();
double x;
double y;
// for each bin, find the min and max points to form an envelope
for(int i=0; i<n; ++i){
graph->GetPoint(i,x,y);
int bin = xvar->getBinning().binNumber(x)+1;
if(maxValues.find(bin)!=maxValues.end()){
maxValues[bin] = std::max(maxValues[bin],y);
} else {
maxValues[bin] = y;
}
if(minValues.find(bin)!=minValues.end()){
minValues[bin] = std::min(minValues[bin],y);
} else {
minValues[bin] = y;
}
}
double xminY = graph->Eval(xmin);
double xmaxY = graph->Eval(xmax);
graph->Set(hist->GetNbinsX()+2);
int np=0;
graph->SetPoint(np,xmin,xminY);
// assign the calculated envelope boundaries to the bin centers of the bins
for(auto it = maxValues.begin(); it != maxValues.end(); ++it){
graph->SetPoint(++np,hist->GetXaxis()->GetBinCenter(it->first),it->second);
}
graph->SetPoint(++np,xmax,xmaxY);
for(auto it = minValues.rbegin(); it != minValues.rend(); ++it){
graph->SetPoint(++np,hist->GetXaxis()->GetBinCenter(it->first),it->second);
}
graph->SetPoint(++np,xmin,xminY);
}
// make sure that the graph also has the labels set, such that subsequent calls to translate this graph will not do anything
graph->GetXaxis()->Set(hist->GetNbinsX(),xmin,xmax);
for(int i=0; i<hist->GetNbinsX(); ++i){
graph->GetXaxis()->SetBinLabel(i+1,hist->GetXaxis()->GetBinLabel(i+1));
}
}
// this version uses TGraphErrors, which is a parent of RooHist
void translateGraph(TH1* hist, RooAbsRealLValue* xvar, TGraphAsymmErrors* graph){
// if the graph already has a labelled axis, don't do anything
if(graph->GetXaxis()->IsAlphanumeric()) return;
int n = graph->GetN();
double xmin = hist->GetXaxis()->GetXmin();
double xmax = hist->GetXaxis()->GetXmax();
double x;
double y;
// as this graph is histogram-like, we expect there to be one point per bin
// we just move these points to the respective bin centers
for(int i=0; i<n; ++i){
if(graph->GetPoint(i,x,y)!=i) break;
int bin = xvar->getBinning().binNumber(x);
graph->SetPoint(i,hist->GetXaxis()->GetBinCenter(bin+1),y);
graph->SetPointEXhigh(i,0.5*hist->GetXaxis()->GetBinWidth(bin+1));
graph->SetPointEXlow(i,0.5*hist->GetXaxis()->GetBinWidth(bin+1));
}
graph->GetXaxis()->Set(hist->GetNbinsX(),xmin,xmax);
// make sure that the graph also has the labels set, such that subsequent calls to translate this graph will not do anything
for(int i=0; i<hist->GetNbinsX(); ++i){
graph->GetXaxis()->SetBinLabel(i+1,hist->GetXaxis()->GetBinLabel(i+1));
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// Add the specified plotable object to our plot. Increase our y-axis
/// limits to fit this object if necessary. The default lower-limit
/// is zero unless we are plotting an object that takes on negative values.
/// This call transfers ownership of the plotable object to this class.
/// The plotable object will be deleted when this plot object is deleted.
void RooPlot::addPlotable(RooPlotable *plotable, Option_t *drawOptions, bool invisible, bool refreshNorm)
{
// update our y-axis label and limits
updateYAxis(plotable->getYAxisMin(),plotable->getYAxisMax(),plotable->getYAxisLabel());
// use this object's normalization if necessary
updateFitRangeNorm(plotable,refreshNorm) ;
// add this element to our list and remember its drawing option
TObject *obj= plotable->crossCast();
if(nullptr == obj) {
coutE(InputArguments) << fName << "::add: cross-cast to TObject failed (nothing added)" << std::endl;
}
else {
// if the frame axis is alphanumeric, the coordinates of the graph need to be translated to this binning
if(_hist->GetXaxis()->IsAlphanumeric()){
if(obj->InheritsFrom(RooCurve::Class())){
::translateGraph(_hist,_plotVar,static_cast<RooCurve*>(obj));
} else if(obj->InheritsFrom(RooHist::Class())){
::translateGraph(_hist,_plotVar,static_cast<RooHist*>(obj));
}
}
DrawOpt opt(drawOptions) ;
opt.invisible = invisible ;
_items.emplace_back(obj,opt.rawOpt());
}
}
////////////////////////////////////////////////////////////////////////////////
/// Update our plot normalization over our plot variable's fit range,
/// which will be determined by the first suitable object added to our plot.
void RooPlot::updateFitRangeNorm(const TH1* hist)
{
const TAxis* xa = const_cast<TH1 *>(hist)->GetXaxis() ;
_normBinWidth = (xa->GetXmax()-xa->GetXmin())/hist->GetNbinsX() ;
_normNumEvts = hist->GetEntries()/_normBinWidth ;
}
////////////////////////////////////////////////////////////////////////////////
/// Update our plot normalization over our plot variable's fit range,
/// which will be determined by the first suitable object added to our plot.
void RooPlot::updateFitRangeNorm(const RooPlotable* rp, bool refreshNorm)
{
if (_normNumEvts != 0) {
// If refresh feature is disabled stop here
if (!refreshNorm) return ;
double corFac(1.0) ;
if (dynamic_cast<const RooHist*>(rp)) corFac = _normBinWidth/rp->getFitRangeBinW() ;
if (std::abs(rp->getFitRangeNEvt()/corFac-_normNumEvts)>1e-6) {
coutI(Plotting) << "RooPlot::updateFitRangeNorm: New event count of " << rp->getFitRangeNEvt()/corFac
<< " will supersede previous event count of " << _normNumEvts << " for normalization of PDF projections" << std::endl ;
}
// Nominal bin width (i.e event density) is already locked in by previously drawn histogram
// scale this histogram to match that density
_normNumEvts = rp->getFitRangeNEvt()/corFac ;
_normObj = rp ;
// std::cout << "correction factor = " << _normBinWidth << "/" << rp->getFitRangeBinW() << std::endl ;
// std::cout << "updating numevts to " << _normNumEvts << std::endl ;
} else {
_normObj = rp ;
_normNumEvts = rp->getFitRangeNEvt() ;
if (rp->getFitRangeBinW()) {
_normBinWidth = rp->getFitRangeBinW() ;
}
// std::cout << "updating numevts to " << _normNumEvts << std::endl ;
}
}
////////////////////////////////////////////////////////////////////////////////
/// Update our y-axis limits to accommodate an object whose spread
/// in y is (ymin,ymax). Use the specified y-axis label if we don't
/// have one assigned already.
void RooPlot::updateYAxis(double ymin, double ymax, const char *label)
{
// force an implicit lower limit of zero if appropriate
if(GetMinimum() == 0 && ymin > 0) ymin= 0;
// calculate padded values
double ypad= getPadFactor()*(ymax-ymin);
ymax+= ypad;
if(ymin < 0) ymin-= ypad;
// update our limits if necessary
if(GetMaximum() < ymax) {
_defYmax = ymax ;
SetMaximum(ymax);
// if we don't do this - Unzoom on y-axis will reset upper bound to 1
_hist->SetBinContent(1,ymax) ;
}
if(GetMinimum() > ymin) {
_defYmin = ymin ;
SetMinimum(ymin);
}
// use the specified y-axis label if we don't have one already
if(0 == strlen(_hist->GetYaxis()->GetTitle())) _hist->SetYTitle(label);
}
////////////////////////////////////////////////////////////////////////////////
/// Draw this plot and all of the elements it contains. The specified options
/// only apply to the drawing of our frame. The options specified in our add...()
/// methods will be used to draw each object we contain.
void RooPlot::Draw(Option_t *option)
{
TString optArg = option ;
optArg.ToLower() ;
// This draw options prevents the histogram with one dummy entry
// to be drawn
if (optArg.Contains("same")) {
_hist->Draw("FUNCSAME");
} else {
_hist->Draw("FUNC");
}
for(auto const& item : _items) {
TObject &obj = *item.first;
DrawOpt opt(item.second.c_str()) ;
if (!opt.invisible) {
//LM: in case of a TGraph derived object, do not use default "" option
// which is "ALP" from 5.34.10 (and will then redrawn the axis) but use "LP"
if (!strlen(opt.drawOptions) && obj.IsA()->InheritsFrom(TGraph::Class()) ) strlcpy(opt.drawOptions,"LP",3);
obj.Draw(opt.drawOptions);
}
}
_hist->Draw("AXISSAME");
}
////////////////////////////////////////////////////////////////////////////////
/// Print frame name
void RooPlot::printName(std::ostream& os) const
{
os << GetName() ;
}
////////////////////////////////////////////////////////////////////////////////
/// Print frame title
void RooPlot::printTitle(std::ostream& os) const
{
os << GetTitle() ;
}
////////////////////////////////////////////////////////////////////////////////
/// Print frame class name
void RooPlot::printClassName(std::ostream& os) const
{
os << ClassName() ;
}
////////////////////////////////////////////////////////////////////////////////
void RooPlot::printArgs(std::ostream& os) const
{
if (_plotVar) {
os << "[" ;
_plotVar->printStream(os,kName,kInline) ;
os << "]" ;
}
}
////////////////////////////////////////////////////////////////////////////////
/// Print frame arguments
void RooPlot::printValue(std::ostream& os) const
{
os << "(" ;
bool first(true) ;
for(auto const& item : _items) {
TObject &obj = *item.first;
if (first) {
first=false ;
} else {
os << "," ;
}
if(obj.IsA()->InheritsFrom(RooPrintable::Class())) {
auto po = dynamic_cast<RooPrintable&>(obj) ;
// coverity[FORWARD_NULL]
po.printStream(os,kClassName|kName,kInline) ;
}
// is it a TNamed subclass?
else {
os << obj.ClassName() << "::" << obj.GetName() ;
}
}
os << ")" ;
}
////////////////////////////////////////////////////////////////////////////////
/// Frame detailed printing
void RooPlot::printMultiline(std::ostream& os, Int_t /*content*/, bool verbose, TString indent) const
{
TString deeper(indent);
deeper.Append(" ");
if(nullptr != _plotVar) {
os << indent << "RooPlot " << GetName() << " (" << GetTitle() << ") plots variable ";
_plotVar->printStream(os,kName|kTitle,kSingleLine,"");
}
else {
os << indent << "RooPlot " << GetName() << " (" << GetTitle() << ") has no associated plot variable" << std::endl ;
}
os << indent << " Plot frame contains " << _items.size() << " object(s):" << std::endl;
if(verbose) {
Int_t i=0 ;
for(auto const& item : _items) {
TObject &obj = *item.first;
os << deeper << "[" << i++ << "] (Options=\"" << item.second << "\") ";
// Is this a printable object?
if(obj.IsA()->InheritsFrom(RooPrintable::Class())) {
auto po = dynamic_cast<RooPrintable&>(obj) ;
po.printStream(os,kName|kClassName|kArgs|kExtras,kSingleLine) ;
}
// is it a TNamed subclass?
else {
os << obj.ClassName() << "::" << obj.GetName() << std::endl;
}
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// Return the name of the object at slot 'idx' in this RooPlot.
/// If the given index is out of range, return a null pointer
const char* RooPlot::nameOf(Int_t idx) const
{
TObject* obj = _items.at(idx).first;
if (!obj) {
coutE(InputArguments) << "RooPlot::nameOf(" << GetName() << ") index " << idx << " out of range" << std::endl ;
return nullptr ;
}
return obj->GetName() ;
}
////////////////////////////////////////////////////////////////////////////////
/// Return the name of the object at slot 'idx' in this RooPlot.
/// If the given index is out of range, return a null pointer
TObject* RooPlot::getObject(Int_t idx) const
{
TObject* obj = _items.at(idx).first;
if (!obj) {
coutE(InputArguments) << "RooPlot::getObject(" << GetName() << ") index " << idx << " out of range" << std::endl ;
return nullptr ;
}
return obj ;
}
////////////////////////////////////////////////////////////////////////////////
/// Return a pointer to the line attributes of the named object in this plot,
/// or zero if the named object does not exist or does not have line attributes.
TAttLine *RooPlot::getAttLine(const char *name) const
{
return dynamic_cast<TAttLine*>(findObject(name));
}
////////////////////////////////////////////////////////////////////////////////
/// Return a pointer to the fill attributes of the named object in this plot,
/// or zero if the named object does not exist or does not have fill attributes.
TAttFill *RooPlot::getAttFill(const char *name) const
{
return dynamic_cast<TAttFill*>(findObject(name));
}
////////////////////////////////////////////////////////////////////////////////
/// Return a pointer to the marker attributes of the named object in this plot,
/// or zero if the named object does not exist or does not have marker attributes.
TAttMarker *RooPlot::getAttMarker(const char *name) const
{
return dynamic_cast<TAttMarker*>(findObject(name));
}
////////////////////////////////////////////////////////////////////////////////
/// Return a pointer to the text attributes of the named object in this plot,
/// or zero if the named object does not exist or does not have text attributes.
TAttText *RooPlot::getAttText(const char *name) const
{
return dynamic_cast<TAttText*>(findObject(name));
}
////////////////////////////////////////////////////////////////////////////////
/// Return a RooCurve pointer of the named object in this plot,
/// or zero if the named object does not exist or is not a RooCurve
RooCurve* RooPlot::getCurve(const char* name) const
{
return dynamic_cast<RooCurve*>(findObject(name)) ;
}
////////////////////////////////////////////////////////////////////////////////
/// Return a RooCurve pointer of the named object in this plot,
/// or zero if the named object does not exist or is not a RooCurve
RooHist* RooPlot::getHist(const char* name) const
{
return dynamic_cast<RooHist*>(findObject(name)) ;
}
////////////////////////////////////////////////////////////////////////////////
/// Remove object with given name, or last object added if no name is given.
void RooPlot::remove(const char* name, bool deleteToo)
{
if(name == nullptr) {
if(!_items.empty()) {
if(deleteToo) delete _items.back().first;
_items.pop_back();
} else {
coutE(InputArguments) << "RooPlot::remove(" << GetName() << ") ERROR: plot frame is empty, cannot remove last object" << std::endl ;
}
} else {
auto item = findItem(name);
if(item == _items.end()) {
coutE(InputArguments) << "RooPlot::remove(" << GetName() << ") ERROR: no object found with name " << name << std::endl ;
} else {
if(deleteToo) delete item->first;
_items.erase(item);
}
}
}
namespace {
template<class Iter>
void moveBefore(Iter before, Iter target) {
auto d = std::distance(before, target);
if(d > 0) std::rotate(before, target, target + 1);
else if(d < 0) std::rotate(target, target+1, before);
}
} // namespace
////////////////////////////////////////////////////////////////////////////////
/// Change the order in which our contained objects are drawn so that
/// the target object is drawn just before the specified object.
/// Returns false if either object does not exist.
bool RooPlot::drawBefore(const char *before, const char *target)
{
auto iterBefore = findItem(before);
auto iterTarget = findItem(target);
if(iterBefore == _items.end() || iterTarget == _items.end()) return false;
moveBefore(iterBefore, iterTarget);
return true;
}
////////////////////////////////////////////////////////////////////////////////
/// Change the order in which our contained objects are drawn so that
/// the target object is drawn just after the specified object.
/// Returns false if either object does not exist.
bool RooPlot::drawAfter(const char *after, const char *target)
{
auto iterAfter = findItem(after);
auto iterTarget = findItem(target);
if(iterAfter == _items.end() || iterTarget == _items.end()) return false;
moveBefore(iterAfter + 1, iterTarget);
return true;
}
////////////////////////////////////////////////////////////////////////////////
/// Find the named object in our list of items and return a pointer
/// to it. Return zero and print a warning message if the named
/// object cannot be found. If no name is supplied the last object
/// added is returned.
///
/// Note that the returned pointer is to a
/// TObject and so will generally need casting. Use the getAtt...()
/// methods to change the drawing style attributes of a contained
/// object directly.
TObject *RooPlot::findObject(const char *name, const TClass *tClass) const
{
TObject *ret = nullptr;
for (auto const &item : _items) {
TObject &obj = *item.first;
if ((!name || name[0] == '\0' || !TString(name).CompareTo(obj.GetName())) && (!tClass || (obj.IsA() == tClass))) {
ret = &obj;
}
}
if (ret == nullptr) {
std::stringstream error;
error << "RooPlot::findObject(" << GetName() << ") cannot find object " << (name ? name : "<last>") << "\n"
<< "Available objects are:\n";
for (auto const &item : _items) {
TObject &obj = *item.first;
error << " - " << obj.IsA()->GetName() << " \"" << obj.GetName() << "\"\n";
}
coutE(InputArguments) << error.str();
}
return ret;
}
RooPlot::Items::iterator RooPlot::findItem(std::string const& name)
{
return std::find_if(_items.begin(), _items.end(), [&name](auto const& item){
return name == item.first->GetName();
});
}
RooPlot::Items::const_iterator RooPlot::findItem(std::string const& name) const
{
return std::find_if(_items.begin(), _items.end(), [&name](auto const& item){
return name == item.first->GetName();
});
}
////////////////////////////////////////////////////////////////////////////////
/// Return the Draw() options registered for the named object. Return
/// an empty string if the named object cannot be found.
TString RooPlot::getDrawOptions(const char *name) const
{
auto item = findItem(name);
if(item == _items.end()) return "";
return DrawOpt{item->second.c_str()}.drawOptions;
}
////////////////////////////////////////////////////////////////////////////////
/// Register the specified drawing options for the named object.
/// Return false if the named object cannot be found.
bool RooPlot::setDrawOptions(const char *name, TString options)
{
auto item = findItem(name);
if(item == _items.end()) return false;
DrawOpt opt(item->second.c_str()) ;
strlcpy(opt.drawOptions,options,128) ;
item->second = opt.rawOpt();
return true;
}
////////////////////////////////////////////////////////////////////////////////
/// Returns true of object with given name is set to be invisible
bool RooPlot::getInvisible(const char* name) const
{
auto item = findItem(name);
if(item == _items.end()) return false;
return DrawOpt{item->second.c_str()}.invisible ;
}
////////////////////////////////////////////////////////////////////////////////
/// If flag is true object with 'name' is set to be invisible
/// i.e. it is not drawn when Draw() is called
void RooPlot::setInvisible(const char* name, bool flag)
{
auto item = findItem(name);
if(item != _items.end()) {
DrawOpt opt;
opt.initialize(item->second.c_str());
opt.invisible = flag;
item->second = opt.rawOpt();
}
}