forked from uboone/xsec_analyzer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSystematicsCalculator.hh
1924 lines (1571 loc) · 69.9 KB
/
SystematicsCalculator.hh
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
#pragma once
// Standard library includes
#include <memory>
// ROOT includes
#include "TDirectoryFile.h"
#include "TFile.h"
#include "TH1D.h"
#include "TH2D.h"
#include "TMatrixD.h"
#include "TParameter.h"
// STV analysis includes
#include "FilePropertiesManager.hh"
#include "UniverseMaker.hh"
#include "utils.hh"
// Helper function template that retrieves an object from a TDirectoryFile
// and loads a pointer to it into a std::unique_ptr of the correct type
template <typename T>
std::unique_ptr<T> get_object_unique_ptr(
const std::string &namecycle, TDirectory &df)
{
T *temp_ptr = nullptr;
df.GetObject(namecycle.c_str(), temp_ptr);
// Set the directory to nullptr in the case of ROOT histograms. This will
// avoid extra deletion attempts
TH1 *temp_hist_ptr = dynamic_cast<TH1 *>(temp_ptr);
if (temp_hist_ptr)
temp_hist_ptr->SetDirectory(nullptr);
return std::unique_ptr<T>(temp_ptr);
}
// Helper function to use on a new Universe object's histograms. Prevents
// auto-deletion problems by disassociating the Universe object's histograms
// from any TDirectory. Also turns off the stats box when plotting for
// convenience.
void set_stats_and_dir(Universe &univ)
{
univ.hist_reco_->SetStats(false);
univ.hist_reco_->SetDirectory(nullptr);
univ.hist_true_->SetStats(false);
univ.hist_true_->SetDirectory(nullptr);
univ.hist_2d_->SetStats(false);
univ.hist_2d_->SetDirectory(nullptr);
univ.hist_categ_->SetStats(false);
univ.hist_categ_->SetDirectory(nullptr);
univ.hist_reco2d_->SetStats(false);
univ.hist_reco2d_->SetDirectory(nullptr);
}
// Tests whether a string ends with another string. Taken from
// https://stackoverflow.com/a/874160/4081973. In C++20, you could use
// std::string::ends_with() instead.
bool has_ending(const std::string &fullString, const std::string &ending)
{
if (fullString.length() >= ending.length())
{
return (0 == fullString.compare(
fullString.length() - ending.length(), ending.length(), ending));
}
return false;
}
// Simple container for a TH2D that represents a covariance matrix
struct CovMatrix
{
CovMatrix() {}
CovMatrix(TH2D *cov_mat) : cov_matrix_(cov_mat) {}
CovMatrix(const TMatrixD &matrix)
{
int num_bins = matrix.GetNrows();
if (matrix.GetNcols() != num_bins)
throw std::runtime_error("Non-square"
" TMatrixD passed to the constructor of CovMatrix");
TH2D *temp_hist = new TH2D("temp_hist", "covariance; bin;"
" bin; covariance",
num_bins, 0., num_bins, num_bins, 0., num_bins);
temp_hist->SetDirectory(nullptr);
temp_hist->SetStats(false);
for (int r = 0; r < num_bins; ++r)
{
for (int c = 0; c < num_bins; ++c)
{
double cov = matrix(r, c);
// Note that TMatrixD element indices are zero-based while TH2D bin
// indices are one-based. We therefore correct for this here.
temp_hist->SetBinContent(r + 1, c + 1, cov);
}
}
cov_matrix_.reset(temp_hist);
}
std::unique_ptr<TH2D> cov_matrix_;
// Helper function for operator+=
void add_or_clone(std::unique_ptr<TH2D> &mine, TH2D *other)
{
if (!other)
return;
if (mine)
mine->Add(other);
else
{
TH2D *temp_clone = dynamic_cast<TH2D *>(
other->Clone("temp_clone"));
temp_clone->SetDirectory(nullptr);
temp_clone->SetStats(false);
mine.reset(temp_clone);
}
}
CovMatrix &operator+=(const CovMatrix &other)
{
add_or_clone(cov_matrix_, other.cov_matrix_.get());
return *this;
}
std::unique_ptr<TMatrixD> get_matrix() const
{
// Note that ROOT histogram bin indices are one-based to allow for
// underflow. The TMatrixDSym element indices, on the other hand,
// are zero-based.
int num_cm_bins = cov_matrix_->GetNbinsX();
auto result = std::make_unique<TMatrixD>(num_cm_bins, num_cm_bins);
// TODO: consider doing something more efficient than setting each
// element manually
for (int a = 0; a < num_cm_bins; ++a)
{
for (int b = 0; b < num_cm_bins; ++b)
{
result->operator()(a, b) = cov_matrix_->GetBinContent(a + 1, b + 1);
}
}
return result;
}
};
// Container that holds the results of subtracting the EXT+MC background from
// the measured data event counts in ordinary reco bins
struct MeasuredEvents
{
MeasuredEvents() {}
MeasuredEvents(TMatrixD *bkgd_subtracted_data, TMatrixD *bkgd,
TMatrixD *mc_plus_ext, TMatrixD *cov_mat)
: reco_signal_(bkgd_subtracted_data), reco_bkgd_(bkgd),
reco_mc_plus_ext_(mc_plus_ext), cov_matrix_(cov_mat)
{
if (bkgd_subtracted_data->GetNcols() != 1)
throw std::runtime_error(
"Non-row-vector background-subtracted signal passed to MeasuredEvents");
if (bkgd->GetNcols() != 1)
throw std::runtime_error("Non-row-vector"
" background prediction passed to MeasuredEvents");
if (mc_plus_ext->GetNcols() != 1)
throw std::runtime_error(
"Non-row-vector MC+EXT prediction passed to MeasuredEvents");
int num_ordinary_reco_bins = bkgd_subtracted_data->GetNrows();
if (cov_mat->GetNcols() != num_ordinary_reco_bins || cov_mat->GetNrows() != num_ordinary_reco_bins)
{
throw std::runtime_error("Bad covariance matrix dimensions passed to"
" MeasuredEvents");
}
}
// Background-subtracted data event counts in the ordinary reco bins
std::unique_ptr<TMatrixD> reco_signal_;
// Background that was subtracted from each reco bin to form the signal
// measurement
std::unique_ptr<TMatrixD> reco_bkgd_;
// Total MC+EXT prediction in each reco bin (used to estimate the covariance
// matrix on the data)
std::unique_ptr<TMatrixD> reco_mc_plus_ext_;
// Covariance matrix for the background-subtracted data
std::unique_ptr<TMatrixD> cov_matrix_;
};
using CovMatrixMap = std::map<std::string, CovMatrix>;
using NFT = NtupleFileType;
class SystematicsCalculator
{
public:
SystematicsCalculator(const std::string &input_respmat_file_name,
const std::string &syst_cfg_file_name = "",
const std::string &respmat_tdirectoryfile_name = "");
void load_universes(TDirectoryFile &total_subdir);
void build_universes(TDirectoryFile &root_tdir);
void save_universes(TDirectoryFile &out_tdf);
const Universe &cv_universe() const
{
return *rw_universes_.at(CV_UNIV_NAME).front();
}
const std::unique_ptr<Universe> &fake_data_universe() const
{
return fake_data_universe_;
}
std::unique_ptr<CovMatrixMap> get_covariances() const;
// Returns a background-subtracted measurement in all ordinary reco bins
// with the total covariance matrix and the background event counts that
// were subtracted.
// NOTE: this function assumes that the ordinary reco bins are all listed
// before any sideband reco bins
virtual MeasuredEvents get_measured_events() const;
// Utility functions to help with unfolding
inline std::unique_ptr<TMatrixD> get_cv_smearceptance_matrix() const
{
const auto &cv_univ = this->cv_universe();
return this->get_smearceptance_matrix(cv_univ);
}
inline TH2D* get_cv_hist_2d() const
{
return this->cv_universe().hist_2d_.get();
}
std::unique_ptr<TMatrixD> get_smearceptance_matrix(
const Universe &univ) const;
std::unique_ptr<TMatrixD> get_cv_true_signal() const;
std::unique_ptr<TMatrixD> get_cv_reco_signal() const;
std::unique_ptr<TMatrixD> get_cv_reco_selected() const;
// Returns the expected background in each ordinary reco bin (including
// both EXT and the central-value MC prediction for beam-correlated
// backgrounds)
// NOTE: This function assumes that all "ordinary" reco bins are listed
// before the sideband ones.
inline std::unique_ptr<TMatrixD> get_cv_ordinary_reco_bkgd() const
{
return this->get_cv_ordinary_reco_helper(true);
}
// Returns the expected signal event counts in each ordinary reco bin
// NOTE: This function assumes that all "ordinary" reco bins are listed
// before the sideband ones.
inline std::unique_ptr<TMatrixD> get_cv_ordinary_reco_signal() const
{
return this->get_cv_ordinary_reco_helper(false);
}
inline size_t get_num_signal_true_bins() const
{
return num_signal_true_bins_;
}
// protected:
// Implements both get_cv_ordinary_reco_bkgd() and
// get_cv_ordinary_reco_signal() in order to reduce code duplication. If
// return_bkgd is false (true), then the background (signal) event counts
// in each ordinary reco bin will be returned as a column vector.
std::unique_ptr<TMatrixD> get_cv_ordinary_reco_helper(
bool return_bkgd) const;
// Returns true if a given Universe represents a detector variation or
// false otherwise
bool is_detvar_universe(const Universe &univ) const;
// Overload for special cases in which the N*N covariance matrix does not
// have dimension parameter N equal to the number of reco bins
inline virtual size_t get_covariance_matrix_size() const
{
return reco_bins_.size();
}
CovMatrix make_covariance_matrix(const std::string &hist_name) const;
// Evaluate the observable described by the covariance matrices in
// a given universe and reco-space bin. NOTE: the reco bin index given
// as an argument to this function is zero-based.
virtual double evaluate_observable(const Universe &univ, int reco_bin,
int flux_universe_index = -1) const = 0;
// Evaluate a covariance matrix element for the data statistical
// uncertainty on the observable of interest for a given pair of reco bins.
// In cases where every event falls into a unique reco bin, only the
// diagonal covariance matrix elements are non-vanishing. Do the
// calculation either for BNB data (use_ext = false) or for EXT data
// (use_ext = true). NOTE: the reco bin indices consumed by this function
// are zero-based.
virtual double evaluate_data_stat_covariance(int reco_bin_a,
int reco_bin_b, bool use_ext) const = 0;
// Evaluate a covariance matrix element for the MC statistical uncertainty
// on the observable of interest (including contributions from both signal
// and background events) for a given pair of reco bins within a particular
// universe. Typically the CV universe should be used, but MC statistical
// uncertainties are tracked for all Universe objects in case they are
// needed. In cases where every event falls into a unique reco bin, only
// the diagonal covariance matrix elements are non-vanishing. NOTE: the
// reco bin indices consumed by this function are zero-based.
virtual double evaluate_mc_stat_covariance(const Universe &univ,
int reco_bin_a, int reco_bin_b) const = 0;
// Central value universe name
const std::string CV_UNIV_NAME = "weight_TunedCentralValue_UBGenie";
// Beginning of the subdirectory name for the TDirectoryFile containing the
// POT-summed histograms for the various universes across all analysis
// ntuples. The full name is formed from this prefix and the name of the
// FilePropertiesManager configuration file that is currently active.
const std::string TOTAL_SUBFOLDER_NAME_PREFIX = "total_";
// Holds reco-space histograms for data (BNB and EXT) bin counts
std::map<NFT, std::unique_ptr<TH1D>> data_hists_;
std::map<NFT, std::unique_ptr<TH2D>> data_hists2d_;
// Holds universe objects for reweightable systematics
std::map<std::string, std::vector<std::unique_ptr<Universe>>>
rw_universes_;
// Detector systematic universes (and the detVar CV) will be indexed using
// ntuple file type values. We're currently scaling one set of ntuples
// (from Run 3b) to the full dataset.
// TODO: revisit this procedure if new detVar samples become available
std::map<NFT, std::unique_ptr<Universe>> detvar_universes_;
// If we are working with fake data, then this will point to a Universe
// object containing full reco and truth information for the MC portion
// (as opposed to the EXT contribution which is added to the reco MC
// counts in the BNB "data" histogram). If we are working with real data,
// then this will be a null pointer.
std::unique_ptr<Universe> fake_data_universe_ = nullptr;
// "Alternate CV" universes for assessing unisim systematics related to
// interaction modeling
std::map<NFT, std::unique_ptr<Universe>> alt_cv_universes_;
// True bin configuration that was used to compute the universes
std::vector<TrueBin> true_bins_;
// Reco bin configuration that was used to compute the universes
std::vector<RecoBin> reco_bins_;
// Total POT exposure for the analyzed BNB data
double total_bnb_data_pot_ = 0.;
// Name of the systematics configuration file that should be used
// when computing covariance matrices
std::string syst_config_file_name_;
// Number of entries in the reco_bins_ vector that are "ordinary" bins
size_t num_ordinary_reco_bins_ = 0u;
// Number of entries in the true_bins_ vector that are "signal" bins
size_t num_signal_true_bins_ = 0u;
};
SystematicsCalculator::SystematicsCalculator(
const std::string &input_respmat_file_name,
const std::string &syst_cfg_file_name,
const std::string &respmat_tdirectoryfile_name)
: syst_config_file_name_(syst_cfg_file_name)
{
// Get access to the FilePropertiesManager singleton class
const auto &fpm = FilePropertiesManager::Instance();
// If the user didn't specify a particular systematics configuration file
// to use when calculating covariance matrices, then use the default one
if (syst_config_file_name_.empty())
{
// Look up the location of the default configuration file using the
// FilePropertiesManager to get the directory name
syst_config_file_name_ = fpm.analysis_path() + "/systcalc.conf";
}
// Open in "update" mode so that we can save POT-summed histograms
// for the combination of all analysis ntuples. Otherwise, we won't
// write to the file.
// TODO: consider adjusting this to be less dangerous
TFile in_tfile(input_respmat_file_name.c_str(), "update");
TDirectoryFile *root_tdir = nullptr;
// If we haven't been handed a root TDirectoryFile name explicitly, then
// just grab the first key from the input TFile and assume it's the right
// one to use.
std::string tdf_name = respmat_tdirectoryfile_name;
if (tdf_name.empty())
{
tdf_name = in_tfile.GetListOfKeys()->At(0)->GetName();
}
in_tfile.GetObject(tdf_name.c_str(), root_tdir);
if (!root_tdir)
{
throw std::runtime_error("Invalid root TDirectoryFile!");
}
// Construct the "total subfolder name" using the constant prefix
// and the name of the FilePropertiesManager configuration file that
// is currently active. Replace any '/' characters in the latter to
// avoid TDirectoryFile path problems.
std::string fpm_config_file = fpm.config_file_name();
// Do the '/' replacement here in the same way as is done for
// TDirectoryFile subfolders by the UniverseMaker class
fpm_config_file = ntuple_subfolder_from_file_name(fpm_config_file);
std::string total_subfolder_name = TOTAL_SUBFOLDER_NAME_PREFIX + fpm_config_file;
// Check whether a set of POT-summed histograms for each universe
// is already present in the input response matrix file. This is
// signalled by a TDirectoryFile with a name matching the string
// total_subfolder_name.
TDirectoryFile *total_subdir = nullptr;
root_tdir->GetObject(total_subfolder_name.c_str(), total_subdir);
if (!total_subdir) { // true //todo figure out why this is not working
// We couldn't find the pre-computed POT-summed universe histograms,
// so make them "on the fly" and store them in this object
this->build_universes(*root_tdir);
// Check if the directory already exists
TDirectoryFile *old_dir = (TDirectoryFile *)root_tdir->Get(total_subfolder_name.c_str());
if (old_dir)
{
// If it exists, delete it
root_tdir->rmdir(total_subfolder_name.c_str());
}
// Create a new TDirectoryFile as a subfolder to hold the POT-summed
// universe histograms
total_subdir = new TDirectoryFile(total_subfolder_name.c_str(),
"universes", "", root_tdir);
// Write the universes to the new subfolder for faster loading
// later
this->save_universes(*total_subdir);
}
else
{
// Retrieve the POT-summed universe histograms that were built
// previously
this->load_universes(*total_subdir);
}
// Also load the configuration of true and reco bins used to create the
// universes
std::string *true_bin_spec = nullptr;
std::string *reco_bin_spec = nullptr;
root_tdir->GetObject(TRUE_BIN_SPEC_NAME.c_str(), true_bin_spec);
root_tdir->GetObject(RECO_BIN_SPEC_NAME.c_str(), reco_bin_spec);
if (!true_bin_spec || !reco_bin_spec)
{
throw std::runtime_error("Failed to load bin specifications");
}
num_signal_true_bins_ = 0u;
std::istringstream iss_true(*true_bin_spec);
TrueBin temp_true_bin;
while (iss_true >> temp_true_bin)
{
if (temp_true_bin.type_ == TrueBinType::kSignalTrueBin)
{
++num_signal_true_bins_;
}
true_bins_.push_back(temp_true_bin);
}
num_ordinary_reco_bins_ = 0u;
std::istringstream iss_reco(*reco_bin_spec);
RecoBin temp_reco_bin;
while (iss_reco >> temp_reco_bin)
{
if (temp_reco_bin.type_ == RecoBinType::kOrdinaryRecoBin)
{
++num_ordinary_reco_bins_;
}
reco_bins_.push_back(temp_reco_bin);
}
}
void SystematicsCalculator::load_universes(TDirectoryFile &total_subdir)
{
const auto &fpm = FilePropertiesManager::Instance();
// TODO: reduce code duplication between this function
// and SystematicsCalculator::build_universes()
TList *universe_key_list = total_subdir.GetListOfKeys();
int num_keys = universe_key_list->GetEntries();
// Loop over the keys in the TDirectoryFile. Build a universe object
// for each key ending in "_2d" and store it in the rw_universes_
// map (for reweightable systematic universes), the detvar_universes_
// map (for detector systematic universes), or the alt_cv_universes_
// map (for alternate CV model universes)
for (int k = 0; k < num_keys; ++k)
{
// To avoid double-counting universes, search only for the 2D event
// count histograms
std::string key = universe_key_list->At(k)->GetName();
bool is_not_2d_hist = !has_ending(key, "_2d");
if (is_not_2d_hist)
continue;
// Get rid of the trailing "_2d" by deleting the last three
// characters from the current key
key.erase(key.length() - 3u);
// The last underscore separates the universe name from its
// index. Split the key into these two parts.
size_t temp_idx = key.find_last_of('_');
std::string univ_name = key.substr(0, temp_idx);
std::string univ_index_str = key.substr(temp_idx + 1u);
int univ_index = std::stoi(univ_index_str);
TH1D *hist_true = nullptr;
TH1D *hist_reco = nullptr;
TH2D *hist_2d = nullptr;
TH2D *hist_categ = nullptr;
TH2D *hist_reco2d = nullptr;
total_subdir.GetObject((key + "_true").c_str(), hist_true);
total_subdir.GetObject((key + "_reco").c_str(), hist_reco);
total_subdir.GetObject((key + "_2d").c_str(), hist_2d);
total_subdir.GetObject((key + "_categ").c_str(), hist_categ);
total_subdir.GetObject((key + "_reco2d").c_str(), hist_reco2d);
if (!hist_true || !hist_reco || !hist_2d || !hist_categ || !hist_reco2d)
{
throw std::runtime_error("Failed to retrieve histograms for the " + key + " universe");
}
// Reconstruct the Universe object from the retrieved histograms
auto temp_univ = std::make_unique<Universe>(univ_name, univ_index,
hist_true, hist_reco, hist_2d, hist_categ, hist_reco2d);
// Determine whether the current universe represents a detector
// variation or a reweightable variation. We'll use this information to
// decide where it should be stored.
NFT temp_type = fpm.string_to_ntuple_type(univ_name);
if (temp_type != NFT::kUnknown)
{
bool is_detvar = ntuple_type_is_detVar(temp_type);
bool is_altCV = ntuple_type_is_altCV(temp_type);
if (!is_detvar && !is_altCV)
throw std::runtime_error("Universe name " + univ_name + " matches a non-detVar and non-altCV file type." + " Handling of this situation is currently unimplemented.");
if (is_detvar && detvar_universes_.count(temp_type))
{
throw std::runtime_error("detVar multisims are not currently"
" supported");
}
else if (is_altCV && alt_cv_universes_.count(temp_type))
{
throw std::runtime_error("altCV multisims are not currently"
" supported");
}
// Move the detector variation Universe object into the map
if (is_detvar)
{
detvar_universes_[temp_type].reset(temp_univ.release());
}
else
{ // is_altCV
alt_cv_universes_[temp_type].reset(temp_univ.release());
}
}
// If we're working with fake data, then a single universe with a specific
// name stores all of the MC information for the "data." Save it in the
// dedicated fake data Universe object.
else if (univ_name == "FakeDataMC")
{
std::cout << "******* USING FAKE DATA *******\n";
fake_data_universe_ = std::move(temp_univ);
}
else
{
// If we've made it here, then we're working with a universe
// for a reweightable systematic variation
// If we do not already have a map entry for this kind of universe,
// then create one
if (!rw_universes_.count(univ_name))
{
rw_universes_[univ_name] = std::vector<std::unique_ptr<Universe>>();
}
// Move this universe into the map. Note that the automatic
// sorting of keys in a ROOT TDirectoryFile ensures that the
// universe ordering remains correct. We'll double-check that
// below, though, just in case.
auto &univ_vec = rw_universes_.at(univ_name);
univ_vec.emplace_back(std::move(temp_univ));
// Verify that the new universe is placed in the expected
// position in the vector. If there's a mismatch, something has
// gone wrong and the universe ordering will not be preserved.
int vec_index = univ_vec.size() - 1;
if (vec_index != univ_index)
{
throw std::runtime_error("Universe index mismatch encountered!");
}
}
} // TDirectoryFile keys (and 2D universe histograms)
constexpr std::array<NFT, 2> data_file_types = {NFT::kOnBNB,
NFT::kExtBNB};
for (const auto &file_type : data_file_types)
{
std::string data_name = fpm.ntuple_type_to_string(file_type);
std::string hist_name = data_name + "_reco";
std::string hist2d_name = data_name + "_reco2d";
TH1D *hist = nullptr;
total_subdir.GetObject(hist_name.c_str(), hist);
TH2D *hist2d = nullptr;
total_subdir.GetObject(hist2d_name.c_str(), hist2d);
if (!hist || !hist2d)
{
throw std::runtime_error("Missing data histogram for " + data_name);
}
hist->SetDirectory(nullptr);
hist2d->SetDirectory(nullptr);
if (data_hists_.count(file_type) || data_hists2d_.count(file_type))
{
throw std::runtime_error("Duplicate data histogram for " + data_name);
}
data_hists_[file_type].reset(hist);
data_hists2d_[file_type].reset(hist2d);
}
TParameter<double> *temp_pot = nullptr;
total_subdir.GetObject("total_bnb_data_pot", temp_pot);
if (!temp_pot)
{
throw std::runtime_error("Missing BNB data POT value");
}
total_bnb_data_pot_ = temp_pot->GetVal();
}
void SystematicsCalculator::build_universes(TDirectoryFile &root_tdir)
{
// Set default values of flags used to signal the presence of fake data. If
// fake data are detected, corresponding truth information will be stored and
// a check will be performed to prevent mixing real and fake data together.
bool using_fake_data = false;
bool began_checking_for_fake_data = false;
// Get some normalization factors here for easy use later.
std::map<int, double> run_to_bnb_pot_map;
std::map<int, double> run_to_bnb_trigs_map;
std::map<int, double> run_to_ext_trigs_map;
const auto &fpm = FilePropertiesManager::Instance();
const auto &data_norm_map = fpm.data_norm_map();
for (const auto &run_and_type_pair : fpm.ntuple_file_map())
{
int run = run_and_type_pair.first;
const auto &type_map = run_and_type_pair.second;
const auto &bnb_file_set = type_map.at(NFT::kOnBNB);
for (const std::string &bnb_file : bnb_file_set)
{
const auto &pot_and_trigs = data_norm_map.at(bnb_file);
if (!run_to_bnb_pot_map.count(run))
{
run_to_bnb_pot_map[run] = 0.;
run_to_bnb_trigs_map[run] = 0.;
}
run_to_bnb_pot_map.at(run) += pot_and_trigs.pot_;
run_to_bnb_trigs_map.at(run) += pot_and_trigs.trigger_count_;
} // BNB data files
// try // TODO remove try catch ?
// {
const auto &ext_file_set = type_map.at(NFT::kExtBNB);
for (const std::string &ext_file : ext_file_set)
{
const auto &pot_and_trigs = data_norm_map.at(ext_file);
if (!run_to_ext_trigs_map.count(run))
{
run_to_ext_trigs_map[run] = 0.;
}
run_to_ext_trigs_map.at(run) += pot_and_trigs.trigger_count_;
} // EXT files
// }
// catch(const std::exception& e)
// {
// std::cerr << "WARNING: EXT files not found for run " << run << std::endl;
// }
} // runs
// Now that we have the accumulated POT over all BNB data runs, sum it
// into a single number. This will be used to normalize the detVar MC
// samples.
total_bnb_data_pot_ = 0.;
for (const auto &pair : run_to_bnb_pot_map)
{
total_bnb_data_pot_ += pair.second;
}
// Loop through the ntuple files for the various run / ntuple file type
// pairs considered in the analysis. We will react differently in a run-
// and type-dependent way.
for (const auto &run_and_type_pair : fpm.ntuple_file_map())
{
int run = run_and_type_pair.first;
const auto &type_map = run_and_type_pair.second;
for (const auto &type_and_files_pair : type_map)
{
const NFT &type = type_and_files_pair.first;
const auto &file_set = type_and_files_pair.second;
bool is_detVar = ntuple_type_is_detVar(type);
bool is_altCV = ntuple_type_is_altCV(type);
bool is_reweightable_mc = ntuple_type_is_reweightable_mc(type);
bool is_mc = ntuple_type_is_mc(type);
for (const std::string &file_name : file_set)
{
std::cout << "PROCESSING universes for " << file_name << '\n';
// Default to assuming that the current ntuple file is not a fake data
// sample. If it is a data sample (i.e., if is_mc == false), then the
// value of this flag will be reconsidered below.
bool is_fake_data = false;
// Get the simulated or measured POT belonging to the current file.
// This will be used to normalize the relevant histograms
double file_pot = 0.;
if (is_mc)
{
// MC files have the simulated POT stored alongside the ntuple
// TODO: use the TDirectoryFile to handle this rather than
// pulling it out of the original ntuple file
TFile temp_mc_file(file_name.c_str(), "read");
TParameter<float> *temp_pot = nullptr;
temp_mc_file.GetObject("summed_pot", temp_pot);
if (!temp_pot)
throw std::runtime_error(
"Missing POT in MC file!");
file_pot = temp_pot->GetVal();
}
else
{
// We can ask the FilePropertiesManager for the data POT values
file_pot = fpm.data_norm_map().at(file_name).pot_;
}
// Get the TDirectoryFile name used to store histograms for the
// current ntuple file
std::string subdir_name = ntuple_subfolder_from_file_name(
file_name);
TDirectoryFile *subdir = nullptr;
root_tdir.GetObject(subdir_name.c_str(), subdir);
if (!subdir)
throw std::runtime_error(
"Missing TDirectoryFile " + subdir_name);
// For data, just add the reco-space event counts to the total,
// scaling to the beam-on triggers in the case of EXT data
if (!is_mc)
{
// When using fake data, test whether there is a weighted CV histogram present (e.g. for a closure test with MC)
auto tmp_reco_hist = type == NFT::kOnBNB ? get_object_unique_ptr<TH1D>((CV_UNIV_NAME + "_0_reco").c_str(), *subdir) : nullptr;
const auto dataContainsWeightedCV = tmp_reco_hist.get() != nullptr;
auto reco_hist = dataContainsWeightedCV ? std::move(tmp_reco_hist) : get_object_unique_ptr<TH1D>("unweighted_0_reco", *subdir);
const std::string reco_hist2d_name = (dataContainsWeightedCV ? CV_UNIV_NAME : "unweighted") + "_0_reco2d";
auto reco_hist2d = get_object_unique_ptr<TH2D>(reco_hist2d_name.c_str(), *subdir);
// auto reco_hist2d = get_object_unique_ptr<TH2D>(
// "unweighted_0_reco2d", *subdir);
// If we're working with EXT data, scale it to the corresponding
// number of triggers from the BNB data from the same run
if (type == NFT::kExtBNB)
{
double bnb_trigs = run_to_bnb_trigs_map.at(run);
double ext_trigs = run_to_ext_trigs_map.at(run);
reco_hist->Scale(bnb_trigs / ext_trigs);
reco_hist2d->Scale(bnb_trigs / ext_trigs);
}
// If we don't have a histogram in the map for this data type
// yet, just clone the existing histogram.
if (!data_hists_.count(type))
{
TH1D *temp_clone = dynamic_cast<TH1D *>(
reco_hist->Clone("temp_clone"));
temp_clone->SetStats(false);
temp_clone->SetDirectory(nullptr);
// Note: here the map entry takes ownership of the histogram
data_hists_[type].reset(temp_clone);
}
else
{
// Otherwise, just add its contribution to the existing
// histogram
data_hists_.at(type)->Add(reco_hist.get());
}
if (!data_hists2d_.count(type))
{
TH2D *temp_clone = dynamic_cast<TH2D *>(
reco_hist2d->Clone("temp_clone"));
temp_clone->SetStats(false);
temp_clone->SetDirectory(nullptr);
// Note: here the map entry takes ownership of the histogram
data_hists2d_[type].reset(temp_clone);
}
else
{
// Otherwise, just add its contribution to the existing
// histogram
data_hists2d_.at(type)->Add(reco_hist2d.get());
}
// For EXT data files (always assumed to be real data), no further
// processing is needed, so just move to the next file
if (type == NFT::kExtBNB)
continue;
// For real BNB data, we're also done. However, if we're working with
// fake data, then we also want to store the truth information for
// the current ntuple file.
// Check to see whether we have fake data or
// not by trying to retrieve the unweighted "2d" histogram (which
// stores event counts that simultaneously fall into a given true bin
// and reco bin). It will only be present for fake data ntuples.
auto fd_check_2d_hist = get_object_unique_ptr<TH2D>("unweighted_0_2d", *subdir);
is_fake_data = (fd_check_2d_hist.get() != nullptr);
// The BNB data files should either all be real data or all be fake
// data. If any mixture occurs, then this suggests that something has
// gone seriously wrong. Throw an exception to warn the user.
if (began_checking_for_fake_data)
{
if (is_fake_data != using_fake_data || (!using_fake_data && dataContainsWeightedCV))
{
throw std::runtime_error("Mixed real and fake data ntuple files"
" encountered in SystematicsCalculator::build_universes()");
}
}
else
{
using_fake_data = is_fake_data;
began_checking_for_fake_data = true;
}
// If we are working with real BNB data, then we don't need to do the
// other MC-ntuple-specific stuff below, so just move on to the next
// file
if (!is_fake_data)
continue;
} // data ntuple files
// If we've made it here, then we're working with an MC ntuple
// file. For these, all four histograms for the "unweighted"
// universe are always evaluated. Use this to determine the number
// of true and reco bins easily.
auto temp_2d_hist = get_object_unique_ptr<TH2D>(
"unweighted_0_2d", *subdir);
// NOTE: the convention of the UniverseMaker class is to use
// x as the true axis and y as the reco axis.
int num_true_bins = temp_2d_hist->GetXaxis()->GetNbins();
int num_reco_bins = temp_2d_hist->GetYaxis()->GetNbins();
// Let's handle the fake BNB data samples first.
if (is_fake_data)
{
// If this is our first fake BNB data ntuple file, then create
// the Universe object that will store the full MC information
// (truth and reco)
if (!fake_data_universe_)
{
fake_data_universe_ = std::make_unique<Universe>("FakeDataMC",
0, num_true_bins, num_reco_bins);
set_stats_and_dir(*fake_data_universe_);
} // first fake BNB data ntuple file
// Since all other histograms are scaled to the POT exposure
// of the BNB data ones, no rescaling is needed here. Just add the
// contributions of the current ntuple file's histograms to the
// fake data Universe object.
// Retrieve the histograms for the fake data universe (which
// corresponds to the "unweighted" histogram name prefix) from
// the current TDirectoryFile.
// TODO: add the capability for fake data to use event weights
// (both in the saved fake data Universe object and in the
// corresponding "data" histogram of reco event counts
const auto tmp_reco_hist = get_object_unique_ptr<TH1D>((CV_UNIV_NAME + "_0_reco").c_str(), *subdir);
const auto dataContainsWeightedCV = tmp_reco_hist.get() != nullptr;
// std::string hist_name_prefix = "unweighted_0";
std::string hist_name_prefix = (dataContainsWeightedCV ? CV_UNIV_NAME : "unweighted" ) + "_0"; // todo decide whether to revert !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
auto h_reco = get_object_unique_ptr<TH1D>(
(hist_name_prefix + "_reco"), *subdir);
auto h_true = get_object_unique_ptr<TH1D>(
(hist_name_prefix + "_true"), *subdir);
auto h_2d = get_object_unique_ptr<TH2D>(
(hist_name_prefix + "_2d"), *subdir);
auto h_categ = get_object_unique_ptr<TH2D>(
(hist_name_prefix + "_categ"), *subdir);
auto h_reco2d = get_object_unique_ptr<TH2D>(
(hist_name_prefix + "_reco2d"), *subdir);
// Add their contributions to the owned histograms for the
// current Universe object
fake_data_universe_->hist_reco_->Add(h_reco.get());
fake_data_universe_->hist_true_->Add(h_true.get());
fake_data_universe_->hist_2d_->Add(h_2d.get());
fake_data_universe_->hist_categ_->Add(h_categ.get());
fake_data_universe_->hist_reco2d_->Add(h_reco2d.get());
} // fake data sample
// Now we'll take care of the detVar and altCV samples.
else if (is_detVar || is_altCV)
{
std::string dv_univ_name = fpm.ntuple_type_to_string(type);
// Make a temporary new Universe object to store
// (POT-scaled) detVar/altCV histograms (if needed)
auto temp_univ = std::make_unique<Universe>(dv_univ_name,
0, num_true_bins, num_reco_bins);
// Temporary pointer that will allow us to treat the single-file
// detector variation samples and the multi-file alternate CV samples
// on the same footing below
Universe *temp_univ_ptr = nullptr;
// Check whether a prior altCV Universe exists in the map
bool prior_altCV = alt_cv_universes_.count(type) > 0;