15 #define XXX std::cout << " I am here: " << __FILE__ << ":" << __LINE__ << std::endl;
36 #include <TObjString.h>
48 TNamed(
name,
"notitle"), m_parentTool(this),
49 m_SetWarnings(true),m_debugging(false),m_printInfo(true),
50 m_countingMode(true),m_unrepresentedDataAction(0),m_isInitialized(false),m_lumiVectorIsLoaded(false),
51 m_dataScaleFactorX(1.),m_dataScaleFactorY(1.),
52 m_mcScaleFactorX(1.),m_mcScaleFactorY(1.),
53 m_nextPeriodNumber(1),m_ignoreFilePeriods(false),m_metadatatree(0),m_unrepDataTolerance(0.05),m_doGlobalDataWeight(false),m_lumicalcRunNumberOffset(0), m_emptyHistogram(), m_random3(), m_ignoreBadChannels(false)
55 m_random3.reset(
new TRandom3(0) );
56 m_random3->SetSeed(1);
59 m_periodList.emplace_back( -1,0,9999999,0 );
60 m_periods[ -1 ] = &( m_periodList.back() );
74 if(m_periods.find(periodNumber)==m_periods.end()) {
75 m_periodList.emplace_back( periodNumber, 0, 0,
channel );
76 m_periods[periodNumber] = &( m_periodList.back() );
78 m_periods[periodNumber]->SetDefaultChannel(
channel);
85 m_emptyHistogram.reset(
new TH2D(
"default",
"default", nbinsx,
xbins,
88 m_emptyHistogram.reset(
new TH1D(
"default",
"default", nbinsx,
xbins ) );
90 m_emptyHistogram->SetDirectory(0);
94 std::vector<double>
xbins(nbinsx+1);
95 std::vector<double>
ybins(nbinsy+1);
96 for(
int i=0;
i<nbinsx+1;
i++)
xbins[
i] = xlow +
i*(xup-xlow)/nbinsx;
98 for(
int i=0;
i<nbinsy+1;
i++)
ybins[
i] = ylow +
i*(yup-ylow)/nbinsy;
99 return SetBinning(nbinsx,&
xbins[0],nbinsy,&
ybins[0]);
103 m_emptyHistogram.reset(
dynamic_cast< TH1*
>(
hist->Clone(
"default" ) ) );
104 if (m_emptyHistogram)
105 m_emptyHistogram->SetDirectory(0);
110 if(m_parentTool !=
this)
return m_parentTool->GetDefaultChannel(mcRunNumber);
111 return m_periods[mcRunNumber]->defaultChannel;
116 if(!m_isInitialized) {
118 Info(
"GetIntegratedLumi",
"Initializing the subtool..");
122 if(!m_lumiVectorIsLoaded) {
123 Error(
"GetIntegratedLumi",
"No UNPRESCALED (Trigger=None) Lumicalc file loaded, so cannot get integrated lumi, returning 0");
126 if(trigger==
"" || trigger==
"None")
return GetSumOfEventWeights(-1)/1E6;
128 if(m_triggerObjs.find(trigger)==m_triggerObjs.end()) {
129 CalculatePrescaledLuminosityHistograms(trigger);
132 auto&
h = m_triggerObjs[trigger]->triggerHists[-1][m_triggerObjs[trigger]->getBits(
this)];
134 return h->Integral(0,
h->GetNbinsX()+1)/1E6;
140 if(!m_isInitialized) {
142 Info(
"GetIntegratedLumi",
"Initializing the subtool..");
149 if(
run >=
start &&
run <=
end) total += m_runs[
run].inputHists[
"None"]->GetSumOfWeights();
155 if(!m_isInitialized) {
157 Info(
"GetIntegratedLumi",
"Initializing the subtool..");
161 if(m_runs.find(
runNumber)==m_runs.end())
return 0.;
164 if(
run.lumiByLbn.find(
lb)==
run.lumiByLbn.end())
return 0.;
165 return run.lumiByLbn[
lb].first*1
E-6;
169 if(!m_isInitialized) {
171 Info(
"GetLumiBlockMu",
"Initializing the subtool..");
175 if(m_runs.find(
runNumber)==m_runs.end())
return -1.0;
178 if(
run.lumiByLbn.find(
lb)==
run.lumiByLbn.end())
return -1.0;
179 return run.lumiByLbn[
lb].second;
183 if(!m_isInitialized) {
185 Info(
"GetIntegratedLumiFraction",
"Initializing the subtool..");
190 if(!m_lumiVectorIsLoaded) {
191 Error(
"GetIntegratedLumiFraction",
"No UNPRESCALED (Trigger=None) Lumicalc file loaded, so no lumi fraction possible, returning 0");
195 double total = m_periods[periodNumber]->sumOfWeights[-1];
199 if(
run >=
start &&
run <=
end) numer += m_runs[
run].inputHists[
"None"]->GetSumOfWeights();
201 return numer / total;
205 if(!m_isInitialized) {
207 Info(
"GetIntegratedLumiFraction",
"Initializing the subtool..");
211 if(!m_lumiVectorIsLoaded) {
212 Error(
"GetIntegratedLumiFraction",
"No UNPRESCALED (Trigger=None) Lumicalc file loaded, so no lumi fraction possible, returning 0");
216 if(!m_emptyHistogram) { Error(
"GetIntegratedLumiFraction",
"Cannot do this without a lumicalc file!");
return 0; }
217 Int_t muBin = m_emptyHistogram->FindFixBin(
mu);
222 double total = m_triggerObjs[
"None"]->triggerHists[periodNumber][0]->GetBinContent(muBin);
226 if(
run >=
start &&
run <=
end) numer += m_runs[
run].muDist->GetBinContent(muBin);
229 return numer / total;
235 if(configName==
"MC11a") {
236 AddPeriod(180164, 177986,180481);
237 AddPeriod(183003, 180614,184169);
238 AddPeriod(185649, 185353,186934);
239 AddPeriod(185761, 186935,191933);
240 SetUniformBinning(100,0,50);
242 Info(
"UsePeriodConfig",
"Using MC11a Period configuration");
245 }
else if(configName==
"MC11b" || configName==
"MC11c") {
246 AddPeriod(180164, 177986, 180481);
247 AddPeriod(183003, 180614, 184169);
248 AddPeriod(186169, 185353, 187815);
249 AddPeriod(189751, 188902, 191933);
250 SetUniformBinning(100,0,50);
252 Info(
"UsePeriodConfig",
"Using MC11b/c Period configuration");
255 }
else if(configName==
"MC12a") {
256 AddPeriod(195847,200804,216432);
259 if(m_emptyHistogram && (m_emptyHistogram->GetNbinsX()!=50 || fabs(m_emptyHistogram->GetXaxis()->GetBinLowEdge(1)+0.5)>0.01|| fabs(m_emptyHistogram->GetXaxis()->GetBinUpEdge(50)-49.5)>0.01) ) {
260 Error(
"UsePeriodConfig",
"Cannot use MC12a, an incompatible config has already been set up");
261 throw std::runtime_error(
"Throwing 13: Cannot use MC14, an incompatible config has already been set up");
265 SetUniformBinning(50,-0.5,49.5);
267 Info(
"UsePeriodConfig",
"Using MC12a Period configuration");
270 }
else if(configName==
"MC12b") {
271 AddPeriod(195848,200804,216432);
274 if(m_emptyHistogram && (m_emptyHistogram->GetNbinsX()!=50 || fabs(m_emptyHistogram->GetXaxis()->GetBinLowEdge(1)+0.5)>0.01|| fabs(m_emptyHistogram->GetXaxis()->GetBinUpEdge(50)-49.5)>0.01) ) {
275 Error(
"UsePeriodConfig",
"Cannot use MC12b, an incompatible config has already been set up");
276 throw std::runtime_error(
"Throwing 13: Cannot use MC14, an incompatible config has already been set up");
280 SetUniformBinning(50,-0.5,49.5);
282 Info(
"UsePeriodConfig",
"Using MC12b Period configuration");
285 }
else if(configName==
"MC12ab") {
286 AddPeriod(195847,200804,216432);
287 AddPeriod(195848,200804,216432);
289 if(m_emptyHistogram && (m_emptyHistogram->GetNbinsX()!=50 || fabs(m_emptyHistogram->GetXaxis()->GetBinLowEdge(1)+0.5)>0.01|| fabs(m_emptyHistogram->GetXaxis()->GetBinUpEdge(50)-49.5)>0.01) ) {
290 Error(
"UsePeriodConfig",
"Cannot use MC12ab, an incompatible config has already been set up");
291 throw std::runtime_error(
"Throwing 13: Cannot use MC14, an incompatible config has already been set up");
296 SetUniformBinning(50,-0.5,49.5);
298 Info(
"UsePeriodConfig",
"Using MC12ab Period configuration");
301 }
else if(configName==
"MC14_8TeV") {
302 AddPeriod(212272,200804,216432);
303 if(m_emptyHistogram && (m_emptyHistogram->GetNbinsX()!=50 || fabs(m_emptyHistogram->GetXaxis()->GetBinLowEdge(1)+0.5)>0.01 || fabs(m_emptyHistogram->GetXaxis()->GetBinUpEdge(50)-49.5)>0.01) ) {
304 Error(
"UsePeriodConfig",
"Cannot use MC14_8TeV, an incompatible config has already been set up");
305 throw std::runtime_error(
"Throwing 13: Cannot use MC14_8TeV, an incompatible config has already been set up");
308 SetUniformBinning(50,-0.5,49.5);
310 Info(
"UsePeriodConfig",
"Using MC14_8TeV Period configuration");
313 }
else if(configName==
"MC14_13TeV") {
314 AddPeriod(222222,222222,999999);
315 if(m_emptyHistogram && (m_emptyHistogram->GetNbinsX()!=100 || fabs(m_emptyHistogram->GetXaxis()->GetBinLowEdge(1)+0.5)>0.01|| fabs(m_emptyHistogram->GetXaxis()->GetBinUpEdge(100)-99.5)>0.01) ) {
316 Error(
"UsePeriodConfig",
"Cannot use MC14_13TeV, an incompatible config has already been set up");
317 throw std::runtime_error(
"Throwing 13: Cannot use MC14_13TeV, an incompatible config has already been set up");
320 SetUniformBinning(100,-0.5,99.5);
322 Info(
"UsePeriodConfig",
"Using MC14_13TeV Period configuration");
325 }
else if(configName==
"MC15") {
326 AddPeriod(222510,222222,999999);
327 AddPeriod(222525,222222,999999);
328 AddPeriod(222526,222222,999999);
329 AddPeriod(284500,222222,999999);
330 AddPeriod(295000,222222,999999);
331 if(m_emptyHistogram && (m_emptyHistogram->GetNbinsX()!=100 || fabs(m_emptyHistogram->GetXaxis()->GetBinLowEdge(1))>0.01 || fabs(m_emptyHistogram->GetXaxis()->GetBinUpEdge(100)-100.)>0.01) ) {
332 Error(
"UsePeriodConfig",
"Cannot use MC15, an incompatible config has already been set up");
333 throw std::runtime_error(
"Throwing 13: Cannot use MC15, an incompatible config has already been set up");
336 SetUniformBinning(100,0,100);
338 Info(
"UsePeriodConfig",
"Using MC15 Period configuration");
341 }
else if(configName==
"Run2") {
342 m_autoRunStart = 222222; m_autoRunEnd = 999999;
343 if(m_emptyHistogram && (m_emptyHistogram->GetNbinsX()!=100 || fabs(m_emptyHistogram->GetXaxis()->GetBinLowEdge(1))>0.01 || fabs(m_emptyHistogram->GetXaxis()->GetBinUpEdge(100)-100.)>0.01) ) {
344 Error(
"UsePeriodConfig",
"Cannot use open Run2, an incompatible config has already been set up");
345 throw std::runtime_error(
"Throwing 13: Cannot use Run2 config, an incompatible config has already been set up");
348 SetUniformBinning(100,0,100);
350 Info(
"UsePeriodConfig",
"Using Run2 Period configuration, which assumes period assignment of 222222 to 999999");
353 }
else if(configName==
"MC16") {
356 SetUniformBinning(100,0,100);
358 Info(
"UsePeriodConfig",
"Using MC16 Period configuration");
362 Error(
"UsePeriodConfig",
"Unrecognized period config");
371 if(m_isInitialized && !m_countingMode) {
372 Error(
"AddPeriod",
"You cannot AddPeriod after initializing the tool, except when in config file generating mode. Reorder your code!");
373 throw std::runtime_error(
"Throwing 1: You cannot AddPeriod after initializing the tool, except when in config file generating mode. Reorder your code!");
376 if(m_periods.find(periodNumber)==m_periods.end()) {
377 m_periodList.emplace_back( periodNumber,
start,
end,
378 GetDefaultChannel( -1 ) );
379 m_periods[periodNumber] = &( m_periodList.back() );
384 Period*
p = m_periods[periodNumber];
386 if(
p->subPeriods.size() == 0 &&
p->start==0 &&
p->end==0) {
p->start=
start;
p->end=
end;
return periodNumber; }
389 if(
p->start==
start &&
p->end==
end)
return periodNumber;
390 for(
auto pp :
p->subPeriods) {
391 if(pp->start==
start && pp->end==
end)
return pp->id;
395 if(m_isInitialized && m_countingMode) {
396 Error(
"AddPeriod",
"You cannot have subperiods when in Config File Generating mode");
397 throw std::runtime_error(
"Throwing 44: In Config File Generating mode, but detected subperiods in the period definition. This is not allowed.");
403 if(
p->subPeriods.size()==0) {
404 while(m_periods.find(m_nextPeriodNumber) != m_periods.end()) m_nextPeriodNumber++;
405 m_periodList.emplace_back( m_nextPeriodNumber,
p->start,
p->end,
407 m_periods[m_nextPeriodNumber] = &( m_periodList.back() );
408 p->subPeriods.push_back(m_periods[m_nextPeriodNumber]);
409 p->start = 0;
p->end=0;
412 while(m_periods.find(m_nextPeriodNumber) != m_periods.end()) m_nextPeriodNumber++;
413 m_periodList.emplace_back( m_nextPeriodNumber,
start,
end,
415 m_periods[m_nextPeriodNumber] = &( m_periodList.back() );
416 p->subPeriods.push_back(m_periods[m_nextPeriodNumber]);
418 return m_nextPeriodNumber;
425 for(
auto period : m_periods) {
426 if(
period.second->id==-1)
continue;
434 std::unique_ptr< TH1 >
438 if(channelNumber>=0) {
439 s +=
"_chan";
s += channelNumber;
445 if(!m_emptyHistogram) {
446 Error(
"CloneEmptyHistogram",
"There is no binning info - use SetBinning/SetUniformBinning or load a prw config file (This usually means you need to call AddConfigFile BEFORE AddLumiCalcFile)");
447 throw std::runtime_error(
"Throwing 47: There is no binning info - use SetBinning/SetUniformBinning or load a prw config file (This usually means you need to call AddConfigFile BEFORE AddLumiCalcFile)");
450 std::unique_ptr< TH1 >
out(
dynamic_cast<TH1*
>(m_emptyHistogram->Clone(
s)) );
453 out->SetDirectory(0);
462 TTree inTree(
"in",
"in");
464 TTree outTree(
"ChannelMetaData",
"ChannelMetaData");
466 std::map<TString, Double_t>
data;
467 TObjArray *leaves = inTree.GetListOfLeaves();
468 if(leaves==0) {Error(
"GenerateMetaDataFile",
"No leaves");
return -1; }
469 for(Int_t
i=0;
i<leaves->GetEntries();++
i) {
470 TLeaf *leaf = (TLeaf *)leaves->At(
i);
472 TBranch *
branch = leaf->GetBranch();
473 if(strcmp(
branch->GetName(),channelBranchName)==0) {
475 if(strcmp(leaf->GetTypeName(),
"Int_t")!=0) {
476 Error(
"GenerateMetaDataFile",
"Channel Branch must be type Int_t");
return -1;
479 outTree.Branch(channelBranchName,&
chanNum);
480 }
else if(strcmp(leaf->GetTypeName(),
"Double_t")!=0) {
481 Warning(
"GenerateMetaDataFile",
"Cannot read non-double branch: %s",
branch->GetName());
489 for(Int_t
i=0;
i<inTree.GetEntries();++
i) {
501 Info(
"GenerateMetaDataFile",
"Succesfully Generated File %s",
outName.Data());
515 Error(
"AddMetaDataFile",
"Could not open file: %s",
fileName.Data());
516 throw std::runtime_error(
"Throwing 6");
521 Error(
"AddMetaDataFile",
"%s is not a valid metadata file. Should have a ChannelMetaData TTree",
fileName.Data());
522 throw std::runtime_error(
"Throwing 7");
529 tmp =
new TTree(
"ChannelMetaData",
"ChannelMetaData");
533 std::map<TString, Double_t>
data;
534 TObjArray *leaves =
tmp->GetListOfLeaves();
535 if(leaves==0) {Error(
"AddMetaDataFile",
"No leaves");
return -1; }
536 for(Int_t
i=0;
i<leaves->GetEntries();++
i) {
537 TLeaf *leaf = (TLeaf *)leaves->At(
i);
539 TBranch *
branch = leaf->GetBranch();
540 if(strcmp(
branch->GetName(),channelBranchName)==0) {
542 if(strcmp(leaf->GetTypeName(),
"Int_t")!=0) {
543 Error(
"AddMetaDataFile",
"Channel Branch must be type Int_t");
544 throw std::runtime_error(
"Throwing 7");
547 }
else if(strcmp(leaf->GetTypeName(),
"Double_t")!=0) {
548 Warning(
"AddMetaDataFile",
"Cannot read non-double branch: %s",
branch->GetName());
555 for(Int_t
i=0;
i<
tmp->GetEntries();++
i) {
558 if(m_metadata.find(
it->first)!=m_metadata.end()&&m_metadata[
it->first].find(
chanNum)!=m_metadata[
it->first].end() && m_metadata[
it->first][
chanNum]!=
it->second) {
559 Warning(
"AddMetaDataFile",
"Overriding metadata [%s,%d]. %f becomes %f",(
it->first).Data(),
chanNum,m_metadata[
it->first][
chanNum],
it->second);
575 if(m_metadatatree)
delete m_metadatatree;
576 m_metadatatree =
new TTree(TString(this->GetName())+
"MetaData",TString(this->GetName())+
"MetaData");
577 m_metadatatree->SetDirectory(0);
579 m_metadatatree->Branch(
"mc_channel_number",&
channel);
580 std::map<TString,Double_t>
data;
583 for(std::map<TString,std::map<Int_t,Double_t> >::
iterator it=m_metadata.begin();
it!=m_metadata.end();++
it) {
587 const auto &[
ptr, inserted ] =
data.try_emplace(
it->first, 0.);
589 m_metadatatree->Branch(
it->first,&(
data[
it->first]));
593 data[
"NumberOfEvents"]=0.;
594 m_metadatatree->Branch(
"NumberOfEvents",&(
data[
"NumberOfEvents"]));
595 data[
"SumOfEventWeights"]=0.;
596 m_metadatatree->Branch(
"SumOfEventWeights",&(
data[
"SumOfEventWeights"]));
598 auto& myMap = m_periods[-1]->sumOfWeights;
607 if(it2->first==
"NumberOfEvents") {
609 if(myMap.find(
channel)==myMap.end()) {
611 Warning(
"GetMetaDataTree",
"Channel %d does not have MetaData %s",
it->first,(it2->first).Data());
613 data[it2->first]=m_periods[-1]->numberOfEntries[
channel];
615 }
else if(it2->first==
"SumOfEventWeights") {
617 auto& myMap2 = m_periods[-1]->sumOfWeights;
618 if(myMap2.find(
channel)==myMap2.end()) {
620 Warning(
"GetMetaDataTree",
"Channel %d does not have MetaData %s",
it->first,(it2->first).Data());
622 data[it2->first]=m_periods[-1]->sumOfWeights[
channel];
625 auto& myMap2 = m_metadata[it2->first];
626 if(myMap2.find(
channel)==myMap2.end()) {
629 Warning(
"GetMetaDataTree",
"Channel %d does not have MetaData %s",
it->first,(it2->first).Data());
635 m_metadatatree->Fill();
638 m_metadatatree->BuildIndex(
"mc_channel_number");
639 m_metadatatree->ResetBranchAddresses();
641 return m_metadatatree;
652 Int_t
channel = 0; UInt_t runNbr = 0;
653 auto pStarts = std::make_unique< std::vector< UInt_t > >();
654 auto pStartsPtr = pStarts.get();
655 auto pEnds = std::make_unique< std::vector< UInt_t > >();
656 auto pEndsPtr = pEnds.get();
658 Char_t customName[150];
659 Bool_t isDefaultForRunNumber(
false);
bool hasDefaultsBranch=
false;
660 if(strcmp(
tree->GetName(),
"MCPileupReweighting")==0) {strcpy(customName,
"pileup");
isMC=
true;}
662 if(
tree->SetBranchAddress(
"CustomName",&customName)!=0) {
663 Error(
"AddDistributionTree",
"Could not find CustomName branch in TTree");
throw std::runtime_error(
"Throwing 18");
666 if(strcmp(
tree->GetName(),
"DataCustomReweighting")==0) {
channel=-1;
isMC=
false;}
668 if(
tree->SetBranchAddress(
"Channel",&
channel)!=0) {
669 Error(
"AddDistributionTree",
"Could not find Channel branch in TTree");
throw std::runtime_error(
"Throwing 18");
672 if(
tree->SetBranchAddress(
"RunNumber",&runNbr)!=0) {
673 Error(
"AddDistributionTree",
"Could not find RunNumber branch in TTree");
throw std::runtime_error(
"Throwing 18");
676 if(
tree->SetBranchAddress(
"PeriodStarts",&pStartsPtr)!=0) {
677 Error(
"AddDistributionTree",
"Could not find PeriodStarts branch in TTree");
throw std::runtime_error(
"Throwing 18");
679 if(
tree->SetBranchAddress(
"PeriodEnds",&pEndsPtr)!=0) {
680 Error(
"AddDistributionTree",
"Could not find PeriodEnds branch in TTree");
throw std::runtime_error(
"Throwing 18");
682 if(
tree->FindBranch(
"IsDefaultForRunNumber")!=0) {
683 tree->SetBranchAddress(
"IsDefaultForRunNumber",&isDefaultForRunNumber);
684 hasDefaultsBranch=
true;
689 Error(
"AddDistributionTree",
"Could not find HistName branch in TTree");
throw std::runtime_error(
"Throwing 18");
691 long n =
tree->GetEntries();
692 std::map<TString,bool> loadedHistos;
693 for(
long i=0;
i<
n;
i++) {
696 TString weightName(customName);
697 const auto &[
ptr, inserted] = loadedHistos.try_emplace(sHistName,
true);
700 if(( (!m_ignoreFilePeriods) || m_periods.find(runNbr)==m_periods.end()) &&
isMC) {
702 for(
unsigned int j=0;j<pStarts->size();j++) {
703 unsigned int start = pStarts->at(j);
704 unsigned int end = pEnds->at(j);
709 TH1 *
histo = (TH1*)
file->Get( sHistName );
712 Error(
"AddDistributionTree",
"Unable to find the histogram %s in the File %s",sHistName.Data(),
file->GetName());
713 throw std::runtime_error(
"Throwing 21");
720 if(hasDefaultsBranch) {
721 if(isDefaultForRunNumber && m_periods.find(runNbr)!=m_periods.end()) m_periods[runNbr]->defaultChannel=
channel;
732 if(m_isInitialized) {
733 Error(
"AddDistribution",
"You cannot AddDistribution after initializing the tool. Reorder your code!");
734 throw std::runtime_error(
"Throwing 5: You cannot AddLumiCalcFile after initializing the tool. Reorder your code!");
737 if(channelNumber>=0 && !m_periods[
runNumber]) {
738 Error(
"AddDistribution",
"Unrecognised periodNumber: %d .. please use AddPeriod to define a period",
runNumber);
739 throw std::runtime_error(
"Throwing 6: Unrecognised periodNumber. Please use AddPeriod to define a period");
745 for(
auto&
period : m_periods) {
746 if(
period.first<0)
continue;
748 if(
period.second->inputHists.find(channelNumber)!=
period.second->inputHists.end()) {
749 TString myMsg =
TString::Format(
"Attempt to add distribution for channel %d to period %d, but this channels already has period %d defined.\nThis is indicative of use of incompatible PRW config files, please check your config files for multiple periods/runNumbers for the same channel.",channelNumber,
runNumber,
period.first);
750 Error(
"AddDistribution",
"%s",myMsg.Data());
751 throw std::runtime_error(myMsg.Data());
757 auto& inputHist = (channelNumber<0) ? m_runs[
runNumber].inputHists[
"None"] : m_periods[
runNumber]->inputHists[channelNumber];
761 if(!m_emptyHistogram) {
763 if(strcmp(
hist->IsA()->GetName(),
"TH1D")==0 || strcmp(
hist->IsA()->GetName(),
"TH2D")==0) {
764 m_emptyHistogram.reset(
dynamic_cast<TH1*
>(
hist->Clone(
"default")) );
767 if(
hist->GetDimension()==1) {
768 std::vector<Double_t>
binsX;
769 for(
int i=0;
i<=
hist->GetNbinsX();
i++)
binsX.push_back(
hist->GetXaxis()->GetBinLowEdge(
i+1));
771 m_emptyHistogram.reset(
dynamic_cast<TH1*
>(
tmpHist.Clone(
"default")) );
772 }
else if(
hist->GetDimension()==2) {
773 std::vector<Double_t>
binsX;std::vector<Double_t>
binsY;
774 for(
int i=0;
i<=
hist->GetNbinsX();
i++)
binsX.push_back(
hist->GetXaxis()->GetBinLowEdge(
i+1));
775 for(
int i=0;
i<=
hist->GetNbinsY();
i++)
binsY.push_back(
hist->GetYaxis()->GetBinLowEdge(
i+1));
777 m_emptyHistogram.reset(
dynamic_cast<TH1*
>(
tmpHist.Clone(
"default")) );
779 Error(
"AddDistribution",
"Unknown input histogram dimensionality: %d",
hist->GetDimension());
780 throw std::runtime_error(
"Throwing 98");
783 if (m_emptyHistogram)
785 m_emptyHistogram->Reset();m_emptyHistogram->SetEntries(0);m_emptyHistogram->SetDirectory(0);
788 inputHist = CloneEmptyHistogram(
runNumber,channelNumber);
794 Double_t numEntries = inputHist->GetEntries();
797 if(channelNumber<0) {
798 m_runs[
runNumber].nominalFromHists =
true;
800 tmpHist.reset(
static_cast<TH1*
>(inputHist->Clone(
"tmpHist")) );
803 for(biny=1; biny<=
tmpHist->GetNbinsY(); biny++) {
804 for(binx=1; binx<=
tmpHist->GetNbinsX(); binx++) {
806 Double_t
x =
tmpHist->GetXaxis()->GetBinCenter(binx)/m_dataScaleFactorX;
807 Double_t
y =
tmpHist->GetYaxis()->GetBinCenter(biny)/m_dataScaleFactorY;
808 if(
tmpHist->GetDimension()==1){
821 for(biny=1; biny<=
hist->GetNbinsY(); biny++) {
822 for(binx=1; binx<=
hist->GetNbinsX(); binx++) {
825 Double_t
x =
hist->GetXaxis()->GetBinCenter(binx);
826 Double_t
y =
hist->GetYaxis()->GetBinCenter(biny);
828 if(channelNumber>=0) {
x *= m_mcScaleFactorX;
y *= m_mcScaleFactorY;}
830 Int_t inBin = inputHist->FindFixBin(
x,
y);
831 Double_t inValue = inputHist->GetBinContent(inBin);
832 inputHist->SetBinContent(inBin,inValue+
value);
838 inputHist->SetEntries(numEntries+
hist->GetEntries());
841 m_countingMode=
false;
849 if(m_isInitialized) {
850 Error(
"AddLumiCalcFile",
"You cannot AddLumiCalcFile after initializing the tool. Reorder your code!");
851 throw std::runtime_error(
"Throwing 5: You cannot AddLumiCalcFile after initializing the tool. Reorder your code!");
857 Error(
"AddConfigFile",
"Could not open file: %s",
fileName.Data());
858 std::string toThrow =
"Throwing 6: Could not open file: "; toThrow +=
fileName.Data();
859 throw std::runtime_error(toThrow);
862 TTree *
tmp = (TTree*)
rootFile->Get(
"LumiMetaData" );
864 m_lumicalcFiles[trigger].push_back(
fileName);
865 if(trigger==
"None") {
867 Info(
"AddLumiCalcFile",
"Adding LumiMetaData (scale factor=%f)...",m_dataScaleFactorX);
871 UInt_t runNbr=0;Float_t intLumi=0;UInt_t lbn=0;TBranch *b_runNbr=0;TBranch *b_intLumi=0;TBranch *b_lbn=0;
872 Float_t
mu=0.; TBranch *b_mu=0;
873 if(
tmp->SetBranchAddress(
"RunNbr",&runNbr,&b_runNbr)!=0) {
874 Error(
"AddLumiCalcFile",
"Could not find RunNbr branch in Data TTree");
throw std::runtime_error(
"Could not find RunNbr branch in Data TTree");
876 if(
tmp->SetBranchAddress(
"AvergeInteractionPerXing",&
mu,&b_mu)!=0) {
877 Error(
"AddLumiCalcFile",
"Could not find AvergeInteractionPerXing branch in Data TTree");
throw std::runtime_error(
"Could not find AvergeInteractionPerXing branch in Data TTree");
879 if(
tmp->SetBranchAddress(
"IntLumi",&intLumi,&b_intLumi)!=0) {
880 Error(
"AddLumiCalcFile",
"Could not find IntLumi branch in Data TTree");
throw std::runtime_error(
"Could not find IntLumi branch in Data TTree");
882 if(
tmp->SetBranchAddress(
"LBStart",&lbn,&b_lbn)!=0) {
883 Error(
"AddLumiCalcFile",
"Could not find LBStart branch in Data TTree");
throw std::runtime_error(
"Could not find LBStart branch in Data TTree");
888 b_runNbr->GetEntry(
i);b_intLumi->GetEntry(
i);b_mu->GetEntry(
i);
889 runNbr += m_lumicalcRunNumberOffset;
894 if(!m_parentTool->runLbnOK(runNbr,lbn))
continue;
896 Run&
r = m_runs[runNbr];
897 if(trigger==
"None") {
898 r.lumiByLbn[lbn].first += intLumi;
899 r.lumiByLbn[lbn].second =
mu;
900 if(
r.nominalFromHists)
continue;
904 mu *= m_dataScaleFactorX;
908 std::unique_ptr<TH1>& histptr =
r.inputHists[trigger];
910 histptr = CloneEmptyHistogram(runNbr,-1);
912 histptr->Fill(
mu,intLumi);
914 m_countingMode=
false;
915 m_lumiVectorIsLoaded=
true;
918 Info(
"AddLumiCalcFile",
"Adding LumiMetaData for DataWeight (trigger=%s) (scale factor=%f)...",trigger.Data(),m_dataScaleFactorX);
923 Error(
"AddLumiCalcFile",
"No LumiMetaData found in file %s. not a LumiCalcFile?",
fileName.Data());
924 throw std::runtime_error(
"No LumiMetaData found in file, not a LumiCalcFile?");
941 if(m_isInitialized) {
942 Error(
"AddConfigFile",
"You cannot AddConfigFile after initializing the tool. Reorder your code!");
943 throw std::runtime_error(
"Throwing 5: You cannot AddConfigFile after initializing the tool. Reorder your code!");
950 Error(
"AddConfigFile",
"Could not open file: %s",
fileName.Data());
951 std::string toThrow =
"Throwing 6: Could not open file: "; toThrow +=
fileName.Data();
952 throw std::runtime_error(toThrow);
955 TTree *
tmp = (TTree*)
rootFile->Get( std::string(m_prwFilesPathPrefix+
"MCPileupReweighting").c_str() );
959 m_countingMode=
false;
961 tmp = 0;
tmp = (TTree*)
rootFile->Get( std::string(m_prwFilesPathPrefix+
"MCCustomReweighting").c_str() );
965 m_countingMode=
false;
967 tmp = 0;
tmp = (TTree*)
rootFile->Get( std::string(m_prwFilesPathPrefix+
"DataCustomReweighting").c_str() );
971 m_countingMode=
false;
973 tmp=0;
tmp = (TTree*)
rootFile->Get( std::string(m_prwFilesPathPrefix+
"PileupReweighting/MCPileupReweighting").c_str() );
977 m_countingMode=
false;
979 tmp = 0;
tmp = (TTree*)
rootFile->Get( std::string(m_prwFilesPathPrefix+
"PileupReweighting/MCCustomReweighting").c_str() );
983 m_countingMode=
false;
985 tmp = 0;
tmp = (TTree*)
rootFile->Get( std::string(m_prwFilesPathPrefix+
"PileupReweighting/DataCustomReweighting").c_str() );
989 m_countingMode=
false;
1002 if(m_isInitialized) {
1003 Error(
"RemoveChannel",
"You cannot RemoveChannel after initializing the tool. Reorder your code!");
1004 throw std::runtime_error(
"Throwing 5: You cannot RemoveChannel after initializing the tool. Reorder your code!");
1008 for(
auto&
period : m_periods) {
1009 auto itr =
period.second->inputHists.begin();
1010 while(itr !=
period.second->inputHists.end()) {
1011 if(itr->first!=
chanNum) ++itr;
1014 itr =
period.second->inputHists.erase(itr);
1032 if(m_countingMode) {
1034 Info(
"Initialize",
"In Config File Generating mode. Remember to call WriteToFile!");
1037 for(
auto period : m_periods) {
1038 if(
period.second->subPeriods.size()!=0) {
1039 Error(
"Initialize",
"You cannot have subperiods when in Config File Generating mode");
1040 throw std::runtime_error(
"Throwing 44: In Config File Generating mode, but detected subperiods in the period definition. This is not allowed.");
1045 m_isInitialized=
true;
1051 std::map<int,std::map<int,bool>> trackWarnings;
1053 double totalData(0);
1055 for(
auto&
run : m_runs) {
1056 if(
run.second.inputHists.find(
"None") ==
run.second.inputHists.end())
continue;
1057 TH1*
hist =
run.second.inputHists[
"None"].get();
1058 Int_t
bin,binx,biny;
1059 for(biny=1; biny<=
hist->GetNbinsY(); biny++) {
1060 for(binx=1; binx<=
hist->GetNbinsX(); binx++) {
1061 bin =
hist->GetBin(binx,biny);
1064 if(
value==0.)
continue;
1065 bool isUnrep(
false);
1066 std::map<Int_t, bool> doneChannels;
1067 for(
auto&
period : m_periods) {
1069 if(
period.first == -1)
continue;
1070 if(!
period.second->contains(
run.first))
continue;
1071 for(
auto& inHist : m_periods[-1]->inputHists) {
1072 if(inHist.first<0)
continue;
1073 if(doneChannels[inHist.first])
continue;
1074 if(
period.second->inputHists.find(inHist.first)==
period.second->inputHists.end()) {
1076 isUnrep=
true;doneChannels[inHist.first]=
true;
1077 unrepDataByChannel[inHist.first] +=
value;
1078 if(!trackWarnings[inHist.first][
period.first]) {
1079 trackWarnings[inHist.first][
period.first]=
true;
1080 Warning(
"Initialize",
"Channel %d has no configuration for period %d -- this is symptomatic of you trying to reweight an MC campaign to data not intended for that campaign (e.g. MC16a with 2017 data)",inHist.first,
period.first);
1082 }
else if(
period.second->inputHists[inHist.first]->GetBinContent(
bin)==0) {
1084 isUnrep=
true;doneChannels[inHist.first]=
true;
1085 unrepDataByChannel[inHist.first] +=
value;
1089 if(isUnrep) unrepDataByChannel[-1] +=
value;
1094 if(m_ignoreBadChannels && unrepDataByChannel[-1] && totalData && (unrepDataByChannel[-1]/totalData)>m_unrepDataTolerance) {
1095 Warning(
"Initialize",
"There is %f%% unrepresented data and 'IgnoreBadChannels' property is set to true. Will start ignoring channels until this is below the tolerance (%f%%)", 100.*(unrepDataByChannel[-1]/totalData),100.*m_unrepDataTolerance);
1097 while( (unrepDataByChannel[-1]/totalData)>m_unrepDataTolerance ) {
1098 int worstChannel = -1;
1099 double worstFraction = 0;
1100 for(
auto&
channel : unrepDataByChannel) {
1102 if(
channel.second/totalData > worstFraction) { worstChannel=
channel.first; worstFraction =
channel.second/totalData; }
1104 if(worstChannel==-1) {
1105 Error(
"Initialize",
"Run out of channels to remove. All your channels are bad ... oh dear oh dear oh dear. Please a better PRW config file");
1106 throw std::runtime_error(
"Throwing exception 333: Run out of channels to remove. All your channels are bad ... oh dear oh dear oh dear. Please a better PRW config file");
1109 Warning(
"Initialize",
"Ignoring channel %d, which has %f%% unrepresented data (%f%% of the total unrep data)",worstChannel,100.*unrepDataByChannel[worstChannel]/totalData,100.*unrepDataByChannel[worstChannel]/unrepDataByChannel[-1]);
1111 RemoveChannel(worstChannel);
1112 unrepDataByChannel.erase(unrepDataByChannel.find(worstChannel));
1115 unrepDataByChannel[-1] = 0;
1116 for(
auto&
run : m_runs) {
1117 if(
run.second.inputHists.find(
"None") ==
run.second.inputHists.end())
continue;
1118 TH1*
hist =
run.second.inputHists[
"None"].get();
1119 Int_t
bin,binx,biny;
1120 for(biny=1; biny<=
hist->GetNbinsY(); biny++) {
1121 for(binx=1; binx<=
hist->GetNbinsX(); binx++) {
1122 bin =
hist->GetBin(binx,biny);
1124 if(
value==0.)
continue;
1125 for(
auto&
period : m_periods) {
1127 if(!
period.second->contains(
run.first))
continue;
1129 for(
auto& inHist :
period.second->inputHists) {
1130 if(inHist.first<0)
continue;
1131 if((inHist.second)->GetBinContent(
bin)==0) {
1132 unrepDataByChannel[-1] +=
value; done=
true;
break;
1145 m_triggerObjs[
"None"] = std::make_unique< CompositeTrigger >();
1148 for(
auto period : m_periods) {
1150 for(
auto& inputHist :
period.second->inputHists) {
1151 int channel = inputHist.first;
1152 TH1*
hist = inputHist.second.get();
1155 if(
hist->GetDimension()==1) {
1161 for(
auto&
run : m_runs) {
1162 if(!
period.second->contains(
run.first))
continue;
1163 if(
run.second.inputHists.find(
"None") ==
run.second.inputHists.end())
continue;
1165 period.second->runNumbers.push_back(
run.first);
1166 TH1*
hist =
run.second.inputHists[
"None"].get();
1169 Int_t
bin,binx,biny;
1170 for(biny=1; biny<=
hist->GetNbinsY(); biny++) {
1171 for(binx=1; binx<=
hist->GetNbinsX(); binx++) {
1172 bin =
hist->GetBin(binx,biny);
1174 if(
value==0.)
continue;
1176 if(
period.second->inputBinRedirect.find(
bin) ==
period.second->inputBinRedirect.end()) {
1177 for(
auto& inputHist :
period.second->inputHists) {
1178 if(inputHist.first<0)
continue;
1179 Double_t mcValue = (inputHist.second)->GetBinContent(
bin);
1181 if(m_unrepresentedDataAction!=0 && m_debugging && m_printInfo) {
1182 Info(
"Initialize",
"Unrepresented data at coords [%f,%f] caused by periodNumber %d in channel %d",
hist->GetXaxis()->GetBinCenter(binx),
hist->GetYaxis()->GetBinCenter(biny),
period.first,inputHist.first);
1185 if(m_unrepresentedDataAction==0) {
period.second->inputBinRedirect[
bin] =
bin-1;Error(
"Initialize",
"Unrepresented data at coords [%f,%f] caused by periodNumber %d in channel %d",
hist->GetXaxis()->GetBinCenter(binx),
hist->GetYaxis()->GetBinCenter(biny),
period.first,inputHist.first);}
1186 if(m_unrepresentedDataAction==1||m_unrepresentedDataAction==2)
period.second->inputBinRedirect[
bin] =
bin-1;
1187 else if(m_unrepresentedDataAction==3)
period.second->inputBinRedirect[
bin] = GetNearestGoodBin(
period.first,
bin);
1191 if(
period.second->inputBinRedirect.find(
bin) ==
period.second->inputBinRedirect.end())
period.second->inputBinRedirect[
bin] =
bin;
1196 if(m_unrepresentedDataAction==1) {
1200 for(
auto& triggerDists :
run.second.inputHists) triggerDists.second->SetBinContent(
bin,0);
1201 }
else if(m_unrepresentedDataAction==3) {
1206 for(
auto& triggerDists :
run.second.inputHists) {
1207 triggerDists.second->SetBinContent(
period.second->inputBinRedirect[
bin],triggerDists.second->GetBinContent(
period.second->inputBinRedirect[
bin])+triggerDists.second->GetBinContent(
bin));
1208 triggerDists.second->SetBinContent(
bin,0);
1216 if(
run.second.nominalFromHists) {
1219 for(
auto lb :
run.second.lumiByLbn) {
1220 totLumi +=
lb.second.first;
1230 if(
hist->GetDimension()==1 ) {
1231 if(!
period.second->primaryHists[-1] ) {
1232 period.second->primaryHists[-1] = CloneEmptyHistogram(
period.first,-1);
1235 m_triggerObjs[
"None"]->triggerHists[
period.second->id][0] =
1239 else if(
hist->GetDimension()==2 ) {
1240 if(!
period.second->secondaryHists[-1] ) {
1241 auto h = CloneEmptyHistogram(
period.first,-1);
1242 period.second->secondaryHists[-1].reset(
dynamic_cast< TH2*
>(
h.release() ) );
1243 period.second->primaryHists[-1].reset(
1244 period.second->secondaryHists[-1]->ProjectionX() );
1245 period.second->primaryHists[-1]->SetDirectory(0);
1246 period.second->primaryHists[-1]->Reset();
1247 m_triggerObjs[
"None"]->triggerHists[
period.second->id][0].reset(
1248 static_cast<TH1*
>(
period.second->primaryHists[-1]->Clone(
"triggerHist")) );
1249 m_triggerObjs[
"None"]->triggerHists[
period.second->id][0]->SetDirectory(0);
1262 double ignoredData(0);
1263 for(
auto&
run : m_runs) {
1264 bool covered(
false);
1265 TH1*
hist =
run.second.inputHists[
"None"].get();
1266 for(
auto&
period : m_periods) {
1267 if(!
period.second->contains(
run.first))
continue;
1268 if(
period.first!=-1) covered=
true;
1269 if(
hist->GetDimension()==1) {
1271 m_triggerObjs[
"None"]->triggerHists[
period.second->id][0]->Add(
hist);
1272 }
else if(
hist->GetDimension()==2) {
1273 period.second->secondaryHists[-1]->Add(
hist);
1274 TH1*
proj = ((TH2*)
hist)->ProjectionX();
1276 m_triggerObjs[
"None"]->triggerHists[
period.second->id][0]->Add(
proj);
1279 period.second->sumOfWeights[-1] +=
hist->GetSumOfWeights();
1280 period.second->numberOfEntries[-1] +=
hist->GetEntries();
1282 if(!covered && m_periods.size()>1) {
1283 Warning(
"Initialize",
"loaded data in run %d that is not covered by period assignments",
run.first);
1284 ignoredData +=
hist->GetSumOfWeights();
1289 if(ignoredData>0.) Warning(
"Initialize",
"Period Assignments missed %f%% data",100.*ignoredData/totalData);
1293 if(unrepDataByChannel[-1]) {
1294 double frac = unrepDataByChannel[-1]/totalData;
1295 if(
frac > m_unrepDataTolerance) {
1296 Error(
"Initialize",
"%f%% unrepresented data, which suggests something is wrong with your prw config. Try EnableDebugging(true) to investigate",100.* (unrepDataByChannel[-1]/totalData));
1298 if(m_unrepresentedDataAction==1) {
1299 Warning(
"Initialize",
"has %f%% unrepresented data. This was removed (UnrepresentedDataAction=1)",100.*
frac);
1300 }
else if(m_unrepresentedDataAction==2) {
1301 Warning(
"Initialize",
"has %f%% unrepresented data. This was kept in (UnrepresentedDataAction=2)",100.*
frac);
1302 }
else if(m_unrepresentedDataAction==3) {
1303 Warning(
"Initialize",
"has %f%% unrepresented data. This was reassigned (UnrepresentedDataAction=3)",100.*
frac);
1304 }
else if(m_unrepresentedDataAction==0) {
1305 Error(
"Initialize",
"has %f%% unrepresented data:",100.*
frac);
1307 for(
auto&
it : unrepDataByChannel) {
1308 if(
it.first<0)
continue;
1309 Error(
"Initialize",
" Channel %d caused %f%% of the unrepresented data (nEntries=%d)",
it.first,100.*
it.second/unrepDataByChannel[-1],m_periods[-1]->numberOfEntries[
it.first]);
1311 Error(
"Initialize",
"Exiting. You must decide how to proceed...");
1312 Error(
"Initialize",
"1) use AddPeriod or RemapPeriod to redefine the mc periods to include this data. You should not need to regenerate your mc config file");
1313 Error(
"Initialize",
"2) use SetUnrepresentedDataAction(1) to remove this data from the weight calculations. You should also veto such data events (using IsUnrepresentedData(..,..) method)");
1314 Error(
"Initialize",
"3) use SetUnrepresentedDataAction(2) to leave this data in the calculation. I hope you know what you're doing!!");
1315 Error(
"Initialize",
"4) use SetUnrepresentedDataAction(3) to reassign the data to the nearest representable bin");
1316 throw std::runtime_error(
"Throwing exception 22: Unrepresented data exists. Make a choice how to handle this. See err log for details");
1319 if(
frac > m_unrepDataTolerance) {
1320 throw std::runtime_error(
"Throwing exception 222: Some channel had too much unrepresented data. You should fix your prw file");
1325 if(m_debugging && m_printInfo) Info(
"Initialize",
"Normalizing histograms and cleaning up...");
1327 for(
auto period : m_periods) {
1329 for(
auto& pHist :
period.second->primaryHists) {
1330 normalizeHistogram(pHist.second.get());
1332 for(
auto& pHist :
period.second->secondaryHists) {
1333 normalizeHistogram(pHist.second.get());
1335 period.second->inputHists.clear();
1340 if(m_debugging && m_printInfo) Info(
"Initialize",
"...Done");
1344 m_isInitialized=
true;
1355 Period*
p = m_periods[periodNumber];
1356 for(
auto& inHist :
p->inputHists) {
1357 int channelNumber = inHist.first;
1358 if(channelNumber<0)
continue;
1359 if(
bin > (inHist.second->GetNbinsX()+2)*(inHist.second->GetNbinsY()+2)*(inHist.second->GetNbinsZ()+2))
return 2;
1360 if(inHist.second->GetBinContent(
bin)==0)
return 1;
1369 int binDistance = 1;
1371 int res1 = IsBadBin(thisMCRunNumber,
bin+binDistance);
1372 if(!res1)
return bin+binDistance;
1373 int res2 = IsBadBin(thisMCRunNumber,
bin-binDistance);
1374 if(!res2)
return bin-binDistance;
1375 if(res1==2 && res2==2) {
1376 Error(
"GetNearestGoodBin",
"None of the bins are good!!??");
1391 Period*
p = m_periods[periodNumber];
1393 Error(
"GetUnrepresentedDataFraction",
"Unrecognised periodNumber: %d",periodNumber);
1394 throw std::runtime_error(
"Throwing 1: Unrecognised periodNumber");
1398 if(
p->sumOfWeights.find(
channel) ==
p->sumOfWeights.end())
channel = GetDefaultChannel(periodNumber);
1401 if(
p->sumOfWeights.find(
channel) ==
p->sumOfWeights.end()) {
1402 Error(
"GetUnrepresentedDataFraction",
"Unrecognised channel: %d",
channel);
1403 throw std::runtime_error(
"GetUnrepresentedDataFraction: Unrecognised channel");
1406 return p->unrepData[
channel]/
p->sumOfWeights[-1];
1413 if(!m_isInitialized) {
1414 if (m_printInfo)Info(
"GetRandomRunNumber",
"Initializing the subtool..");
1417 if(m_countingMode) {
return 0; }
1419 Period*
p = m_periods[periodNumber];
1420 if(!
p || !
p->primaryHists[-1]) {
1421 Error(
"GetRandomRunNumber",
"Unrecognised periodNumber or no data loaded for: %d",periodNumber);
1422 throw std::runtime_error(
"Throwing 1: Unrecognised periodNumber");
1425 double lumi =
p->sumOfWeights[-1] * m_random3->Rndm();
1429 for(
auto runNum :
p->runNumbers) {
1430 lumiSum += m_runs[
runNum].inputHists[
"None"]->GetSumOfWeights();
1433 Error(
"GetRandomRunNumber",
"overran integrated luminosity for periodNumber=%d (%f vs %f)",periodNumber,lumiSum,
lumi);
1434 throw std::runtime_error(
"Throwing 46.1: overran integrated luminosity for GetRandomRunNumber");
1439 if(!m_isInitialized) {
1440 if (m_printInfo) Info(
"GetRandomRunNumber",
"Initializing the subtool..");
1443 if(m_countingMode) {
return 0; }
1445 Period*
p = m_periods[periodNumber];
1446 if(!
p || !
p->primaryHists[-1]) {
1447 Error(
"GetRandomRunNumber",
"Unrecognised periodNumber or no data loaded for: %d",periodNumber);
1448 throw std::runtime_error(
"Throwing 1: Unrecognised periodNumber");
1451 int bin = m_emptyHistogram->FindFixBin(
x);
1453 double lumi =
p->primaryHists[-1]->GetBinContent(
bin) *
p->sumOfWeights[-1] * m_random3->Rndm();
1455 if(!
lumi) {
return 0; }
1460 for(
auto runNum :
p->runNumbers) {
1461 lumiSum += m_runs[
runNum].inputHists[
"None"]->GetBinContent(
bin);
1464 Error(
"GetRandomRunNumber",
"overran integrated luminosity for periodNumber=%d (%f vs %f)",periodNumber,lumiSum,
lumi);
1465 throw std::runtime_error(
"Throwing 46.1: overran integrated luminosity for GetRandomRunNumber");
1470 if(!m_isInitialized) {
1472 Info(
"GetRandomLumiBlockNumber",
"Initializing the subtool..");
1476 if(m_countingMode) {
return 0; }
1479 double lumisum = 0.;
1481 for(
auto& lbn : m_runs[
runNumber].lumiByLbn) {
1482 if(m_unrepresentedDataAction==1 && IsUnrepresentedData(
runNumber,lbn.second.second))
continue;
1483 lumisum += lbn.second.first;
1484 if(lumisum >=
lumi)
return lbn.first;
1486 Error(
"GetRandomLumiBlockNumber",
"overran integrated luminosity for RunNumber=%d (%f vs %f)",
runNumber,
lumi,lumisum);
1487 throw std::runtime_error(
"Throwing 46: overran integrated luminosity for runNumber");
1493 if(!m_isInitialized) {
1494 if (m_printInfo) Info(
"GetRandomPeriodNumber",
"Initializing the subtool..");
1497 if(m_countingMode) {
return 0; }
1499 Period*
p = m_periods[periodNumber];
1501 Error(
"GetRandomPeriodNumber",
"Unrecognised periodNumber: %d",periodNumber);
1502 throw std::runtime_error(
"Throwing 1: Unrecognised periodNumber");
1506 if(
p->subPeriods.size()==0)
return p->id;
1509 double lumi =
p->sumOfWeights[-1] * m_random3->Rndm();
1513 for(
auto subp :
p->subPeriods) {
1514 lumiSum += subp->sumOfWeights[-1];
1515 if(lumiSum >=
lumi)
return subp->id;
1518 Error(
"GetRandomPeriodNumber",
"overran integrated luminosity for periodNumber=%d",periodNumber);
1519 throw std::runtime_error(
"Throwing 46.1: overran integrated luminosity for GetRandomPeriodNumber");
1525 int bin = m_emptyHistogram->FindFixBin(
x,
y);
1531 if(!m_isInitialized ) {
1532 if (m_printInfo) Info(
"MakeWeightTree",
"Initializing the subtool..");
1535 TH1*
hist = m_emptyHistogram.get();
1537 Error(
"MakeWeightTree",
"Tool not configured properly ... please report this!");
1538 throw std::runtime_error(
"Throwing 47: Tool not configured properly ... please report this!");
1544 TTree* outTree =
new TTree(
"prwTree",
"prwTree");
1545 ULong64_t prwHash(0);Float_t
weight(0.);
1546 outTree->Branch(hashBranch,&prwHash);
1547 outTree->Branch(weightBranch,&
weight);
1549 TObjArray *
tx = channelNumbers.Tokenize(
",");
1550 for (Int_t
i = 0;
i <
tx->GetEntries();
i++) {
1551 int channelNumber = ((TObjString *)(
tx->At(
i)))->String().Atoi();
1552 if(channelNumber>999999 || channelNumber<0) {
1553 Error(
"MakeWeightTree",
"ChannelNumber can not be bigger than 999999 or less than 0 ... got %d",channelNumber);
1557 for(
auto&
period : m_periods) {
1558 if(
period.first==-1)
continue;
1559 int periodNumber =
period.first;
1560 for(
int i=1;
i<=
hist->GetNbinsX();
i++) {
1561 double x =
hist->GetXaxis()->GetBinCenter(
i);
1562 for(
int j=1;j<=
hist->GetNbinsY();j++) {
1563 double y =
hist->GetYaxis()->GetBinCenter(j);
1564 weight = GetCombinedWeight(periodNumber,channelNumber,
x,
y);
1565 prwHash = GetPRWHash(periodNumber,channelNumber,
x,
y);
1573 outTree->BuildIndex(hashBranch.Data());
1578 Info(
"MakeWeightTree",
"Successfully wrote prwTree to %s",
outFile.Data());
1585 if(!m_isInitialized) {
1586 if (m_printInfo) Info(
"GetPRWHash",
"Initializing the subtool..");
1589 TH1*
hist = m_emptyHistogram.get();
1591 Error(
"GetPRWHash",
"Tool not configured properly ... please report this!");
1592 throw std::runtime_error(
"Throwing 47: Tool not configured properly ... please report this!");
1596 out += (
unsigned long)(channelNumber)*10000000000;
1597 out += (
unsigned long)(periodNumber)*10000;
1604 if(!m_isInitialized) {
1605 if (m_printInfo) Info(
"GetCombinedWeight",
"Initializing the subtool..");
1608 if(m_countingMode)
return 0.;
1611 TH1*
hist = m_emptyHistogram.get();
1613 Error(
"GetCombinedWeight",
"Tool not configured properly ... please report this!");
1614 throw std::runtime_error(
"Throwing 47: Tool not configured properly ... please report this!");
1617 Float_t
out = GetPeriodWeight(periodNumber,channelNumber)*GetPrimaryWeight(periodNumber,channelNumber,
x);
1618 if(
hist->GetDimension()>1)
out *= GetSecondaryWeight(periodNumber,channelNumber,
x,
y);
1625 if(!m_isInitialized) {
1626 if (m_printInfo) Info(
"GetPeriodWeight",
"Initializing the subtool..");
1629 if(m_countingMode)
return 0.;
1631 Period*
p = m_periods[periodNumber];
1633 Error(
"GetPeriodWeight",
"Unrecognised periodNumber: %d",periodNumber);
1634 throw std::runtime_error(
"Throwing 1: Unrecognised periodNumber");
1636 if(
p->sumOfWeights.find(channelNumber) ==
p->sumOfWeights.end()) {
1637 channelNumber = GetDefaultChannel(periodNumber);
1638 if(channelNumber!=0) {
1639 Warning(
"GetPeriodWeight",
"You're using a default config file ... you're gonna have a bad time!!");
1640 Warning(
"GetPeriodWeight",
"Please generate proper config files!");
1644 double n_a =
p->sumOfWeights[channelNumber];
1645 double n = m_periods[-1]->sumOfWeights[channelNumber];
1647 double l_a =
p->sumOfWeights[-1];
1648 double l = m_periods[-1]->sumOfWeights[-1];
1650 return (l_a/
l) / (n_a/
n);
1655 if(!m_isInitialized ) {
1656 if (m_printInfo) Info(
"GetPrimaryWeight",
"Initializing the subtool..");
1659 if(m_countingMode)
return 0.;
1661 Period*
p = m_periods[periodNumber];
1663 Error(
"GetPrimaryWeight",
"Unrecognised periodNumber: %d",periodNumber);
1664 throw std::runtime_error(
"Throwing 1: Unrecognised periodNumber");
1666 int oChanNumber = channelNumber;
1667 if(
p->sumOfWeights.find(channelNumber) ==
p->sumOfWeights.end()) channelNumber = GetDefaultChannel(periodNumber);
1669 if(!
p->primaryHists[channelNumber]) {
1670 Error(
"GetPrimaryWeight",
"Unrecognised channelNumber %d for periodNumber %d",oChanNumber,periodNumber);
1671 throw std::runtime_error(
"Throwing 2: Unrecognised channelNumber");
1674 int bin =
p->primaryHists[channelNumber]->FindFixBin(
x);
1676 double n =
p->primaryHists[channelNumber]->GetBinContent(
bin);
1682 Warning(
"GetPrimaryWeight",
"No events expected in channelNumber %d for periodNumber %d with x=%g. Incorrect PRW profile or are you very unlucky???",channelNumber,periodNumber,
x);
1686 if(!
p->primaryHists[-1]) {
1687 Error(
"GetPrimaryWeight",
"No data loaded for period %d. Did you forget to load a lumicalc file or data config file?",periodNumber);
1688 throw std::runtime_error(
"Throwing 3: No data loaded. Did you forget to load a lumicalc file or data config file?");
1691 double l =
p->primaryHists[-1]->GetBinContent(
bin);
1694 Error(
"GetPrimaryWeight",
"No events expected with this mu. Incorrect PRW profile? Throwing exception ...");
1695 throw std::runtime_error(Form(
"Incorrect PRW profile detected. x=%g is not in the config file profile for channel %d, period %d",
x, channelNumber, periodNumber ));
1703 if(!m_isInitialized ) {
1704 if (m_printInfo) Info(
"GetSecondaryWeight",
"Initializing the subtool..");
1707 if(m_countingMode)
return 0.;
1709 Period*
p = m_periods[periodNumber];
1711 Error(
"GetSecondaryWeight",
"Unrecognised periodNumber: %d",periodNumber);
1712 throw std::runtime_error(
"Throwing 1: Unrecognised periodNumber");
1714 if(
p->sumOfWeights.find(channelNumber) ==
p->sumOfWeights.end()) channelNumber = GetDefaultChannel(periodNumber);
1715 int bin =
p->secondaryHists[channelNumber]->FindFixBin(
x,
y);
1716 double n =
p->secondaryHists[channelNumber]->GetBinContent(
bin);
1717 double l =
p->secondaryHists[-1]->GetBinContent(
bin);
1724 m_doGlobalDataWeight=
true;
1726 m_doGlobalDataWeight=
false;
1732 if(!m_isInitialized ) {
1733 if (m_printInfo) Info(
"GetDataWeight",
"Initializing the subtool..");
1736 if(m_countingMode)
return 0.;
1739 Int_t periodNumber = GetFirstFoundPeriodNumber(
runNumber);
1741 Period*
p = m_periods[periodNumber];
1743 Error(
"GetDataWeight",
"Unrecognised periodNumber: %d",periodNumber);
1744 throw std::runtime_error(
"Throwing 1: Unrecognised periodNumber");
1748 auto tobj = m_triggerObjs.find(trigger);
1751 if(tobj==m_triggerObjs.end()) {
1754 CalculatePrescaledLuminosityHistograms(trigger,0);
1755 tobj = m_triggerObjs.find(trigger);
1762 if(tobj->second->triggerHists.find(
p->id) == tobj->second->triggerHists.end()) {
1763 Error(
"GetDataWeight",
"Could not find trigger %s in period %d",trigger.Data(),
p->id);
1764 throw std::runtime_error(
"GetDataWeight: Could not find trigger 1");
1769 long tbits = tobj->second->getBits(
this);
1771 if(tbits==0)
return 1;
1776 auto dItr = tobj->second->triggerHists[
idx].find(tbits);
1779 if(dItr == tobj->second->triggerHists[
idx].end()) {
1781 calculateHistograms(tobj->second.get(),(runDependent) ?
runNumber:0);
1783 denomHist = tobj->second->triggerHists[
idx][tbits].get();
1785 Error(
"GetDataWeight",
"Could not find trigger %s in period %d with bits %ld",trigger.Data(),
idx, tbits);
1786 throw std::runtime_error(
"GetDataWeight: Could not find trigger 2");
1789 denomHist = dItr->second.get();
1793 TH1* numerHist = m_triggerObjs[
"None"]->triggerHists[
idx][0].get();
1795 Error(
"GetDataWeight",
"Could not find unprescaled trigger in period %d",
idx);
1796 throw std::runtime_error(
"GetDataWeight: Could not find unprescaled trigger. Please AddLumiCalc with a 'None' trigger");
1799 if(m_doGlobalDataWeight)
return numerHist->Integral(0,numerHist->GetNbinsX()+1)/denomHist->Integral(0,denomHist->GetNbinsX()+1);
1801 Int_t
bin=(m_doPrescaleWeight) ? numerHist->FindFixBin(
x) :
1802 numerHist->FindFixBin(
x*m_dataScaleFactorX);
1805 if( (!m_doPrescaleWeight) && m_unrepresentedDataAction==3)
bin =
p->inputBinRedirect[
bin];
1807 if(!denomHist->GetBinContent(
bin)) {
1808 if(m_doPrescaleWeight)
return -1;
1809 Error(
"GetDataWeight",
"Unrecognised mu value %f ... are you sure you included all lumicalc files",
x);
1810 throw std::runtime_error(
"GetDataWeight: Unrecognised mu value. Please AddLumiCalc enough lumi with 'None' trigger");
1813 return numerHist->GetBinContent(
bin)/denomHist->GetBinContent(
bin);
1819 m_doGlobalDataWeight=
true;
1821 m_doGlobalDataWeight=
false;
1827 m_doPrescaleWeight =
true;
1828 double out = GetDataWeight(
runNumber,trigger,
x,runDependent);
1829 m_doPrescaleWeight =
false;
1830 if(
out<=0)
return 0;
1838 if(!m_isInitialized ) {
1839 if (m_printInfo) Info(
"Fill",
"Initializing the subtool..");
1847 if(channelNumber>=0) {
1848 if(m_periods.find(
runNumber)==m_periods.end()) {
1850 if(m_autoRunStart || m_autoRunEnd) {
1851 AddPeriod(
runNumber,m_autoRunStart,m_autoRunEnd);
1853 if(m_periods.find(
runNumber)==m_periods.end()) {
1854 Error(
"Fill",
"Unrecognised runNumber: %d. Check your period configuration (AddPeriod or UsePeriodConfig)",
runNumber);
1855 throw std::runtime_error(
"Throwing 1: Unrecognised periodNumber");
1860 Error(
"Fill",
"Unrecognised runNumber: %d. Check your period configuration (AddPeriod or UsePeriodConfig) ... but should never have got here so please report this!",
runNumber);
1861 throw std::runtime_error(
"Throwing 1: Unrecognised periodNumber");
1863 std::unique_ptr<TH1>& histptr =
p->inputHists[channelNumber];
1866 histptr = CloneEmptyHistogram(
runNumber,channelNumber);
1868 hist = histptr.get();
1871 if( !
r.inputHists[
"None"])
r.inputHists[
"None"]=CloneEmptyHistogram(
runNumber,channelNumber);
1872 hist =
r.inputHists[
"None"].get();
1876 Error(
"Fill",
"Unknown [run,channel] = [%d,%d]",
runNumber,channelNumber);
1877 throw std::runtime_error(
"Throwing 45: Fill:: Unknown [run,channel] ");
1880 if(
hist->GetDimension()==1) {
1882 }
else if(
hist->GetDimension()==2) {
1883 return (
static_cast<TH2*
>(
hist))->Fill(
x,
y,
w);
1890 if(!m_countingMode) {Warning(
"WriteToFile",
"Not in counting mode, so no file will be written");
return 0;}
1908 if(!m_countingMode) {Warning(
"WriteToFile",
"Not in counting mode, so no file will be written");
return 0;}
1914 std::unique_ptr< TTree > outTreeMC;
1915 std::unique_ptr< TTree > outTreeData;
1917 auto pStarts = std::make_unique< std::vector< UInt_t > >();
1918 auto pStartsPtr = pStarts.get();
1919 auto pEnds = std::make_unique< std::vector< UInt_t > >();
1920 auto pEndsPtr = pEnds.get();
1925 for(
auto period : m_periods) {
1927 if(
period.first<0)
continue;
1931 if(
period.second->subPeriods.size()==0) {
1932 pStarts->push_back(
period.second->start); pEnds->push_back(
period.second->end);
1935 for(
auto subp :
period.second->subPeriods) {
1936 pStarts->push_back(subp->start); pEnds->push_back(subp->end);
1939 for(
auto& inHist :
period.second->inputHists) {
1941 TH1*
hist = inHist.second.get();
1946 outTreeMC.reset(
new TTree(
"MCPileupReweighting",
"MCPileupReweighting") );
1947 outTreeMC->Branch(
"Channel",&
channel);
1948 outTreeMC->Branch(
"RunNumber",&
runNumber);
1949 outTreeMC->Branch(
"PeriodStarts",&pStartsPtr);
1950 outTreeMC->Branch(
"PeriodEnds",&pEndsPtr);
1951 outTreeMC->Branch(
"HistName",&
histName,
"HistName/C");
1958 for(
auto&
run : m_runs) {
1960 if(
run.second.inputHists.find(
"None")==
run.second.inputHists.end())
continue;
1962 TH1*
hist =
run.second.inputHists[
"None"].get();
1966 outTreeData.reset(
new TTree(
"DataPileupReweighting",
"DataPileupReweighting") );
1967 outTreeData->Branch(
"RunNumber",&
runNumber);
1968 outTreeData->Branch(
"HistName",&
histName,
"HistName/C");
1970 outTreeData->Fill();
1979 outTreeData->Write();
1983 Info(
"WriteToFile",
"Successfully generated config file: %s",
outFile->GetName());
1984 Info(
"WriteToFile",
"Happy Reweighting :-)");
1999 if(
hist->InheritsFrom(
"TH3")) {
2000 Error(
"normalizeHistogram",
"3D reweighting not supported yet");
2001 throw std::runtime_error(
"Throwing 3: 3D reweighting not supported yet");
2003 else if(
hist->InheritsFrom(
"TH2")) {
2004 bool skipNorm=
false;
2006 TH1D*
proj = ((TH2*)
hist)->ProjectionX();
2007 Int_t
bin,binx,biny,binz;
2008 for(binz=1; binz<=
hist->GetNbinsZ(); binz++) {
2009 for(biny=1; biny<=
hist->GetNbinsY(); biny++) {
2010 for(binx=1; binx<=
hist->GetNbinsX(); binx++) {
2011 bin =
hist->GetBin(binx,biny,binz);
2013 Double_t normalizer =
proj->GetBinContent(binx);
2014 if(normalizer!=0.0) {
2023 if(skipNorm && m_debugging) Warning(
"normalizeHistogram",
"Skipped normalization in hist %s",
hist->GetName());
2026 if(
hist->GetSumOfWeights()!=0.0) {
2027 hist->Scale(1.0/
hist->GetSumOfWeights());
2029 if (m_debugging) Warning(
"normalizeHistogram",
"Skipping Normalizing histogram %s to ~zero: %f",
hist->GetName(),
hist->GetSumOfWeights());
2033 Error(
"normalizeHistogram",
"Non existent histogram for normalizing");
throw std::runtime_error(
"Throwing 56");
2041 if(coll->IsEmpty())
return 0;
2051 Error(
"Merge",
"Unknown object type encountered: %s",
obj->ClassName() );
2058 for(
auto& iHist :
period.second->inputHists) {
2059 if(GetInputHistogram(
period.first,iHist.first)==0) {
2060 m_periods[
period.first]->inputHists[iHist.first].reset(
2061 dynamic_cast<TH1*
>(iHist.second->Clone(iHist.second->GetName())) );
2062 m_periods[
period.first]->inputHists[iHist.first]->SetDirectory(0);
2064 GetInputHistogram(
period.first,iHist.first)->Add(iHist.second.get());
2070 for(
auto& iHist :
run.second.inputHists) {
2071 if( ! m_runs[
run.first].inputHists[iHist.first] ) {
2072 m_runs[
run.first].inputHists[iHist.first].reset(
2073 dynamic_cast<TH1*
>( iHist.second->Clone(iHist.second->GetName())) );
2074 m_runs[
run.first].inputHists[iHist.first]->SetDirectory(0);
2076 m_runs[
run.first].inputHists[iHist.first]->Add(iHist.second.get());
2089 TString triggerCopy = trigger; triggerCopy.ReplaceAll(
" ",
""); triggerCopy.ReplaceAll(
"&&",
"&");triggerCopy.ReplaceAll(
"||",
"|");
2090 auto t = makeTrigger(triggerCopy);
2092 Error(
"GetDataWeight",
"Error parsing composite trigger set: %s",trigger.Data());
2093 throw std::runtime_error(
"Could not parse composite trigger");
2096 std::vector<TString> subTriggers;
2098 t->getTriggers(subTriggers);
2100 t->subTriggers = subTriggers;
2102 calculateHistograms(
t.get(),runDependentRun);
2105 m_triggerObjs[trigger] = std::move(
t );
2110 TH1* unprescaledLumi = 0;
2111 if(runDependentRun) {
2112 unprescaledLumi = m_triggerObjs[
"None"]->triggerHists[-runDependentRun][0].get();
2114 bool fillUnprescaledLumi = (unprescaledLumi==0);
2117 long tbits =
t->getBits(
this);
2125 std::map<TString, std::map<Int_t, std::map<Int_t, Float_t> > > prescaleByRunAndLbn;
2133 bool isUnprescaled = (
std::find(m_lumicalcFiles[
"None"].
begin(),m_lumicalcFiles[
"None"].
end(),
fileName)!=m_lumicalcFiles[
"None"].end());
2137 Error(
"CalculatePrescaledLuminosityHistograms",
"Could not open file: %s",
fileName.Data());
2138 std::string toThrow =
"Throwing 6: Could not open file: "; toThrow +=
fileName.Data();
2139 throw std::runtime_error(toThrow);
2142 TTree *
tmp = (TTree*)
rootFile->Get(
"LumiMetaData" );
2146 UInt_t runNbr=0;Float_t
ps1=0;Float_t
ps2=0; Float_t ps3=0;UInt_t lbn=0;TBranch *b_runNbr=0;TBranch *b_L1Presc=0;TBranch *b_L2Presc=0;TBranch *b_L3Presc=0;TBranch *b_lbn=0;
2147 if(
tmp->SetBranchAddress(
"RunNbr",&runNbr,&b_runNbr)!=0) {
2148 Error(
"CalculatePrescaledLuminosityHistograms",
"Could not find RunNbr branch in Data TTree");
throw std::runtime_error(
"Could not find RunNbr branch in Data TTree");
2150 if(
tmp->SetBranchAddress(
"L1Presc",&
ps1,&b_L1Presc)!=0) {
2151 Error(
"CalculatePrescaledLuminosityHistograms",
"Could not find L1Presc branch in Data TTree");
throw std::runtime_error(
"Could not find L1Presc branch in Data TTree");
2153 if(
tmp->SetBranchAddress(
"L2Presc",&
ps2,&b_L2Presc)!=0) {
2154 Error(
"CalculatePrescaledLuminosityHistograms",
"Could not find L2Presc branch in Data TTree");
throw std::runtime_error(
"Could not find L2Presc branch in Data TTree");
2156 if(
tmp->SetBranchAddress(
"L3Presc",&ps3,&b_L3Presc)!=0) {
2157 Error(
"CalculatePrescaledLuminosityHistograms",
"Could not find L3Presc branch in Data TTree");
throw std::runtime_error(
"Could not find L3Presc branch in Data TTree");
2159 if(
tmp->SetBranchAddress(
"LBStart",&lbn,&b_lbn)!=0) {
2160 Error(
"CalculatePrescaledLuminosityHistograms",
"Could not find LBStart branch in Data TTree");
throw std::runtime_error(
"Could not find LBStart branch in Data TTree");
2164 b_runNbr->GetEntry(
i);b_L1Presc->GetEntry(
i);b_L2Presc->GetEntry(
i);b_L3Presc->GetEntry(
i);b_lbn->GetEntry(
i);
2165 runNbr += m_lumicalcRunNumberOffset;
2166 if(runDependentRun &&
int(runNbr)!=runDependentRun)
continue;
2169 if(m_debugging && m_printInfo) Info(
"...",
"prescale in [%d,%d] = %f %f %f", runNbr,lbn,
ps1,
ps2,ps3);
2170 if(
ps1>0&&
ps2>0&&ps3>0) prescaleByRunAndLbn[*
it][runNbr][lbn] =
ps1*
ps2*ps3;
2171 else if(isUnprescaled) prescaleByRunAndLbn[*
it][runNbr][lbn] = 1;
2180 for(
auto&
fileName : m_lumicalcFiles[
"None"]) {
2184 Error(
"CalculatePrescaledLuminosityHistograms",
"Could not open file: %s",
fileName.Data());
2185 std::string toThrow =
"Throwing 6: Could not open file: "; toThrow +=
fileName.Data();
2186 throw std::runtime_error(toThrow);
2189 TTree *
tmp = (TTree*)
rootFile->Get(
"LumiMetaData" );
2193 UInt_t runNbr=0;Float_t intLumi=0;UInt_t lbn=0;TBranch *b_runNbr=0;TBranch *b_intLumi=0;TBranch *b_lbn=0;
2194 Float_t
mu=0.; TBranch *b_mu=0;
2195 if(
tmp->SetBranchAddress(
"RunNbr",&runNbr,&b_runNbr)!=0) {
2196 Error(
"CalculatePrescaledLuminosityHistograms",
"Could not find RunNbr branch in Data TTree");
throw std::runtime_error(
"Could not find RunNbr branch in Data TTree");
2198 if(
tmp->SetBranchAddress(
"AvergeInteractionPerXing",&
mu,&b_mu)!=0) {
2199 Error(
"CalculatePrescaledLuminosityHistograms",
"Could not find AvergeInteractionPerXing branch in Data TTree");
throw std::runtime_error(
"Could not find AvergeInteractionPerXing branch in Data TTree");
2201 if(
tmp->SetBranchAddress(
"IntLumi",&intLumi,&b_intLumi)!=0) {
2202 Error(
"CalculatePrescaledLuminosityHistograms",
"Could not find IntLumi branch in Data TTree");
throw std::runtime_error(
"Could not find IntLumi branch in Data TTree");
2204 if(
tmp->SetBranchAddress(
"LBStart",&lbn,&b_lbn)!=0) {
2205 Error(
"CalculatePrescaledLuminosityHistograms",
"Could not find LBStart branch in Data TTree");
throw std::runtime_error(
"Could not find LBStart branch in Data TTree");
2210 b_runNbr->GetEntry(
i);b_intLumi->GetEntry(
i);b_mu->GetEntry(
i);
2213 runNbr += m_lumicalcRunNumberOffset;
2214 if(runDependentRun &&
int(runNbr)!=runDependentRun)
continue;
2217 double pFactor =
t->eval(prescaleByRunAndLbn,runNbr,lbn,
this);
2221 int bin = m_emptyHistogram->FindFixBin(
mu*m_dataScaleFactorX);
2224 bool firstFill=
false;
2225 for(
auto p : m_periods) {
2226 if(
p.first !=
p.second->id)
continue;
2227 if(!
p.second->contains(runNbr))
continue;
2228 if(runDependentRun && firstFill)
continue;
2230 int idx = (runDependentRun) ? -runDependentRun :
p.second->id;
2233 auto& triggerHists =
t->triggerHists[
idx];
2234 std::unique_ptr<TH1>& histptr = triggerHists[tbits];
2236 histptr = CloneEmptyHistogram(
p.first,-1);
2237 if(m_debugging && m_printInfo) Info(
"CalculatePrescaledLuminosityHistograms",
"Created Data Weight Histogram for [%s,%d,%d,%ld]",
t->val.Data(),
p.first,
idx,tbits);
2240 if( (m_unrepresentedDataAction==1) &&
p.second->inputBinRedirect[
bin]!=
bin) { }
2241 else if( m_unrepresentedDataAction==3 ) {histptr->Fill(triggerHists[tbits]->GetBinCenter(
p.second->inputBinRedirect[
bin]), intLumi*pFactor);}
2242 else triggerHists[tbits]->Fill(
mu*m_dataScaleFactorX,intLumi*pFactor);
2245 if(runDependentRun && fillUnprescaledLumi) {
2247 if(unprescaledLumi==0) {
2248 m_triggerObjs[
"None"]->triggerHists[-runDependentRun][0] = CloneEmptyHistogram(
p.first,-1);
2249 unprescaledLumi = m_triggerObjs[
"None"]->triggerHists[-runDependentRun][0].get();
2251 if( (m_unrepresentedDataAction==1) &&
p.second->inputBinRedirect[
bin]!=
bin) { }
2252 else if( m_unrepresentedDataAction==3 ) {unprescaledLumi->Fill(unprescaledLumi->GetBinCenter(
p.second->inputBinRedirect[
bin]), intLumi);}
2253 else unprescaledLumi->Fill(
mu*m_dataScaleFactorX,intLumi);
2277 std::unique_ptr<CP::TPileupReweighting::CompositeTrigger>
2280 if( m_debugging && m_printInfo ) {
2281 Info(
"makeTrigger",
"Doing %s",
s.Data() );
2286 std::unique_ptr< CompositeTrigger > cOper1;
2287 if(
s.BeginsWith(
"(" ) ) {
2289 int bCounter=1;
int i=1;
2290 while( ( bCounter != 0 ) && (
i <=
s.Length() ) ) {
2291 if(
s(
i ) ==
'(' ) {
2293 }
else if(
s(
i ) ==
')' ) {
2298 if( bCounter != 0 ) {
2299 Error(
"makeTrigger",
"Missing closing bracket" );
2300 return std::unique_ptr< CompositeTrigger >();
2302 oper1 =
s( 1,
i - 2 );
2303 if(
i ==
s.Length() + 1 ) {
2304 return makeTrigger( oper1 );
2306 cOper1 = makeTrigger( oper1 );
2315 int i=0;
int bCounter=0;
int op=0;
2316 while(
i <=
s.Length() ) {
2317 if(
s(
i ) ==
'(' ) {
2319 }
else if(
s(
i ) ==
')' ) {
2321 }
else if( (
s(
i ) ==
'&' ) && ( bCounter == 0 ) ) {
2324 }
else if( (
s(
i ) ==
'|' ) && ( bCounter == 0 ) ) {
2333 if( m_lumicalcFiles.find(
s ) == m_lumicalcFiles.end() ) {
2334 Error(
"GetDataWeight",
"Could not find subTrigger %s",
s.Data() );
2335 return std::unique_ptr< CompositeTrigger >();
2340 auto out = std::make_unique< CompositeTrigger >();
2346 auto out = std::make_unique< CompositeTrigger >();
2351 out->trig1 = std::move( cOper1 );
2354 out->trig1 = makeTrigger( oper1 );
2355 if( !
out->trig1 ) {
2356 return std::unique_ptr< CompositeTrigger >();
2359 TString oper2 =
s(
i + 1,
s.Length() );
2360 out->trig2 = makeTrigger( oper2 );
2361 if( !
out->trig2 ) {
2362 return std::unique_ptr< CompositeTrigger >();
2371 while( j <=
s.Length() ) {
2372 if(
s( j ) ==
'(' ) {
2374 }
else if(
s( j )==
')' ) {
2376 }
else if( (
s( j ) ==
'|' ) && ( bCounter == 0 ) ) {
2382 if( ( j ==
s.Length() + 1 ) && ( op == 2 ) ) {
2384 out->trig1 = std::move( cOper1 );
2387 out->trig1 = makeTrigger( oper1 );
2389 TString oper2 =
s(
i + 1,
s.Length() );
2390 if( m_debugging && m_printInfo ) {
2391 Info(
"makeTrigger",
"Found & %s %s", oper1.Data(), oper2.Data() );
2393 out->trig2 = makeTrigger( oper2 );
2394 if( !
out->trig2 ) {
2395 return std::unique_ptr< CompositeTrigger >();
2398 }
else if( op ==1 ) {
2401 TString oper2 =
s( j + 1,
s.Length() );
2402 if( m_debugging && m_printInfo ) {
2403 Info(
"makeTrigger",
"Found & then | %s %s", oper1.Data(),
2407 out->trig1 = makeTrigger( oper1 );
2408 if( !
out->trig1 ) {
2409 return std::unique_ptr< CompositeTrigger >();
2411 out->trig2 = makeTrigger( oper2 );
2412 if( !
out->trig2 ) {
2413 return std::unique_ptr< CompositeTrigger >();
2417 Error(
"makeTrigger",
"Should never have got here!, but did with %s",
2419 return std::unique_ptr< CompositeTrigger >();