ATLAS Offline Software
Loading...
Searching...
No Matches
CP::PileupReweightingTool Class Reference

Implementation of the PileupReweighting tool. More...

#include <PileupReweightingTool.h>

Inheritance diagram for CP::PileupReweightingTool:

Public Member Functions

virtual UInt_t GetRandomLumiBlockNumber (UInt_t runNumber)
 Get a random lumiblock number for the given run number.
virtual Double_t GetIntegratedLumi (UInt_t start, UInt_t end)
 Get the integrated luminosity (in pb-1) between start and end run (inclusive).
virtual Double_t GetIntegratedLumi (const TString &trigger)
 Total lumi (in pb-1) for a given trigger combination .. leave blank for the unprescaled.
virtual Double_t GetIntegratedLumi (Int_t periodNumber, UInt_t start, UInt_t end)
 similar to above, but for only the given mcRunNumber/periodNumber
virtual Double_t GetIntegratedLumiFraction (Int_t periodNumber, UInt_t start, UInt_t end)
 return fraction of lumi assigned to periodNumber (or mcRunNumber) that is between start and end data run numbers
virtual Double_t GetIntegratedLumiFraction (Int_t periodNumber, Double_t mu, UInt_t start, UInt_t end)
 return fraction of lumi assigned to periodNumber (or mcRunNumber) with given mu, that is between start and end data run numbers
virtual Int_t AddPeriod (Int_t periodNumber, UInt_t start, UInt_t end)
 use these methods when generating config files
virtual Int_t SetBinning (Int_t nbinsx, Double_t *xbins, Int_t nbinsy=0, Double_t *ybins=0)
virtual Int_t SetUniformBinning (Int_t nbinsx, Double_t xlow, Double_t xup, Int_t nbinsy=0, Double_t ylow=0, Double_t yup=0)
virtual Int_t SetBinning (TH1 *hist)
virtual Double_t GetSumOfEventWeights (Int_t channel)
 helpful alternative to using the EventBookkeepers info ... assuming you made your PRW Config file!!
virtual Double_t GetNumberOfEvents (Int_t channel)
 PileupReweightingTool (const std::string &name)
 Constructor for standalone usage.
virtual StatusCode initialize ()
 Function initialising the tool.
virtual StatusCode finalize ()
 Finalize - can call the WriteToFile for us.
virtual StatusCode apply (const xAOD::EventInfo &eventInfo, bool mu_dependent)
 Decorates with: MC: PileupWeight (CombinedWeight[*UnrepresentedDataWeight if action=2]), RandomRunNumber, RandomLumiBlockNumber Data: corrected_averageInteractionsPerCrossing mu_dependent says if the mu_dependency should be used for random run numbers or the data weights.
virtual float getCombinedWeight (const xAOD::EventInfo &eventInfo, bool correctUnrepresented)
 Return combined pileup weight.
virtual float getCombinedWeight (const xAOD::EventInfo &eventInfo, Double_t x, Double_t y, bool correctUnrepresented)
 Same as above, but for a 'custom weight' variable.
virtual float getCombinedWeight (const xAOD::EventInfo &eventInfo, const TString &trigger, bool mu_dependent, bool correctUnrepresented)
 get combined weight (i.e. pileup weight) but with a 1./dataWeight factor applied, this if used for 'prescaling' MC
virtual ULong64_t getPRWHash (const xAOD::EventInfo &eventInfo)
 return the prw hash used for fast updates of weights at the post-processing level ... see the share/makeWeightTree.C script for usage
virtual float getCorrectedAverageInteractionsPerCrossing (const xAOD::EventInfo &eventInfo, bool includeDataScaleFactor)
 Get the mu of a lumiblock ... needed to 'correct' the number in datasets.
virtual float getCorrectedActualInteractionsPerCrossing (const xAOD::EventInfo &eventInfo, bool includeDataScaleFactor)
 Get the corrected 'actual' interactions per crossing.
virtual double getLumiBlockIntegratedLumi (const xAOD::EventInfo &eventInfo)
 Get the integrated lumi of a lumiblock (in pb-1).
virtual float getUnrepresentedDataWeight (const xAOD::EventInfo &eventInfo)
 When using UnrepresentedDataAction=2, you may want to apply this additional weight to ensure sum of weights are preserved.
virtual float getDataWeight (const xAOD::EventInfo &eventInfo, const TString &trigger, bool mu_dependent)
 Get the dataWeight used to 'unprescale' data collected from a given trigger combination. mu_dependency is recommended to be true.
virtual float getPrescaleWeight (const xAOD::EventInfo &eventInfo, const TString &trigger, bool mu_dependent)
 Get weight used to 'prescale' Monte Carlo for given trigger comibnation.
virtual int getRandomRunNumber (const xAOD::EventInfo &eventInfo, bool mu_dependent)
 Get a random run number for this MC event, using mu-dependent randomization by default ... jetetmiss seem to like it muchly.
virtual int fill (const xAOD::EventInfo &eventInfo)
 Call this method once per event when in config file generating mode and you want standard mu reweighting.
virtual int fill (const xAOD::EventInfo &eventInfo, Double_t x, Double_t y)
 Use this method if you want to do a generic reweighting instead.
virtual CP::TPileupReweightingexpert ()
 Get pointer to the underlying tool - expert use only. Will require #include "PileupReweighting/TPileupReweighting.h".
bool isAffectedBySystematic (const CP::SystematicVariation &systematic) const
 The ISystematicsTool methods.
CP::SystematicSet affectingSystematics () const
 the list of all systematics this tool can be affected by
CP::SystematicSet recommendedSystematics () const
 the list of all systematics this tool recommends to use
StatusCode applySystematicVariation (const CP::SystematicSet &systConfig)
 effects: configure this tool for the given list of systematic variations.
void updateHandler (Gaudi::Details::PropertyBase &)
Int_t Merge (TCollection *coll)
virtual void print () const
 Print the state of the tool.
ServiceHandle< StoreGateSvc > & evtStore ()
 The standard StoreGateSvc (event store) Returns (kind of) a pointer to the StoreGateSvc.
const ServiceHandle< StoreGateSvc > & detStore () const
 The standard StoreGateSvc/DetectorStore Returns (kind of) a pointer to the StoreGateSvc.
virtual StatusCode sysInitialize () override
 Perform system initialization for an algorithm.
virtual StatusCode sysStart () override
 Handle START transition.
virtual std::vector< Gaudi::DataHandle * > inputHandles () const override
 Return this algorithm's input handles.
virtual std::vector< Gaudi::DataHandle * > outputHandles () const override
 Return this algorithm's output handles.
Gaudi::Details::PropertyBase & declareProperty (Gaudi::Property< T, V, H > &t)
void updateVHKA (Gaudi::Details::PropertyBase &)
MsgStream & msg () const
bool msgLvl (const MSG::Level lvl) const
virtual float getCorrectedMu (const xAOD::EventInfo &eventInfo, bool includedDataScaleFactor=false)
 Get the corrected average mu of a lumiblock ... (averaging is over all filled BCID in the fill) The additional flag indicates if the returned value should include the data scale factor or not.
Additional helper functions, not directly mimicking Athena
template<class T>
const T * getProperty (const std::string &name) const
 Get one of the tool's properties.
const std::string & msg_level_name () const __attribute__((deprecated))
 A deprecated function for getting the message level's name.
const std::string & getName (const void *ptr) const
 Get the name of an object that is / should be in the event store.
SG::sgkey_t getKey (const void *ptr) const
 Get the (hashed) key of an object that is in the event store.

Static Public Member Functions

static Version_t Class_Version ()

Protected Member Functions

virtual bool runLbnOK (Int_t runNbr, Int_t lbn)
virtual bool passTriggerBeforePrescale (const TString &trigger) const
void renounceArray (SG::VarHandleKeyArray &handlesArray)
 remove all handles from I/O resolution
std::enable_if_t< std::is_void_v< std::result_of_t< decltype(&T::renounce)(T)> > &&!std::is_base_of_v< SG::VarHandleKeyArray, T > &&std::is_base_of_v< Gaudi::DataHandle, T >, void > renounce (T &h)
void extraDeps_update_handler (Gaudi::Details::PropertyBase &ExtraDeps)
 Add StoreName to extra input/output deps as needed.
Int_t UsePeriodConfig (const TString &configName)
 use a hardcoded period configuration
void SetDefaultChannel (Int_t channel, Int_t mcRunNumber=-1)
 Set which channel should be used as a default when specific mc channel distributions cannot be found.
Int_t GetDefaultChannel (Int_t mcRunNumber=-1)
void RemapPeriod (Int_t periodNumber1, Int_t periodNumber2)
 Combine two period numbers.
Double_t GetLumiBlockIntegratedLumi (Int_t runNumber, UInt_t lb)
 get integrated lumi for specific run and lumiblock number .
Float_t GetLumiBlockMu (Int_t runNumber, UInt_t lb)
 get the lumiblock mu, useful for 'updating' the mu coming from data to account for new lumitags
void DisableWarnings (Bool_t in)
 Indicate if warnings should be suppressed.
void EnableDebugging (Bool_t in)
 Indicate if additional debugging information should be output.
void PrintInfo (Bool_t in)
 disable info
void SetUnrepresentedDataAction (Int_t action, Double_t tolerance=0.05)
 Set how to handle configurations where some of your data has no corresponding mc to describe it 0=Default (Throw exception), 1=Subtract lumi from normalizations (i.e.
Double_t GetUnrepresentedDataFraction (Int_t periodNumber, Int_t channel)
 return the unrepresented data fraction in a given channel .
Float_t GetUnrepresentedDataWeight (Int_t periodNumber, Int_t channel)
Bool_t IsUnrepresentedData (Int_t runNumber, Float_t x, Float_t y=0.)
void IgnoreConfigFilePeriods (Bool_t in)
 Should the tool ignore period assignments encoded in config file.
Int_t GetFirstFoundPeriodNumber (UInt_t runNumber)
 Get the first period number with the data run number contained - assume all periods are disconnected for this to be useful.
void SetDataScaleFactors (Float_t x, Float_t y=1.)
 Scale the LumiMetaData mu values by this factor.
void SetMCScaleFactors (Float_t x, Float_t y=1.)
Int_t AddConfigFile (const TString &fileName)
Int_t AddLumiCalcFile (const TString &fileName, const TString &trigger="None")
Int_t AddMetaDataFile (const TString &fileName, const TString &channelBranchName="mc_channel_number")
Bool_t RemoveChannel (int chanNum)
 Removes a channel from the inputs ... this is for experts only.
Int_t Initialize ()
 Initialize this class once before the event loop starts If distribution information is provided, it is assumed to be for the standard pileup reweighting.
Float_t GetCombinedWeight (Int_t periodNumber, Int_t channelNumber, Float_t x, Float_t y=0.)
Float_t GetPeriodWeight (Int_t periodNumber, Int_t channelNumber)
Float_t GetPrimaryWeight (Int_t periodNumber, Int_t channelNumber, Float_t x)
Float_t GetSecondaryWeight (Int_t periodNumber, Int_t channelNumber, Float_t x, Float_t y)
Double_t GetMetaData (const TString &metadataName, Int_t channelNumber)
TTree * GetMetaDataTree ()
 combines loaded metadata with channel sumsofweights and entry counts
Int_t GenerateMetaDataFile (const TString &fileName, const TString &channelBranchName="mc_channel_number")
Int_t Fill (Int_t runNumber, Int_t channelNumber, Float_t w, Float_t x, Float_t y=0.)
Int_t WriteToFile (const TString &filename="")
Int_t WriteToFile (TFile *outFile)
ULong64_t GetPRWHash (Int_t periodNumber, Int_t channelNumber, Float_t x, Float_t y=0.)
Bool_t MakeWeightTree (TString channelNumbers, TString outFile, TString hashBranch="PRWHash", TString weightBranch="PileupWeight")
void SetRandomSeed (int seed)
int GetRandomSeed ()
UInt_t GetRandomRunNumber (Int_t mcRunNumber)
 Gets a random data run number according to the integrated lumi distribution associated to this mcRunNumber.
UInt_t GetRandomRunNumber (Int_t mcRunNumber, Double_t mu)
 Get random run number according to integrated lumi distribution for the given mu value (uses the binning of the mu histogram).
Int_t GetRandomPeriodNumber (Int_t mcRunNumber)
 Get random period number from the sub-periods assigned to this run number.
std::vector< intGetPeriodNumbers () const
TH1 * GetInputHistogram (Int_t channelNumber, Int_t periodNumber)
TH1 * GetPrimaryDistribution (Int_t channelNumber, Int_t periodNumber)
TH1 * GetPrimaryTriggerDistribution (const TString &trigger, Int_t periodNumber, long triggerBits)
Double_t GetDataWeight (Int_t runNumber, const TString &trigger, Double_t x, bool run_dependent=false)
 Method for weighting data to account for prescales and mu bias.
Double_t GetDataWeight (Int_t runNumber, const TString &trigger)
Double_t GetPrescaleWeight (Int_t runNumber, const TString &trigger, Double_t x, bool run_dependent=false)
 Method for prescaling MC to account for prescales in data.
Double_t GetPrescaleWeight (Int_t runNumber, const TString &trigger)
Bool_t IsInitialized ()
Int_t AddDistribution (TH1 *hist, Int_t runNumber, Int_t channelNumber)
void ResetCountingMode ()
 This method is DEFINITELY EXPERT USE ONLY.
void SetParentTool (TPileupReweighting *tool)
Float_t GetDataScaleFactor () const
void SetTriggerBit (const TString &trigger, bool in=true)
void ResetTriggerBits ()
double GetRunAverageMu (int run)
Int_t GetNearestGoodBin (Int_t thisMCRunNumber, Int_t bin)
Int_t IsBadBin (Int_t thisMCRunNumber, Int_t bin)
std::unique_ptr< TH1 > CloneEmptyHistogram (Int_t runNumber, Int_t channelNumber)
void normalizeHistogram (TH1 *histo)
 Normalize histograms.
void AddDistributionTree (TTree *tree, TFile *file)
void CalculatePrescaledLuminosityHistograms (const TString &trigger, int run_dependent=0)
std::unique_ptr< CompositeTriggermakeTrigger (const TString &s)
void calculateHistograms (CompositeTrigger *trigger, int run_dependent)
void PrintPeriods ()
std::map< UInt_t, Run > & GetRunMap ()
void CopyProperties (const TPileupReweighting *in)

Protected Attributes

std::map< TString, boolm_triggerPassBits
TPileupReweightingm_parentTool
Bool_t m_SetWarnings
Bool_t m_debugging
Bool_t m_printInfo
Bool_t m_countingMode
Int_t m_unrepresentedDataAction
Bool_t m_isInitialized
Bool_t m_lumiVectorIsLoaded
Float_t m_dataScaleFactorX
Float_t m_dataScaleFactorY
Float_t m_mcScaleFactorX
Float_t m_mcScaleFactorY
Int_t m_nextPeriodNumber
Bool_t m_ignoreFilePeriods
TTree * m_metadatatree
Double_t m_unrepDataTolerance
Double_t m_unrepDataWarningThreshold {0.0}
Bool_t m_doGlobalDataWeight
Bool_t m_doPrescaleWeight = false
Int_t m_lumicalcRunNumberOffset
std::map< TString, std::vector< TString > > m_lumicalcFiles
 map storing the lumicalc file locations - used when building DataPileupWeights
std::unique_ptr< TH1 > m_emptyHistogram
 the empty histogram used for this weight... effectively holds the configuration of the binning
std::map< TString, std::map< Int_t, Double_t > > m_metadata
 channel metadata map
std::map< TString, std::unique_ptr< CompositeTrigger > > m_triggerObjs
std::list< Periodm_periodList
 List physically holding (owning) period objects.
std::map< Int_t, Period * > m_periods
std::map< UInt_t, Runm_runs
std::map< Int_t, Double_t > unrepDataByChannel
std::string m_prwFilesPathPrefix
std::unique_ptr< TRandom3 > m_random3
Bool_t m_ignoreBadChannels
Bool_t m_useMultiPeriods = true
int m_autoRunStart = 0
int m_autoRunEnd = 0

Private Types

typedef ServiceHandle< StoreGateSvcStoreGateSvc_t

Private Member Functions

Gaudi::Details::PropertyBase & declareGaudiProperty (Gaudi::Property< T, V, H > &hndl, const SG::VarHandleKeyType &)
 specialization for handling Gaudi::Property<SG::VarHandleKey>

Private Attributes

std::string m_configStream
bool m_inConfigMode
std::unique_ptr< CP::TPileupReweightingm_upTool
std::unique_ptr< CP::TPileupReweightingm_downTool
double m_upVariation
double m_downVariation
CP::SystematicVariation m_systUp
CP::SystematicVariation m_systDown
CP::TPileupReweightingm_activeTool
std::vector< std::string > m_prwFiles
std::vector< std::string > m_toolLumicalcFiles
std::string m_prefix
int m_defaultChannel
std::string m_usePeriodConfig
std::map< int, boolm_doneConfigs
bool m_noWeightsMode
bool m_varyRunNumber
bool m_useRunDependentPrescaleWeight
std::vector< intm_customPeriods
 Default weight tool in standalone mode.
std::unique_ptr< IWeightToolm_defaultWeightTool
ToolHandle< IWeightToolm_weightTool
ToolHandle< IGoodRunsListSelectionToolm_grlTool
ToolHandle< Trig::ITrigDecisionToolm_tdt
StoreGateSvc_t m_evtStore
 Pointer to StoreGate (event store by default).
StoreGateSvc_t m_detStore
 Pointer to StoreGate (detector store by default).
std::vector< SG::VarHandleKeyArray * > m_vhka
bool m_varHandleArraysDeclared

Detailed Description

Implementation of the PileupReweighting tool.

Author
Will Buttinger

Definition at line 33 of file PileupReweightingTool.h.

Member Typedef Documentation

◆ StoreGateSvc_t

typedef ServiceHandle<StoreGateSvc> AthCommonDataStore< AthCommonMsg< AlgTool > >::StoreGateSvc_t
privateinherited

Definition at line 388 of file AthCommonDataStore.h.

Constructor & Destructor Documentation

◆ PileupReweightingTool()

CP::PileupReweightingTool::PileupReweightingTool ( const std::string & name)

Constructor for standalone usage.

Definition at line 34 of file PileupReweightingTool.cxx.

34 :CP::TPileupReweighting(name.c_str()), asg::AsgTool( name ),
35 m_inConfigMode(false),
36 m_upTool(), m_downTool(), m_systUp("PRW_DATASF", 1 ), m_systDown("PRW_DATASF", -1),
37 m_activeTool(this),
38 m_noWeightsMode(false),
39#ifdef XAOD_STANDALONE
40 m_defaultWeightTool( new McEventWeight( "DefaultWeightTool" ) ),
41#endif // XAOD_STANDALONE
42 m_weightTool("McEventWeight/myWeightTool"),
43 m_grlTool(""), m_tdt("") {
44
46
47#ifndef XAOD_STANDALONE
48 declareProperty("ConfigOutputStream", m_configStream="", "When creating PRW config files, this is the THistSvc stream it goes into. If blank, it wont write this way");
49#endif
50
51 declareProperty("ConfigFiles", m_prwFiles, "List of prw config files"); //array of files
52 declareProperty("ConfigFilesPathPrefix", m_prwFilesPathPrefix="", "Path of additional folder structure in prw config files"); //string prefix
53 declareProperty("LumiCalcFiles", m_toolLumicalcFiles, "List of lumicalc files, in the format '<filename>:<trigger>' .. if no trigger given, 'None' is assumed"); //array of files
54 declareProperty("Prefix",m_prefix="","Prefix to attach to all decorations ... only used in the 'apply' method");
55 declareProperty("UnrepresentedDataAction",m_unrepresentedDataAction=3,"1 = remove unrepresented data, 2 = leave it there, 3 = reassign it to nearest represented bin");
56 declareProperty("UnrepresentedDataThreshold",m_unrepDataTolerance=0.05,"When unrepresented data is above this level, will require the PRW config file to be repaired");
57 declareProperty("UnrepresentedDataWarningThreshold",
59 "Suppress the unrepresented-data WARNING when the"
60 " unrepresented fraction is below this value."
61 " Default 0 means always warn (preserving the"
62 " existing behaviour).");
63 declareProperty("UseMultiPeriods",m_useMultiPeriods=true,"If true, will try to treat each mc runNumber in a single mc dataset (channel) as a modelling a distinct period of data taking");
64 declareProperty("UseRunDependentPrescaleWeight",m_useRunDependentPrescaleWeight=false,"If true, prescale weights in the getCombinedWeight method with Trigger string are determined with the specific random run number");
65 declareProperty("DataScaleFactor",m_dataScaleFactorX=1./1.03);
66 declareProperty("UsePeriodConfig",m_usePeriodConfig="auto","Use this period configuration when in config generating mode. Set to 'auto' to auto-detect");
67 declareProperty("IgnoreBadChannels",m_ignoreBadChannels=true,"If true, will ignore channels with too much unrepresented data, printing a warning for them");
68 declareProperty("DataScaleFactorUP",m_upVariation=1./0.99,"Set to a value representing the 'up' fluctuation - will report a PRW_DATASF uncertainty to Systematic Registry");
69 declareProperty("DataScaleFactorDOWN",m_downVariation=1./1.07,"Set to a value representing the 'down' fluctuation - will report a PRW_DATASF uncertainty to Systematic Registry");
70 declareProperty("VaryRandomRunNumber",m_varyRunNumber=false,"If true, then when doing systematic variations, RandomRunNumber will fluctuate as well. Off by default as believed to lead to overestimated uncertainties");
71 declareProperty("PeriodAssignments", m_customPeriods={284500,222222,324300,300000,324300,344495,310000,344496,367384,410000,422633,440613,450000,450360,461002,470000,473235,486706,495000,497924,999999}, "Specify period number assignments to run numbers ranges - this is usually an expert option");
72 declareProperty("GRLTool", m_grlTool, "If you provide a GoodRunsListSelectionTool, any information from lumicalc files will be automatically filtered" );
73 declareProperty("TrigDecisionTool",m_tdt, "When using the getDataWeight method, the TDT will be used to check decisions before prescale. Alternatively do expert()->SetTriggerBit('trigger',0) to flag which triggers are not fired before prescale (assumed triggers are fired if not specified)");
74
75#ifdef XAOD_STANDALONE
77 "The tool to compute the weight in the sumOfWeights" );
78#else
79 declareProperty( "WeightTool", m_weightTool,
80 "The tool to compute the weight in the sumOfWeights" );
81#endif
82
83#ifndef XAOD_STANDALONE
84 //attached update handler to the outputlevel property, so we can pass changes on to the underlying tool
85 auto props = getProperties();
86 for( Gaudi::Details::PropertyBase* prop : props ) {
87 if( prop->name() != "OutputLevel" ) {
88 continue;
89 }
90 prop->declareUpdateHandler( &PileupReweightingTool::updateHandler, this );
91 break;
92 }
93#endif
94}
Gaudi::Details::PropertyBase & declareProperty(Gaudi::Property< T, V, H > &t)
ToolHandle< Trig::ITrigDecisionTool > m_tdt
std::unique_ptr< IWeightTool > m_defaultWeightTool
std::vector< std::string > m_prwFiles
std::vector< int > m_customPeriods
Default weight tool in standalone mode.
std::unique_ptr< CP::TPileupReweighting > m_upTool
void updateHandler(Gaudi::Details::PropertyBase &)
ToolHandle< IWeightTool > m_weightTool
CP::SystematicVariation m_systDown
std::vector< std::string > m_toolLumicalcFiles
std::unique_ptr< CP::TPileupReweighting > m_downTool
CP::TPileupReweighting * m_activeTool
ToolHandle< IGoodRunsListSelectionTool > m_grlTool
CP::SystematicVariation m_systUp

Member Function Documentation

◆ AddConfigFile()

Int_t TPileupReweighting::AddConfigFile ( const TString & fileName)
inherited

Definition at line 936 of file TPileupReweighting.cxx.

936 {
937
938 //open the file and look for config TTrees
939 //recognised TTrees are: ChannelMetaData, MCPileupReweighting, MCCustomReweighting, DataCustomReweighting
940
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!");
944 }
945
946 TDirectory* origDir = gDirectory;
947 // Load the data ROOT file
948 TFile* rootFile = TFile::Open( fileName, "READ" );
949 if ( rootFile->IsZombie() ) {
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);
953 } else {
954 //try to get the the known TTrees
955 TTree *tmp = (TTree*)rootFile->Get( std::string(m_prwFilesPathPrefix+"MCPileupReweighting").c_str() );
956 if(tmp) {
957 //Info("AddConfigFile","Adding MCPileupReweighting...");
958 AddDistributionTree(tmp,rootFile);
959 m_countingMode=false;
960 }
961 tmp = 0;tmp = (TTree*)rootFile->Get( std::string(m_prwFilesPathPrefix+"MCCustomReweighting").c_str() );
962 if(tmp) {
963 //Info("AddConfigFile","Adding MCCustomReweighting...");
964 AddDistributionTree(tmp,rootFile);
965 m_countingMode=false;
966 }
967 tmp = 0;tmp = (TTree*)rootFile->Get( std::string(m_prwFilesPathPrefix+"DataCustomReweighting").c_str() );
968 if(tmp) {
969 //Info("AddConfigFile","Adding DataCustomReweighting...");
970 AddDistributionTree(tmp,rootFile);
971 m_countingMode=false;
972 }
973 tmp=0; tmp = (TTree*)rootFile->Get( std::string(m_prwFilesPathPrefix+"PileupReweighting/MCPileupReweighting").c_str() ); //allow trees in the PileupReweighting dir instead
974 if(tmp) {
975 //Info("AddConfigFile","Adding MCPileupReweighting...");
976 AddDistributionTree(tmp,rootFile);
977 m_countingMode=false;
978 }
979 tmp = 0;tmp = (TTree*)rootFile->Get( std::string(m_prwFilesPathPrefix+"PileupReweighting/MCCustomReweighting").c_str() );
980 if(tmp) {
981 //Info("AddConfigFile","Adding MCCustomReweighting...");
982 AddDistributionTree(tmp,rootFile);
983 m_countingMode=false;
984 }
985 tmp = 0;tmp = (TTree*)rootFile->Get( std::string(m_prwFilesPathPrefix+"PileupReweighting/DataCustomReweighting").c_str() );
986 if(tmp) {
987 //Info("AddConfigFile","Adding DataCustomReweighting...");
988 AddDistributionTree(tmp,rootFile);
989 m_countingMode=false;
990 }
991 }
992
993 delete rootFile;
994
995 // Return to the original ROOT directory
997
998 return 0;
999}
void AddDistributionTree(TTree *tree, TFile *file)
Error
The different types of error that can be flagged in the L1TopoRDO.
Definition Error.h:16

◆ AddDistribution()

Int_t TPileupReweighting::AddDistribution ( TH1 * hist,
Int_t runNumber,
Int_t channelNumber )
inherited

Definition at line 728 of file TPileupReweighting.cxx.

728 {
729
730 //NOTE: should probably just ignore histograms with 0 entries
731
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!");
735 }
736
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");
740 }
741
742 if(!m_useMultiPeriods && runNumber>=0) {
743 //not allowing multi periods in a single channel, so before we go any further, require no periods other than this incoming one to have a hist defined for this channel
744 //the global one can though
745 for(auto& period : m_periods) {
746 if(period.first<0) continue; //global sum period
747 if(period.first==runNumber) continue; //ok to add to this
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());
752 }
753 }
754 }
755
756
757 auto& inputHist = (channelNumber<0) ? m_runs[runNumber].inputHists["None"] : m_periods[runNumber]->inputHists[channelNumber];
758
759 if(!inputHist) {
760 //if no emptyHistogram specified, we will use this histogram as the structure for the empty;
761 if(!m_emptyHistogram) {
762 //check if the input histogram is a TH1D or not. We like TH1D, not yucky TH1F
763 if(strcmp(hist->IsA()->GetName(),"TH1D")==0 || strcmp(hist->IsA()->GetName(),"TH2D")==0) {
764 m_emptyHistogram.reset( dynamic_cast<TH1*>(hist->Clone("default")) );
765 } else {
766 //check dimensionality
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));
770 TH1D tmpHist("tmpHist","tmpHist",binsX.size()-1,&binsX[0]);
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));
776 TH2D tmpHist("tmpHist","tmpHist",binsX.size()-1,&binsX[0],binsY.size()-1,&binsY[0]);
777 m_emptyHistogram.reset( dynamic_cast<TH1*>(tmpHist.Clone("default")) );
778 } else {
779 Error("AddDistribution","Unknown input histogram dimensionality: %d",hist->GetDimension());
780 throw std::runtime_error("Throwing 98");
781 }
782 }
784 {
785 m_emptyHistogram->Reset();m_emptyHistogram->SetEntries(0);m_emptyHistogram->SetDirectory(0);//clear the histogram
786 }
787 }
788 inputHist = CloneEmptyHistogram(runNumber,channelNumber);
789
790 }
791
792
793 //iterator over bins of histogram, filling the TH1 stored in the data map
794 Double_t numEntries = inputHist->GetEntries();
795
796 std::unique_ptr<TH1> tmpHist;
797 if(channelNumber<0) {
798 m_runs[runNumber].nominalFromHists = true;
799 //for data we will do an interpolation to build the shape and then scale it to the integral ...
800 tmpHist.reset( static_cast<TH1*>(inputHist->Clone("tmpHist")) );
801 tmpHist->Reset();
802 Int_t bin,binx,biny;
803 for(biny=1; biny<=tmpHist->GetNbinsY(); biny++) {
804 for(binx=1; binx<=tmpHist->GetNbinsX(); binx++) {
805 bin = tmpHist->GetBin(binx,biny);
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){
809 tmpHist->SetBinContent(bin, hist->Interpolate(x));
810 } else {
811 tmpHist->SetBinContent(bin, hist->Interpolate(x,y));
812 }
813 }
814 }
815 tmpHist->Scale( hist->Integral() / tmpHist->Integral() );
816 tmpHist->SetEntries( hist->GetEntries() );
817 hist = tmpHist.get();
818 }
819
820 Int_t bin,binx,biny;
821 for(biny=1; biny<=hist->GetNbinsY(); biny++) {
822 for(binx=1; binx<=hist->GetNbinsX(); binx++) {
823 bin = hist->GetBin(binx,biny);
824 Double_t value = hist->GetBinContent(bin);
825 Double_t x = hist->GetXaxis()->GetBinCenter(binx);
826 Double_t y = hist->GetYaxis()->GetBinCenter(biny);
827 //shift x,y,z by the MCScaleFactors as appropriate
828 if(channelNumber>=0) {x *= m_mcScaleFactorX; y *= m_mcScaleFactorY;}
829 //data scale factor now dealt with in above interpolation
830 Int_t inBin = inputHist->FindFixBin(x,y);
831 Double_t inValue = inputHist->GetBinContent(inBin);
832 inputHist->SetBinContent(inBin,inValue+value);
833 }
834 }
835
836 //also keep track of the number of entries
837 //SetBinContent screws with the entry count, so had to record it before the loops above
838 inputHist->SetEntries(numEntries+hist->GetEntries());
839
840
841 m_countingMode=false;
842 return 0;
843
844}
#define y
#define x
std::map< UInt_t, Run > m_runs
std::map< Int_t, Period * > m_periods
std::unique_ptr< TH1 > m_emptyHistogram
the empty histogram used for this weight... effectively holds the configuration of the binning
std::unique_ptr< TH1 > CloneEmptyHistogram(Int_t runNumber, Int_t channelNumber)
tmpHist(what, wmin=-1e10, wmax=+1e10)
Definition fitman.py:146

◆ AddDistributionTree()

void TPileupReweighting::AddDistributionTree ( TTree * tree,
TFile * file )
protectedinherited

Definition at line 648 of file TPileupReweighting.cxx.

648 {
649
650 bool isMC=true;
651 //should have the standard structure
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();
657 Char_t histName[150];
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;}
661 else {
662 if(tree->SetBranchAddress("CustomName",&customName)!=0) {
663 Error("AddDistributionTree","Could not find CustomName branch in TTree");throw std::runtime_error("Throwing 18");
664 }
665 }
666 if(strcmp(tree->GetName(),"DataCustomReweighting")==0) {channel=-1;isMC=false;}
667 else {
668 if(tree->SetBranchAddress("Channel",&channel)!=0) {
669 Error("AddDistributionTree","Could not find Channel branch in TTree");throw std::runtime_error("Throwing 18");
670 }
671 }
672 if(tree->SetBranchAddress("RunNumber",&runNbr)!=0) {
673 Error("AddDistributionTree","Could not find RunNumber branch in TTree");throw std::runtime_error("Throwing 18");
674 }
675 if(isMC) {
676 if(tree->SetBranchAddress("PeriodStarts",&pStartsPtr)!=0) {
677 Error("AddDistributionTree","Could not find PeriodStarts branch in TTree");throw std::runtime_error("Throwing 18");
678 }
679 if(tree->SetBranchAddress("PeriodEnds",&pEndsPtr)!=0) {
680 Error("AddDistributionTree","Could not find PeriodEnds branch in TTree");throw std::runtime_error("Throwing 18");
681 }
682 if(tree->FindBranch("IsDefaultForRunNumber")!=0) {
683 tree->SetBranchAddress("IsDefaultForRunNumber",&isDefaultForRunNumber);
684 hasDefaultsBranch=true;
685 }
686 }
687
688 if(tree->SetBranchAddress("HistName",&histName)!=0) {
689 Error("AddDistributionTree","Could not find HistName branch in TTree");throw std::runtime_error("Throwing 18");
690 }
691 long n = tree->GetEntries();
692 std::map<TString,bool> loadedHistos; //avoid double-loading from this file
693 for(long i=0;i<n;i++) {
694 tree->GetEntry(i);
695 TString sHistName(histName);
696 TString weightName(customName);
697 const auto &[ptr, inserted] = loadedHistos.try_emplace(sHistName, true);
698
699 if(inserted) {
700 if(( (!m_ignoreFilePeriods) || m_periods.find(runNbr)==m_periods.end()) && isMC) {
701 //if ignoring file periods, will still add the period if it doesnt exist!
702 for(unsigned int j=0;j<pStarts->size();j++) {
703 unsigned int start = pStarts->at(j);
704 unsigned int end = pEnds->at(j);
705 AddPeriod(runNbr,start,end);
706 }
707 }
708 //load the histogram
709 TH1 *histo = (TH1*)file->Get( sHistName );
710 if(!histo) histo = (TH1*)file->Get( TString::Format("%sPileupReweighting/%s",m_prwFilesPathPrefix.c_str(),sHistName.Data()) ); //try from subdir
711 if(!histo) {
712 Error("AddDistributionTree","Unable to find the histogram %s in the File %s",sHistName.Data(),file->GetName());
713 throw std::runtime_error("Throwing 21");
714 }
715 //add it to the histograms
716 AddDistribution(histo, runNbr, channel);
717 //we also add it to the global count, if this isn't data
718 if(channel>=0) AddDistribution(histo,-1,channel);
719 }
720 if(hasDefaultsBranch) {
721 if(isDefaultForRunNumber && m_periods.find(runNbr)!=m_periods.end()) m_periods[runNbr]->defaultChannel=channel;
722 }
723 }
724
725}
Int_t AddPeriod(Int_t periodNumber, UInt_t start, UInt_t end)
Assign an mc RunNumber to a data period.
Int_t AddDistribution(TH1 *hist, Int_t runNumber, Int_t channelNumber)
float j(const xAOD::IParticle &, const xAOD::TrackMeasurementValidation &hit, const Eigen::Matrix3d &jab_inv)
void * ptr(T *p)
Definition SGImplSvc.cxx:74
TChain * tree
TFile * file

◆ AddLumiCalcFile()

Int_t TPileupReweighting::AddLumiCalcFile ( const TString & fileName,
const TString & trigger = "None" )
inherited

Definition at line 847 of file TPileupReweighting.cxx.

847 {
848
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!");
852 }
853 TDirectory* origDir = gDirectory;
854 // Load the data ROOT file
855 TFile* rootFile = TFile::Open( fileName, "READ" );
856 if ( rootFile->IsZombie() ) {
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);
860 } else {
861 //try to get the the known TTrees
862 TTree *tmp = (TTree*)rootFile->Get( "LumiMetaData" );
863 if(tmp) {
864 m_lumicalcFiles[trigger].push_back(fileName);
865 if(trigger=="None") {
866 if (m_printInfo) {
867 Info("AddLumiCalcFile","Adding LumiMetaData (scale factor=%f)...",m_dataScaleFactorX);
868 }
869 //structure expected is as given by iLumiCalc:
870 // RunNbr, AvergeInteractionPerXing, IntLumi
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");
875 }
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");
878 }
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");
881 }
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");
884 }
885 long nEntries = tmp->GetEntries();
886
887 for(long i=0;i<nEntries;i++) {
888 b_runNbr->GetEntry(i);b_intLumi->GetEntry(i);b_mu->GetEntry(i);
890 //save the lumi by run and lbn
891 b_lbn->GetEntry(i);
892
893 //before going any further, check the runnbr and lbn are ok
894 if(!m_parentTool->runLbnOK(runNbr,lbn)) continue;
895
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; //don't fill runs that we already filled from hists ... only happens for the 'None' trigger
901 }
902
903 //rescale the mu value ... do this *after* having stored the mu value in the lumiByLbn map
905 //fill into input data histograms
906 //check if we need to create an empty histogram
907
908 std::unique_ptr<TH1>& histptr = r.inputHists[trigger];
909 if (!histptr) {
910 histptr = CloneEmptyHistogram(runNbr,-1);
911 }
912 histptr->Fill(mu,intLumi);
913 }
914 m_countingMode=false;
916 } else {
917 if (m_printInfo) {
918 Info("AddLumiCalcFile","Adding LumiMetaData for DataWeight (trigger=%s) (scale factor=%f)...",trigger.Data(),m_dataScaleFactorX);
919 }
920 }
921
922 } else {
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?");
925 }
926 }
927
928 delete rootFile;
929
930 // Return to the original ROOT directory
932
933 return 0;
934}
TPileupReweighting * m_parentTool
std::map< TString, std::vector< TString > > m_lumicalcFiles
map storing the lumicalc file locations - used when building DataPileupWeights
int r
Definition globals.cxx:22
@ Info
Definition ZDCMsg.h:20

◆ AddMetaDataFile()

Int_t TPileupReweighting::AddMetaDataFile ( const TString & fileName,
const TString & channelBranchName = "mc_channel_number" )
inherited

Definition at line 506 of file TPileupReweighting.cxx.

506 {
507 TDirectory* origDir = gDirectory;
508 TTree* tmp = 0;
509 TFile* rootFile = 0;
510 if(fileName.EndsWith(".root")) {
511 //looks for ChannelMetaData ttree
512 // Load the data ROOT file
513 rootFile = TFile::Open( fileName, "READ" );
514 if ( rootFile->IsZombie() ) {
515 Error("AddMetaDataFile","Could not open file: %s",fileName.Data());
516 throw std::runtime_error("Throwing 6");
517 } else {
518 //try to get the the known TTrees
519 tmp = (TTree*)rootFile->Get( "ChannelMetaData" );
520 if(!tmp) {
521 Error("AddMetaDataFile","%s is not a valid metadata file. Should have a ChannelMetaData TTree",fileName.Data());
522 throw std::runtime_error("Throwing 7");
523 }
524 rootFile->Close();
525 }
526 delete rootFile;
527 } else {
528 //try to make the TTree by reading the file
529 tmp = new TTree("ChannelMetaData","ChannelMetaData");
530 tmp->ReadFile(fileName);
531 }
532 Int_t chanNum;
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);
538 if(leaf) {
539 TBranch *branch = leaf->GetBranch();
540 if(strcmp(branch->GetName(),channelBranchName)==0) {
541 //this is the channel branch
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");
545 }
546 branch->SetAddress(&chanNum);
547 } else if(strcmp(leaf->GetTypeName(),"Double_t")!=0) {
548 Warning("AddMetaDataFile","Cannot read non-double branch: %s",branch->GetName());
549 } else {
550 branch->SetAddress(&(data[branch->GetName()]));
551 }
552 }
553 }
554 //loop over tree entries and read in the values
555 for(Int_t i=0;i<tmp->GetEntries();++i) {
556 tmp->GetEntry(i);
557 for(std::map<TString, Double_t>::iterator it = data.begin();it!=data.end();++it) {
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);
560 }
561 m_metadata[it->first][chanNum] = it->second;
562 }
563 }
564
565 delete tmp;
566 if(rootFile) { rootFile->Close();delete rootFile;}
567
568 // Return to the original ROOT directory
570
571 return 0;
572}
char data[hepevt_bytes_allocation_ATLAS]
Definition HepEvt.cxx:11
std::map< TString, std::map< Int_t, Double_t > > m_metadata
channel metadata map

◆ AddPeriod()

virtual Int_t CP::PileupReweightingTool::AddPeriod ( Int_t periodNumber,
UInt_t start,
UInt_t end )
inlinevirtual

use these methods when generating config files

Implements CP::IPileupReweightingTool.

Definition at line 59 of file PileupReweightingTool.h.

59{ return m_activeTool->AddPeriod(periodNumber, start, end); }

◆ affectingSystematics()

CP::SystematicSet CP::PileupReweightingTool::affectingSystematics ( ) const
virtual

the list of all systematics this tool can be affected by

Implements CP::IReentrantSystematicsTool.

Definition at line 125 of file PileupReweightingTool.cxx.

125 {
126 CP::SystematicSet result;
127 if(m_upVariation) result.insert( m_systUp );
128 if(m_downVariation) result.insert( m_systDown );
129 return result;
130}

◆ apply()

StatusCode CP::PileupReweightingTool::apply ( const xAOD::EventInfo & eventInfo,
bool mu_dependent )
virtual

Decorates with: MC: PileupWeight (CombinedWeight[*UnrepresentedDataWeight if action=2]), RandomRunNumber, RandomLumiBlockNumber Data: corrected_averageInteractionsPerCrossing mu_dependent says if the mu_dependency should be used for random run numbers or the data weights.

You will get random run numbers of 0 for events with zero pileup weight

Implements CP::IPileupReweightingTool.

Definition at line 462 of file PileupReweightingTool.cxx.

462 {
463
464 if(m_inConfigMode) {
465 fill( eventInfo );
466 return StatusCode::SUCCESS;
467 }
468
469 SG::Decorator<float> corrAvgIntPerXingDec(m_prefix+"corrected_averageInteractionsPerCrossing");
471 if(!corrAvgIntPerXingDec.isAvailable(eventInfo))
472 corrAvgIntPerXingDec(eventInfo) = getCorrectedAverageInteractionsPerCrossing(eventInfo,false);
473 return StatusCode::SUCCESS;
474 }
475
476 //just copy the value over for MC
477 if(!corrAvgIntPerXingDec.isAvailable(eventInfo))
478 corrAvgIntPerXingDec(eventInfo) = eventInfo.averageInteractionsPerCrossing();
479
480 //decorate with random run number etc
481 SG::Decorator<unsigned int> rrnDec(m_prefix+"RandomRunNumber");
482 SG::ConstAccessor<unsigned int> rrnAcc(rrnDec.auxid());
483 if(!rrnDec.isAvailable(eventInfo)){
484 unsigned int rrn = getRandomRunNumber( eventInfo, mu_dependent );
485 rrnDec(eventInfo) = (rrn==0) ? getRandomRunNumber(eventInfo, false) : rrn;
486 }
487 SG::Decorator<unsigned int> rlbnDec(m_prefix+"RandomLumiBlockNumber");
488 SG::Decorator<unsigned int> rlbnAcc(rlbnDec.auxid());
489 if(!rlbnDec.isAvailable(eventInfo))
490 rlbnDec(eventInfo) = (rrnAcc(eventInfo)==0) ? 0 : /*m_tool->*/GetRandomLumiBlockNumber( rrnAcc(eventInfo) );
491 SG::Decorator<ULong64_t> prwHashDec(m_prefix+"PRWHash");
492 if(!prwHashDec.isAvailable(eventInfo))
493 prwHashDec(eventInfo) = getPRWHash( eventInfo );
494
495 //decorate with standard PileupWeight
496 SG::Decorator<float> puWeightDec(m_prefix+"PileupWeight");
497 SG::ConstAccessor<float> puWeightAcc(puWeightDec.auxid());
498 if(!m_noWeightsMode && !puWeightDec.isAvailable(eventInfo))
499 puWeightDec(eventInfo) = getCombinedWeight(eventInfo, true);
500
501 ATH_MSG_VERBOSE("PileupWeight = " << puWeightAcc(eventInfo) << " RandomRunNumber = " << rrnAcc(eventInfo) << " RandomLumiBlockNumber = " << rlbnAcc(eventInfo));
502
503 return StatusCode::SUCCESS;
504}
#define ATH_MSG_VERBOSE(x)
virtual int fill(const xAOD::EventInfo &eventInfo)
Call this method once per event when in config file generating mode and you want standard mu reweight...
virtual float getCorrectedAverageInteractionsPerCrossing(const xAOD::EventInfo &eventInfo, bool includeDataScaleFactor)
Get the mu of a lumiblock ... needed to 'correct' the number in datasets.
virtual ULong64_t getPRWHash(const xAOD::EventInfo &eventInfo)
return the prw hash used for fast updates of weights at the post-processing level ....
virtual float getCombinedWeight(const xAOD::EventInfo &eventInfo, bool correctUnrepresented)
Return combined pileup weight.
virtual UInt_t GetRandomLumiBlockNumber(UInt_t runNumber)
Get a random lumiblock number for the given run number.
virtual int getRandomRunNumber(const xAOD::EventInfo &eventInfo, bool mu_dependent)
Get a random run number for this MC event, using mu-dependent randomization by default ....
bool eventType(EventType type) const
Check for one particular bitmask value.
float averageInteractionsPerCrossing() const
Average interactions per crossing for all BCIDs - for out-of-time pile-up.
@ IS_SIMULATION
true: simulation, false: data
SG::Decorator< T, ALLOC > Decorator
Helper class to provide type-safe access to aux data, specialized for JaggedVecElt.
Definition AuxElement.h:576

◆ applySystematicVariation()

StatusCode CP::PileupReweightingTool::applySystematicVariation ( const CP::SystematicSet & systConfig)
virtual

effects: configure this tool for the given list of systematic variations.

any requested systematics that are not affecting this tool will be silently ignored (unless they cause other errors). failures: systematic unknown failures: requesting multiple variations on the same systematic (e.g. up & down) failures: requesting an unsupported variation on an otherwise supported systematic (e.g. a 2 sigma variation and the tool only supports 1 sigma variations) failures: unsupported combination of supported systematic failures: other tool specific errors

Implements CP::ISystematicsTool.

Definition at line 136 of file PileupReweightingTool.cxx.

136 {
137 if(systConfig.find( m_systUp ) != systConfig.end() && systConfig.find( m_systDown ) != systConfig.end()) {
138 ATH_MSG_ERROR("Errr... what the!? You're trying to do both PRW_DATASF directions at the same time!!!??");
139 return StatusCode::FAILURE;
140 }
141 if(systConfig.find( m_systUp ) != systConfig.end()) {
142 if(!m_upTool) { ATH_MSG_ERROR("Requested up variation of PRW_DATASF, but not configured to do this :-("); return StatusCode::FAILURE; }
143 m_activeTool = m_upTool.get();
144 }
145 else if(systConfig.find( m_systDown ) != systConfig.end() ) {
146 if(!m_downTool) { ATH_MSG_ERROR("Requested down variation of PRW_DATASF, but not configured to do this :-("); return StatusCode::FAILURE; }
147 m_activeTool = m_downTool.get();
148 }
149 else m_activeTool = this;
150 return StatusCode::SUCCESS;
151}
#define ATH_MSG_ERROR(x)
const_iterator end() const
description: const iterator to the end of the set
iterator find(const SystematicVariation &sys) const
description: find an element in the set

◆ calculateHistograms()

void TPileupReweighting::calculateHistograms ( CompositeTrigger * trigger,
int run_dependent )
protectedinherited

Definition at line 2115 of file TPileupReweighting.cxx.

2115 {
2116 TH1* unprescaledLumi = 0;
2117 if(runDependentRun) {
2118 unprescaledLumi = m_triggerObjs["None"]->triggerHists[-runDependentRun][0].get();
2119 }
2120 bool fillUnprescaledLumi = (unprescaledLumi==0); //only fill the unprescaled histogram once ... so if it already exists, it must have already been filled
2121
2122 //now we need the trigger bits for this trigger for this event
2123 long tbits = t->getBits(this);
2124 //1. Open all the lumicalc files
2125 //2. For each entry in the 'None' lumicalc file, lookup the run and lb in the subTriggers, and get the prescales (if not found, assume trigger not in, prescale=infinity)
2126 //3. perform calculation of lumi as: Lumi*(1 - Prod_triggers(1-1/prescale)) .. sum this up into the output histogram
2127 // Note: Put each lumi into the period that contains the run ( use )
2128
2129 TDirectory* origDir = gDirectory;
2130
2131 std::map<TString, std::map<Int_t, std::map<Int_t, Float_t> > > prescaleByRunAndLbn;
2132
2133 //Load the prescales for each lumicalc subTrigger
2134 for(std::vector<TString>::iterator it = t->subTriggers.begin();it!=t->subTriggers.end();++it) {
2135 //Info("aa","subtrigger %s Int lumi is %f", it->Data(), m_triggerPrimaryDistributions[*it][1]->Integral());
2136 for(auto& fileName : m_lumicalcFiles[*it]) {
2137 //if the file is also in the "None" list, then we will now the prescale must be 0
2138 //it seems that in these no-trigger files used for unprescaled lumi the prescales are all set to -1
2139 bool isUnprescaled = (std::find(m_lumicalcFiles["None"].begin(),m_lumicalcFiles["None"].end(),fileName)!=m_lumicalcFiles["None"].end());
2140
2141 TFile* rootFile = TFile::Open( fileName, "READ" );
2142 if ( rootFile->IsZombie() ) {
2143 Error("CalculatePrescaledLuminosityHistograms","Could not open file: %s",fileName.Data());
2144 std::string toThrow = "Throwing 6: Could not open file: "; toThrow += fileName.Data();
2145 throw std::runtime_error(toThrow);
2146 } else {
2147 //try to get the the known TTrees
2148 TTree *tmp = (TTree*)rootFile->Get( "LumiMetaData" );
2149 if(tmp) {
2150 //structure expected is as given by iLumiCalc:
2151 // RunNbr, AvergeInteractionPerXing, IntLumi
2152 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;
2153 if(tmp->SetBranchAddress("RunNbr",&runNbr,&b_runNbr)!=0) {
2154 Error("CalculatePrescaledLuminosityHistograms","Could not find RunNbr branch in Data TTree");throw std::runtime_error("Could not find RunNbr branch in Data TTree");
2155 }
2156 if(tmp->SetBranchAddress("L1Presc",&ps1,&b_L1Presc)!=0) {
2157 Error("CalculatePrescaledLuminosityHistograms","Could not find L1Presc branch in Data TTree");throw std::runtime_error("Could not find L1Presc branch in Data TTree");
2158 }
2159 if(tmp->SetBranchAddress("L2Presc",&ps2,&b_L2Presc)!=0) {
2160 Error("CalculatePrescaledLuminosityHistograms","Could not find L2Presc branch in Data TTree");throw std::runtime_error("Could not find L2Presc branch in Data TTree");
2161 }
2162 if(tmp->SetBranchAddress("L3Presc",&ps3,&b_L3Presc)!=0) {
2163 Error("CalculatePrescaledLuminosityHistograms","Could not find L3Presc branch in Data TTree");throw std::runtime_error("Could not find L3Presc branch in Data TTree");
2164 }
2165 if(tmp->SetBranchAddress("LBStart",&lbn,&b_lbn)!=0) {
2166 Error("CalculatePrescaledLuminosityHistograms","Could not find LBStart branch in Data TTree");throw std::runtime_error("Could not find LBStart branch in Data TTree");
2167 }
2168 long nEntries = tmp->GetEntries();
2169 for(long i=0;i<nEntries;i++) {
2170 b_runNbr->GetEntry(i);b_L1Presc->GetEntry(i);b_L2Presc->GetEntry(i);b_L3Presc->GetEntry(i);b_lbn->GetEntry(i);
2171 runNbr += m_lumicalcRunNumberOffset;
2172 if(runDependentRun && int(runNbr)!=runDependentRun) continue; //only use the given run with doing calculation run-dependently
2173 //save the prescale by run and lbn
2174 //if(runNbr==215643)
2175 if(m_debugging && m_printInfo) Info("...","prescale in [%d,%d] = %f %f %f", runNbr,lbn,ps1,ps2,ps3);
2176 if(ps1>0&&ps2>0&&ps3>0) prescaleByRunAndLbn[*it][runNbr][lbn] = ps1*ps2*ps3;
2177 else if(isUnprescaled) prescaleByRunAndLbn[*it][runNbr][lbn] = 1; //special case where the trigger is an unprescaled one and user is reusing the unprescaled lumicalc
2178 }
2179 }
2180 rootFile->Close();
2181 }
2182 delete rootFile;
2183 } //end of loop over lumicalc files for this trigger
2184 }
2185
2186 for(auto& fileName : m_lumicalcFiles["None"]) {
2187 // Load the data ROOT file for the 'None' lumicalc file
2188 TFile* rootFile = TFile::Open( fileName, "READ" );
2189 if ( rootFile->IsZombie() ) {
2190 Error("CalculatePrescaledLuminosityHistograms","Could not open file: %s",fileName.Data());
2191 std::string toThrow = "Throwing 6: Could not open file: "; toThrow += fileName.Data();
2192 throw std::runtime_error(toThrow);
2193 } else {
2194 //try to get the the known TTrees
2195 TTree *tmp = (TTree*)rootFile->Get( "LumiMetaData" );
2196 if(tmp) {
2197 //structure expected is as given by iLumiCalc:
2198 // RunNbr, AvergeInteractionPerXing, IntLumi
2199 UInt_t runNbr=0;Float_t intLumi=0;UInt_t lbn=0;TBranch *b_runNbr=0;TBranch *b_intLumi=0;TBranch *b_lbn=0;
2200 Float_t mu=0.; TBranch *b_mu=0;
2201 if(tmp->SetBranchAddress("RunNbr",&runNbr,&b_runNbr)!=0) {
2202 Error("CalculatePrescaledLuminosityHistograms","Could not find RunNbr branch in Data TTree");throw std::runtime_error("Could not find RunNbr branch in Data TTree");
2203 }
2204 if(tmp->SetBranchAddress("AvergeInteractionPerXing",&mu,&b_mu)!=0) {
2205 Error("CalculatePrescaledLuminosityHistograms","Could not find AvergeInteractionPerXing branch in Data TTree");throw std::runtime_error("Could not find AvergeInteractionPerXing branch in Data TTree");
2206 }
2207 if(tmp->SetBranchAddress("IntLumi",&intLumi,&b_intLumi)!=0) {
2208 Error("CalculatePrescaledLuminosityHistograms","Could not find IntLumi branch in Data TTree");throw std::runtime_error("Could not find IntLumi branch in Data TTree");
2209 }
2210 if(tmp->SetBranchAddress("LBStart",&lbn,&b_lbn)!=0) {
2211 Error("CalculatePrescaledLuminosityHistograms","Could not find LBStart branch in Data TTree");throw std::runtime_error("Could not find LBStart branch in Data TTree");
2212 }
2213 long nEntries = tmp->GetEntries();
2214 //this loop ends up calling the triggerBeforePrescale method each time, but this should hopefully stop once the loading is done
2215 for(long i=0;i<nEntries;i++) {
2216 b_runNbr->GetEntry(i);b_intLumi->GetEntry(i);b_mu->GetEntry(i);
2217 b_lbn->GetEntry(i);
2218
2219 runNbr += m_lumicalcRunNumberOffset;
2220 if(runDependentRun && int(runNbr)!=runDependentRun) continue; //only use the given run with doing calculation run-dependently
2221 //for each subtrigger, lookup prescale, and calculate pFactor
2222
2223 double pFactor = t->eval(prescaleByRunAndLbn,runNbr,lbn,this);
2224
2225 //Info("...","prescale in [%d,%d] = %f", runNbr,lbn,1./pFactor);
2226
2227 int bin = m_emptyHistogram->FindFixBin(mu*m_dataScaleFactorX);
2228
2229 //add into all periods that contain this runNbr
2230 bool firstFill=false;
2231 for(auto p : m_periods) {
2232 if(p.first != p.second->id) continue; //skips remappings
2233 if(!p.second->contains(runNbr)) continue;
2234 if(runDependentRun && firstFill) continue; //only fill runDependentRun once, since they aren't kept in the period they go in their own run-indexed histogram
2235
2236 int idx = (runDependentRun) ? -runDependentRun : p.second->id; //use negative runNumber to avoid clash with periodID
2237
2238
2239 auto& triggerHists = t->triggerHists[idx];
2240 std::unique_ptr<TH1>& histptr = triggerHists[tbits];
2241 if(!histptr) {
2242 histptr = CloneEmptyHistogram(p.first,-1);
2243 if(m_debugging && m_printInfo) Info("CalculatePrescaledLuminosityHistograms","Created Data Weight Histogram for [%s,%d,%d,%ld]",t->val.Data(),p.first,idx,tbits);
2244 }
2245 //check if we were about to fill a bad bin ... if we are, we either skipp the fill (unrep action=1) or redirect (unrep action=3)
2246 if( (m_unrepresentedDataAction==1) && p.second->inputBinRedirect[bin]!=bin) { } //do nothing
2247 else if( m_unrepresentedDataAction==3 ) {histptr->Fill(triggerHists[tbits]->GetBinCenter(p.second->inputBinRedirect[bin]), intLumi*pFactor);}
2248 else triggerHists[tbits]->Fill(mu*m_dataScaleFactorX,intLumi*pFactor);
2249
2250
2251 if(runDependentRun && fillUnprescaledLumi) {
2252 //need to fill unprescaled lumi histogram for this particular run ...
2253 if(unprescaledLumi==0) {
2254 m_triggerObjs["None"]->triggerHists[-runDependentRun][0] = CloneEmptyHistogram(p.first,-1);
2255 unprescaledLumi = m_triggerObjs["None"]->triggerHists[-runDependentRun][0].get();
2256 }
2257 if( (m_unrepresentedDataAction==1) && p.second->inputBinRedirect[bin]!=bin) { } //do nothing
2258 else if( m_unrepresentedDataAction==3 ) {unprescaledLumi->Fill(unprescaledLumi->GetBinCenter(p.second->inputBinRedirect[bin]), intLumi);}
2259 else unprescaledLumi->Fill(mu*m_dataScaleFactorX,intLumi);
2260 }
2261
2262 firstFill=true;
2263
2264 }
2265 }
2266 rootFile->Close();
2267 }
2268 }
2269 delete rootFile;
2270 } //end loop over unprescaled lumicalc files
2271
2272
2273 //Info("aa","Int lumi is %f", m_triggerPrimaryDistributions[trigger][1]->Integral());
2274
2275
2276
2277 // Return to the original ROOT directory
2279
2280
2281}
std::map< TString, std::unique_ptr< CompositeTrigger > > m_triggerObjs
TrigPassBitsCollection tbits
ps1
rename ourselfs to athena, both the prompt and the process (for top & ps)
Definition athena.py:137

◆ CalculatePrescaledLuminosityHistograms()

void TPileupReweighting::CalculatePrescaledLuminosityHistograms ( const TString & trigger,
int run_dependent = 0 )
protectedinherited

Definition at line 2092 of file TPileupReweighting.cxx.

2092 {
2093 //check if this is a composite trigger (user has provided OR of triggers that are passed before prescale)
2094
2095 TString triggerCopy = trigger; triggerCopy.ReplaceAll(" ",""); triggerCopy.ReplaceAll("&&","&");triggerCopy.ReplaceAll("||","|");
2096 auto t = makeTrigger(triggerCopy);
2097 if( ! t ) {
2098 Error("GetDataWeight","Error parsing composite trigger set: %s",trigger.Data());
2099 throw std::runtime_error("Could not parse composite trigger");
2100 }
2101
2102 std::vector<TString> subTriggers;
2103
2104 t->getTriggers(subTriggers); //fills the vector
2105
2106 t->subTriggers = std::move(subTriggers); //cache the vector of triggers
2107
2108 calculateHistograms(t.get(),runDependentRun);
2109
2110 //save trigger object
2111 m_triggerObjs[trigger] = std::move( t );
2112
2113}
std::unique_ptr< CompositeTrigger > makeTrigger(const TString &s)
void calculateHistograms(CompositeTrigger *trigger, int run_dependent)

◆ Class_Version()

Version_t CP::PileupReweightingTool::Class_Version ( )
inlinestatic

Definition at line 177 of file PileupReweightingTool.h.

177{ return 0; }

◆ CloneEmptyHistogram()

std::unique_ptr< TH1 > TPileupReweighting::CloneEmptyHistogram ( Int_t runNumber,
Int_t channelNumber )
protectedinherited

Definition at line 435 of file TPileupReweighting.cxx.

435 {
436
437 TString s("pileup");
438 if(channelNumber>=0) {
439 s += "_chan"; s += channelNumber;
440 } else {
441 s += "_data";
442 }
443 s+="_run"; s+= runNumber;
444 //get the empty histogram
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)");
448 }
449
450 std::unique_ptr< TH1 > out( dynamic_cast<TH1*>(m_emptyHistogram->Clone(s)) );
451 if (out) {
452 out->SetTitle(s);
453 out->SetDirectory(0); //take ownership
454 out->SetEntries(0);
455 }
456 return out;
457
458}

◆ CopyProperties()

void CP::TPileupReweighting::CopyProperties ( const TPileupReweighting * in)
inlineinherited

Definition at line 480 of file TPileupReweighting.h.

480 {
481 m_prwFilesPathPrefix = in->m_prwFilesPathPrefix;
482 m_ignoreBadChannels = in->m_ignoreBadChannels;
483 m_unrepresentedDataAction = in->m_unrepresentedDataAction;
484 m_unrepDataTolerance= in->m_unrepDataTolerance;
485 m_unrepDataWarningThreshold = in->m_unrepDataWarningThreshold;
486 }

◆ declareGaudiProperty()

Gaudi::Details::PropertyBase & AthCommonDataStore< AthCommonMsg< AlgTool > >::declareGaudiProperty ( Gaudi::Property< T, V, H > & hndl,
const SG::VarHandleKeyType &  )
inlineprivateinherited

specialization for handling Gaudi::Property<SG::VarHandleKey>

Definition at line 156 of file AthCommonDataStore.h.

158 {
160 hndl.value(),
161 hndl.documentation());
162
163 }

◆ declareProperty()

Gaudi::Details::PropertyBase & AthCommonDataStore< AthCommonMsg< AlgTool > >::declareProperty ( Gaudi::Property< T, V, H > & t)
inlineinherited

Definition at line 145 of file AthCommonDataStore.h.

145 {
146 typedef typename SG::HandleClassifier<T>::type htype;
148 }
Gaudi::Details::PropertyBase & declareGaudiProperty(Gaudi::Property< T, V, H > &hndl, const SG::VarHandleKeyType &)
specialization for handling Gaudi::Property<SG::VarHandleKey>

◆ detStore()

const ServiceHandle< StoreGateSvc > & AthCommonDataStore< AthCommonMsg< AlgTool > >::detStore ( ) const
inlineinherited

The standard StoreGateSvc/DetectorStore Returns (kind of) a pointer to the StoreGateSvc.

Definition at line 95 of file AthCommonDataStore.h.

◆ DisableWarnings()

void CP::TPileupReweighting::DisableWarnings ( Bool_t in)
inlineinherited

Indicate if warnings should be suppressed.

Definition at line 116 of file TPileupReweighting.h.

◆ EnableDebugging()

void CP::TPileupReweighting::EnableDebugging ( Bool_t in)
inlineinherited

Indicate if additional debugging information should be output.

Definition at line 118 of file TPileupReweighting.h.

118{ m_debugging = in;}

◆ evtStore()

ServiceHandle< StoreGateSvc > & AthCommonDataStore< AthCommonMsg< AlgTool > >::evtStore ( )
inlineinherited

The standard StoreGateSvc (event store) Returns (kind of) a pointer to the StoreGateSvc.

Definition at line 85 of file AthCommonDataStore.h.

◆ expert()

virtual CP::TPileupReweighting * CP::PileupReweightingTool::expert ( )
inlinevirtual

Get pointer to the underlying tool - expert use only. Will require #include "PileupReweighting/TPileupReweighting.h".

Implements CP::IPileupReweightingTool.

Definition at line 121 of file PileupReweightingTool.h.

121{ return m_activeTool; }

◆ extraDeps_update_handler()

void AthCommonDataStore< AthCommonMsg< AlgTool > >::extraDeps_update_handler ( Gaudi::Details::PropertyBase & ExtraDeps)
protectedinherited

Add StoreName to extra input/output deps as needed.

use the logic of the VarHandleKey to parse the DataObjID keys supplied via the ExtraInputs and ExtraOuputs Properties to add the StoreName if it's not explicitly given

◆ Fill()

Int_t TPileupReweighting::Fill ( Int_t runNumber,
Int_t channelNumber,
Float_t w,
Float_t x,
Float_t y = 0. )
inherited

Definition at line 1843 of file TPileupReweighting.cxx.

1843 {
1844 if(!m_isInitialized ) {
1845 if (m_printInfo) Info("Fill","Initializing the subtool..");
1846 Initialize();
1847 }
1848 //should only be given genuine mcRunNumbers if mc (channel>=0). We don't fill periodNumber distributions
1849
1850 TH1* hist = 0;
1851
1852 //get the period if mc, get the data run if data
1853 if(channelNumber>=0) {
1854 if(m_periods.find(runNumber)==m_periods.end()) {
1855 //if assume default binning is true, will add binning from 0 to 100 for this run number
1858 }
1859 if(m_periods.find(runNumber)==m_periods.end()) {
1860 Error("Fill","Unrecognised runNumber: %d. Check your period configuration (AddPeriod or UsePeriodConfig)",runNumber);
1861 throw std::runtime_error("Throwing 1: Unrecognised periodNumber");
1862 }
1863 }
1865 if(!p) {
1866 Error("Fill","Unrecognised runNumber: %d. Check your period configuration (AddPeriod or UsePeriodConfig) ... but should never have got here so please report this!",runNumber);
1867 throw std::runtime_error("Throwing 1: Unrecognised periodNumber");
1868 }
1869 std::unique_ptr<TH1>& histptr = p->inputHists[channelNumber];
1870 if(!histptr) {
1871 //need to create my period histogram
1872 histptr = CloneEmptyHistogram(runNumber,channelNumber);
1873 }
1874 hist = histptr.get();
1875 } else {
1876 Run& r = m_runs[runNumber];
1877 if( ! r.inputHists["None"]) r.inputHists["None"]=CloneEmptyHistogram(runNumber,channelNumber);
1878 hist = r.inputHists["None"].get();
1879 }
1880
1881 if(!hist) {
1882 Error("Fill","Unknown [run,channel] = [%d,%d]",runNumber,channelNumber);
1883 throw std::runtime_error("Throwing 45: Fill:: Unknown [run,channel] ");
1884 }
1885
1886 if(hist->GetDimension()==1) {
1887 return hist->Fill(x,w);
1888 } else if(hist->GetDimension()==2) {
1889 return (static_cast<TH2*>(hist))->Fill(x,y,w);
1890 }
1891 return -1;
1892}
Int_t Initialize()
Initialize this class once before the event loop starts If distribution information is provided,...

◆ fill() [1/2]

int CP::PileupReweightingTool::fill ( const xAOD::EventInfo & eventInfo)
virtual

Call this method once per event when in config file generating mode and you want standard mu reweighting.

Implements CP::IPileupReweightingTool.

Definition at line 436 of file PileupReweightingTool.cxx.

436 {
437 return fill(eventInfo,eventInfo.averageInteractionsPerCrossing(),0);
438}

◆ fill() [2/2]

int CP::PileupReweightingTool::fill ( const xAOD::EventInfo & eventInfo,
Double_t x,
Double_t y )
virtual

Use this method if you want to do a generic reweighting instead.

Implements CP::IPileupReweightingTool.

Definition at line 440 of file PileupReweightingTool.cxx.

440 {
441
442 //auto-detect the period config if necessary
443 if(m_usePeriodConfig=="auto" && !m_doneConfigs[eventInfo.runNumber()]) { //try autodetect based on runnum of first event ...
444 //if data, we only need to ensure a binning is done ... for now, we assume the MC15 binning
446 if(!m_emptyHistogram) { SetUniformBinning(100,0,100.); } //use a default binning
447 } else {
448 switch(eventInfo.runNumber()) {
449 case 212272: UsePeriodConfig("MC14_8TeV");break;
450 case 222222: UsePeriodConfig("MC14_13TeV");break;
451 case 222510: case 222525: case 222526: case 284500: UsePeriodConfig("MC15"); break;
452 }
453 if(eventInfo.runNumber()>284500) UsePeriodConfig("Run2"); //this is the automatic period config, allows any run numbers to be added
454 }
455 m_doneConfigs[eventInfo.runNumber()] = true;
456 }
457
458 return TPileupReweighting::Fill(eventInfo.runNumber(), eventInfo.eventType(xAOD::EventInfo::IS_SIMULATION) ? eventInfo.mcChannelNumber() : -1 /*data*/, eventInfo.eventType(xAOD::EventInfo::IS_SIMULATION) ? m_weightTool->getWeight() : 1., x, y);
459
460}
virtual Int_t SetUniformBinning(Int_t nbinsx, Double_t xlow, Double_t xup, Int_t nbinsy=0, Double_t ylow=0, Double_t yup=0)
std::map< int, bool > m_doneConfigs
Int_t Fill(Int_t runNumber, Int_t channelNumber, Float_t w, Float_t x, Float_t y=0.)
Int_t UsePeriodConfig(const TString &configName)
use a hardcoded period configuration
uint32_t runNumber() const
The current event's run number.
uint32_t mcChannelNumber() const
The MC generator's channel number.

◆ finalize()

StatusCode CP::PileupReweightingTool::finalize ( )
virtual

Finalize - can call the WriteToFile for us.

Definition at line 310 of file PileupReweightingTool.cxx.

310 {
311 if(m_inConfigMode) {
312#ifndef XAOD_STANDALONE
313 if(m_configStream=="") {
314 //write the prw config files
315 std::string nameWithoutParent = this->name().substr(this->name().find(".")+1);
316 TString fileName = TString::Format("%s.prw.root", nameWithoutParent.c_str());
317 /*m_tool->*/WriteToFile(fileName);
318 } else {
319 //write to the histsvc stream instead ...
320
321 ServiceHandle<ITHistSvc> histSvc("THistSvc",name());
322 CHECK( histSvc.retrieve() );
323
324 TTree *outTreeMC=0;
325 TTree *outTreeData=0;
326 Int_t channel = 0;UInt_t runNumber = 0;
327 std::vector<UInt_t> pStarts;
328 std::vector<UInt_t> pEnds;
329 std::vector<UInt_t>* pStartsPtr = &pStarts;
330 std::vector<UInt_t>* pEndsPtr = &pEnds;
331 Char_t histName[150];
332
333
334 //loop over periods ... periods only get entry in table if they have an input histogram
335 for(auto period : m_periods) {
336 if(!period.second) continue; //should never happen, but just in case!
337 if(period.first<0) continue; //avoid the global run number
338 if(period.first != period.second->id) continue; //skips redirects
339 runNumber = period.first;
340 pStarts.clear();
341 pEnds.clear();
342 if(period.second->subPeriods.size()==0) {
343 pStarts.push_back(period.second->start); pEnds.push_back(period.second->end);
344 }
345 else {
346 for(auto subp : period.second->subPeriods) {
347 pStarts.push_back(subp->start); pEnds.push_back(subp->end);
348 }
349 }
350 for(auto& inHist : period.second->inputHists) {
351 channel = inHist.first;
352 TH1* hist = inHist.second.release();
353 strncpy(histName,hist->GetName(),sizeof(histName)-1);
354 CHECK( histSvc->regHist(TString::Format("/%s/PileupReweighting/%s",m_configStream.c_str(),hist->GetName()).Data(),hist) );
355 if(!outTreeMC) {
356 outTreeMC = new TTree("MCPileupReweighting","MCPileupReweighting");
357 outTreeMC->Branch("Channel",&channel);
358 outTreeMC->Branch("RunNumber",&runNumber);
359 outTreeMC->Branch("PeriodStarts",&pStartsPtr);
360 outTreeMC->Branch("PeriodEnds",&pEndsPtr);
361 outTreeMC->Branch("HistName",&histName,"HistName/C");
362 CHECK( histSvc->regTree(TString::Format("/%s/PileupReweighting/%s",m_configStream.c_str(),outTreeMC->GetName()).Data(),outTreeMC) );
363 }
364 outTreeMC->Fill();
365 }
366 }
367
368 //loop over data
369 for(auto& run : m_runs) {
370 runNumber = run.first;
371 if(run.second.inputHists.find("None")==run.second.inputHists.end()) continue;
372
373 TH1* hist = run.second.inputHists["None"].release();
374 strncpy(histName,hist->GetName(),sizeof(histName)-1);
375 CHECK( histSvc->regHist(TString::Format("/%s/PileupReweighting/%s",m_configStream.c_str(),hist->GetName()).Data(),hist) );
376 if(!outTreeData) {
377 outTreeData = new TTree("DataPileupReweighting","DataPileupReweighting");
378 outTreeData->Branch("RunNumber",&runNumber);
379 outTreeData->Branch("HistName",&histName,"HistName/C");
380 CHECK( histSvc->regTree(TString::Format("/%s/PileupReweighting/%s",m_configStream.c_str(),outTreeData->GetName()).Data(),outTreeData) );
381 }
382 outTreeData->Fill();
383 }
384
385 Info("WriteToFile", "Successfully generated config file to stream: %s",m_configStream.c_str());
386 Info("WriteToFile", "Happy Reweighting :-)");
387
388 }
389
390#else
391 //write the prw config files
392 std::string nameWithoutParent = this->name().substr(this->name().find(".")+1);
393 TString fileName = TString::Format("%s.prw.root", nameWithoutParent.c_str());
394 /*m_tool->*/WriteToFile(fileName);
395#endif
396 }
397
398 m_upTool.reset(); m_downTool.reset();
399
400 return StatusCode::SUCCESS;
401}
#define CHECK(...)
Evaluate an expression and check for errors.
Int_t WriteToFile(const TString &filename="")
std::string find(const std::string &s)
return a remapped string
Definition hcg.cxx:140
int run(int argc, char *argv[])

◆ GenerateMetaDataFile()

Int_t TPileupReweighting::GenerateMetaDataFile ( const TString & fileName,
const TString & channelBranchName = "mc_channel_number" )
inherited

Definition at line 460 of file TPileupReweighting.cxx.

460 {
461
462 TTree inTree("in","in");
463 inTree.ReadFile(fileName);
464 TTree outTree("ChannelMetaData","ChannelMetaData");
465 Int_t chanNum;
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);
471 if(leaf) {
472 TBranch *branch = leaf->GetBranch();
473 if(strcmp(branch->GetName(),channelBranchName)==0) {
474 //this is the channel branch
475 if(strcmp(leaf->GetTypeName(),"Int_t")!=0) {
476 Error("GenerateMetaDataFile","Channel Branch must be type Int_t"); return -1;
477 }
478 branch->SetAddress(&chanNum);
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());
482 } else {
483 branch->SetAddress(&(data[branch->GetName()]));
484 outTree.Branch(branch->GetName(),&(data[branch->GetName()]));
485 }
486 }
487 }
488 //loop over tree entries and read in the values according to property type
489 for(Int_t i=0;i<inTree.GetEntries();++i) {
490 inTree.GetEntry(i);
491 outTree.Fill();
492 }
493
494 //remove the file extension and replace with .root
495 TString outName = fileName(0,fileName.Last('.'));
496 outName += ".prw.root";
497 TFile f1(outName,"RECREATE");
498 outTree.Write();
499 f1.Close();
500 if (m_printInfo) {
501 Info("GenerateMetaDataFile","Succesfully Generated File %s",outName.Data());
502 }
503 return 0;
504}

◆ GetCombinedWeight()

Float_t TPileupReweighting::GetCombinedWeight ( Int_t periodNumber,
Int_t channelNumber,
Float_t x,
Float_t y = 0. )
inherited

Definition at line 1609 of file TPileupReweighting.cxx.

1609 {
1610 if(!m_isInitialized) {
1611 if (m_printInfo) Info("GetCombinedWeight","Initializing the subtool..");
1612 Initialize();
1613 }
1614 if(m_countingMode) return 0.;
1615
1616 //decide how many dimensions this weight has - use the emptyHistogram to tell...
1617 TH1* hist = m_emptyHistogram.get();
1618 if(!hist) {
1619 Error("GetCombinedWeight","Tool not configured properly ... please report this!");
1620 throw std::runtime_error("Throwing 47: Tool not configured properly ... please report this!");
1621 }
1622
1623 Float_t out = GetPeriodWeight(periodNumber,channelNumber)*GetPrimaryWeight(periodNumber,channelNumber,x);
1624 if(hist->GetDimension()>1) out *= GetSecondaryWeight(periodNumber,channelNumber,x,y);
1625
1626 return out;
1627}
Float_t GetSecondaryWeight(Int_t periodNumber, Int_t channelNumber, Float_t x, Float_t y)
Float_t GetPrimaryWeight(Int_t periodNumber, Int_t channelNumber, Float_t x)
Float_t GetPeriodWeight(Int_t periodNumber, Int_t channelNumber)

◆ getCombinedWeight() [1/3]

float CP::PileupReweightingTool::getCombinedWeight ( const xAOD::EventInfo & eventInfo,
bool correctUnrepresented )
virtual

Return combined pileup weight.

Implements CP::IPileupReweightingTool.

Definition at line 408 of file PileupReweightingTool.cxx.

408 {
409 float weight = m_activeTool->GetCombinedWeight( eventInfo.runNumber(), eventInfo.mcChannelNumber(), eventInfo.averageInteractionsPerCrossing() );
410 if(correctUnrepresented && m_unrepresentedDataAction==2)
411 weight *= getUnrepresentedDataWeight( eventInfo );
412 return weight;
413}
virtual float getUnrepresentedDataWeight(const xAOD::EventInfo &eventInfo)
When using UnrepresentedDataAction=2, you may want to apply this additional weight to ensure sum of w...

◆ getCombinedWeight() [2/3]

float CP::PileupReweightingTool::getCombinedWeight ( const xAOD::EventInfo & eventInfo,
const TString & trigger,
bool mu_dependent,
bool correctUnrepresented )
virtual

get combined weight (i.e. pileup weight) but with a 1./dataWeight factor applied, this if used for 'prescaling' MC

Implements CP::IPileupReweightingTool.

Definition at line 536 of file PileupReweightingTool.cxx.

536 {
537 float out = getCombinedWeight(eventInfo, correctUnrepresented);
538 if(!out) return out; //don't try to evaluate DataWeight if our PRW is 0 ... means there is no data available at that mu anyway
539
540 out *= getPrescaleWeight(eventInfo, trigger, mu_dependent);
541 return out;
542}
virtual float getPrescaleWeight(const xAOD::EventInfo &eventInfo, const TString &trigger, bool mu_dependent)
Get weight used to 'prescale' Monte Carlo for given trigger comibnation.

◆ getCombinedWeight() [3/3]

float CP::PileupReweightingTool::getCombinedWeight ( const xAOD::EventInfo & eventInfo,
Double_t x,
Double_t y,
bool correctUnrepresented )
virtual

Same as above, but for a 'custom weight' variable.

Implements CP::IPileupReweightingTool.

Definition at line 415 of file PileupReweightingTool.cxx.

415 {
416 float weight = m_activeTool->GetCombinedWeight( eventInfo.runNumber(), eventInfo.mcChannelNumber(), x, y );
417 if(correctUnrepresented && m_unrepresentedDataAction==2)
418 weight *= getUnrepresentedDataWeight( eventInfo );
419 return weight;
420}

◆ getCorrectedActualInteractionsPerCrossing()

float CP::PileupReweightingTool::getCorrectedActualInteractionsPerCrossing ( const xAOD::EventInfo & eventInfo,
bool includeDataScaleFactor )
virtual

Get the corrected 'actual' interactions per crossing.

Implements CP::IPileupReweightingTool.

Definition at line 163 of file PileupReweightingTool.cxx.

163 {
164 float result = 1.;
165 const float actualInteractions = eventInfo.actualInteractionsPerCrossing();
167 return actualInteractions; //no correction needed for MC
168 }
169 float correctedMu = CP::TPileupReweighting::GetLumiBlockMu(eventInfo.runNumber(),eventInfo.lumiBlock());
170 if(correctedMu<0) return correctedMu; //will be -1
171 if ( const auto avg = eventInfo.averageInteractionsPerCrossing(); avg != 0.){
172 result = actualInteractions * (correctedMu/avg) * ( (includeDataScaleFactor) ? m_activeTool->GetDataScaleFactor() : 1.);
173 }
174 return result;
175}
Float_t GetLumiBlockMu(Int_t runNumber, UInt_t lb)
get the lumiblock mu, useful for 'updating' the mu coming from data to account for new lumitags
uint32_t lumiBlock() const
The current event's luminosity block number.
float actualInteractionsPerCrossing() const
Average interactions per crossing for the current BCID - for in-time pile-up.
avg(a, b)
Definition Recovery.py:79

◆ getCorrectedAverageInteractionsPerCrossing()

float CP::PileupReweightingTool::getCorrectedAverageInteractionsPerCrossing ( const xAOD::EventInfo & eventInfo,
bool includeDataScaleFactor )
virtual

Get the mu of a lumiblock ... needed to 'correct' the number in datasets.

Implements CP::IPileupReweightingTool.

Definition at line 154 of file PileupReweightingTool.cxx.

154 {
156 return eventInfo.averageInteractionsPerCrossing(); //no correction needed for MC
157 }
158 float out = CP::TPileupReweighting::GetLumiBlockMu(eventInfo.runNumber(),eventInfo.lumiBlock());
159 if(out<0) return out; //will be -1
160 return out * ( (includeDataScaleFactor) ? m_activeTool->GetDataScaleFactor() : 1.);
161}

◆ getCorrectedMu()

virtual float CP::IPileupReweightingTool::getCorrectedMu ( const xAOD::EventInfo & eventInfo,
bool includedDataScaleFactor = false )
inlinevirtualinherited

Get the corrected average mu of a lumiblock ... (averaging is over all filled BCID in the fill) The additional flag indicates if the returned value should include the data scale factor or not.

Note: if the lumiblock is not present in the input lumicalc file, then -1.0 will be returned This method will soon be deprecated in favour of the new naming: getCorrectedAverageInteractionsPerCrossing

Definition at line 61 of file IPileupReweightingTool.h.

61 {
62 return getCorrectedAverageInteractionsPerCrossing( eventInfo, includedDataScaleFactor );
63 }
virtual float getCorrectedAverageInteractionsPerCrossing(const xAOD::EventInfo &eventInfo, bool includedDataScaleFactor=false)=0

◆ GetDataScaleFactor()

Float_t CP::TPileupReweighting::GetDataScaleFactor ( ) const
inlineinherited

Definition at line 298 of file TPileupReweighting.h.

298{ return m_dataScaleFactorX; }

◆ GetDataWeight() [1/2]

Double_t TPileupReweighting::GetDataWeight ( Int_t runNumber,
const TString & trigger )
inherited

Definition at line 1728 of file TPileupReweighting.cxx.

1728 {
1729 //special mu-independent version of GetDataWeight. Will just use the global luminosity
1731 double out = GetDataWeight(runNumber, trigger, 0);
1733 return out;
1734}
Double_t GetDataWeight(Int_t runNumber, const TString &trigger, Double_t x, bool run_dependent=false)
Method for weighting data to account for prescales and mu bias.

◆ GetDataWeight() [2/2]

Double_t TPileupReweighting::GetDataWeight ( Int_t runNumber,
const TString & trigger,
Double_t x,
bool run_dependent = false )
inherited

Method for weighting data to account for prescales and mu bias.

Use by giving the tool multiple lumicalc files, one for each trigger

Definition at line 1736 of file TPileupReweighting.cxx.

1736 {
1737
1738 if(!m_isInitialized ) {
1739 if (m_printInfo) Info("GetDataWeight","Initializing the subtool..");
1740 Initialize();
1741 }
1742 if(m_countingMode) return 0.;
1743
1744 //determine which period this run number is in
1745 Int_t periodNumber = GetFirstFoundPeriodNumber(runNumber);
1746
1747 Period* p = m_periods[periodNumber];
1748 if(!p) {
1749 Error("GetDataWeight","Unrecognised periodNumber: %d",periodNumber);
1750 throw std::runtime_error("Throwing 1: Unrecognised periodNumber");
1751 }
1752
1753 //see if we already made this trigger hist
1754 auto tobj = m_triggerObjs.find(trigger);
1755
1756
1757 if(tobj==m_triggerObjs.end()) {
1758 //try to do a subtrigger calculation we need to reopen all the lumicalc files and do the fiddily prescaled luminosity calculation
1759 //will throw errors if can't
1761 tobj = m_triggerObjs.find(trigger);
1762 }
1763
1764 //check
1765
1766
1767
1768 if(tobj->second->triggerHists.find(p->id) == tobj->second->triggerHists.end()) {
1769 Error("GetDataWeight","Could not find trigger %s in period %d",trigger.Data(),p->id);
1770 throw std::runtime_error("GetDataWeight: Could not find trigger 1");
1771 }
1772
1773
1774 //now we need to evaluate the trigger bits, and if necessary calculate the new trigger hist for the new bits combination
1775 long tbits = tobj->second->getBits(this);
1776
1777 if(tbits==0) return 1; //no trigger passed
1778
1779 int idx = (runDependent) ? -runNumber : p->id;
1780
1781
1782 auto dItr = tobj->second->triggerHists[idx].find(tbits);
1783
1784 TH1* denomHist = 0;
1785 if(dItr == tobj->second->triggerHists[idx].end()) {
1786 //possible that the tbits for this event have not been encountered before, so just redo the calculation ...
1787 calculateHistograms(tobj->second.get(),(runDependent) ? runNumber:0);
1788
1789 denomHist = tobj->second->triggerHists[idx][tbits].get();
1790 if(denomHist==0) {
1791 Error("GetDataWeight","Could not find trigger %s in period %d with bits %ld",trigger.Data(),idx, tbits);
1792 throw std::runtime_error("GetDataWeight: Could not find trigger 2");
1793 }
1794 } else {
1795 denomHist = dItr->second.get();
1796 }
1797
1798
1799 TH1* numerHist = m_triggerObjs["None"]->triggerHists[idx][0].get();
1800 if(numerHist==0) {
1801 Error("GetDataWeight","Could not find unprescaled trigger in period %d",idx);
1802 throw std::runtime_error("GetDataWeight: Could not find unprescaled trigger. Please AddLumiCalc with a 'None' trigger");
1803 }
1804
1805 if(m_doGlobalDataWeight) return numerHist->Integral(0,numerHist->GetNbinsX()+1)/denomHist->Integral(0,denomHist->GetNbinsX()+1);
1806
1807 Int_t bin=(m_doPrescaleWeight) ? numerHist->FindFixBin(x) : //DO NOT SHIFT IF GETTING A PRESCALE WEIGHT - applied to MC, we only shift incoming mu if we are data
1808 numerHist->FindFixBin(x*m_dataScaleFactorX); //if getting a data weight (i.e. running on data) MUST SCALE BY THE DATA SCALE FACTOR! (assume incoming is raw unscaled)
1809
1810 //we also need to redirect the binning if necessary (unrepData=3)
1811 if( (!m_doPrescaleWeight) && m_unrepresentedDataAction==3) bin = p->inputBinRedirect[bin];
1812
1813 if(!denomHist->GetBinContent(bin)) {
1814 if(m_doPrescaleWeight) return -1; //happens if trigger was disabled/unavailable for that mu, even though that mu is in the dataset
1815 Error("GetDataWeight","Unrecognised mu value %f ... are you sure you included all lumicalc files",x);
1816 throw std::runtime_error("GetDataWeight: Unrecognised mu value. Please AddLumiCalc enough lumi with 'None' trigger");
1817 }
1818
1819 return numerHist->GetBinContent(bin)/denomHist->GetBinContent(bin);
1820}
void CalculatePrescaledLuminosityHistograms(const TString &trigger, int run_dependent=0)
Int_t GetFirstFoundPeriodNumber(UInt_t runNumber)
Get the first period number with the data run number contained - assume all periods are disconnected ...

◆ getDataWeight()

float CP::PileupReweightingTool::getDataWeight ( const xAOD::EventInfo & eventInfo,
const TString & trigger,
bool mu_dependent )
virtual

Get the dataWeight used to 'unprescale' data collected from a given trigger combination. mu_dependency is recommended to be true.

Implements CP::IPileupReweightingTool.

Definition at line 506 of file PileupReweightingTool.cxx.

506 {
507
509 ATH_MSG_WARNING("Requesting Data Weight is not intended for simulated events. Returning 1.");
510 return 1; //no data weights for simulated events
511 }
512
513 if(!mu_dependent) return /*m_tool->*/m_activeTool->GetDataWeight(eventInfo.runNumber(), trigger);
514
515 double correctedMu = getCorrectedAverageInteractionsPerCrossing(eventInfo,false);
516 if(correctedMu<0) {
517 ATH_MSG_ERROR("Unrecognised run+lumiblock number (" << eventInfo.runNumber() << "," << eventInfo.lumiBlock() << ") ... please ensure your lumicalc files are complete! Returning 1.");
518 return 1;
519 }
520
521 return /*m_tool->*/m_activeTool->GetDataWeight( eventInfo.runNumber(), trigger, correctedMu/*use the 'correct' mu instead of the one from the file!!*/ );
522
523}
#define ATH_MSG_WARNING(x)

◆ GetDefaultChannel()

Int_t TPileupReweighting::GetDefaultChannel ( Int_t mcRunNumber = -1)
inherited

Definition at line 109 of file TPileupReweighting.cxx.

109 {
110 if(m_parentTool != this) return m_parentTool->GetDefaultChannel(mcRunNumber);
111 return m_periods[mcRunNumber]->defaultChannel;
112}

◆ GetFirstFoundPeriodNumber()

Int_t TPileupReweighting::GetFirstFoundPeriodNumber ( UInt_t runNumber)
inherited

Get the first period number with the data run number contained - assume all periods are disconnected for this to be useful.

Definition at line 422 of file TPileupReweighting.cxx.

422 {
423 //go through periods, first period that includes this runNumber wins!
424 //otherwise it returns the 'global period number': -1
425 for(auto period : m_periods) {
426 if(period.second->id==-1) continue;
427 if(period.second->contains(runNumber)) return period.second->id;
428 }
429 return -1;
430
431}

◆ GetInputHistogram()

TH1 * CP::TPileupReweighting::GetInputHistogram ( Int_t channelNumber,
Int_t periodNumber )
inlineinherited

Definition at line 251 of file TPileupReweighting.h.

251 {
252 if(m_periods.find(periodNumber)==m_periods.end()||
253 m_periods[periodNumber]->inputHists.find(channelNumber)==m_periods[periodNumber]->inputHists.end()) {
254 return 0;
255 }
256 return m_periods[periodNumber]->inputHists[channelNumber].get();
257 }

◆ GetIntegratedLumi() [1/3]

virtual Double_t CP::PileupReweightingTool::GetIntegratedLumi ( const TString & trigger)
inlinevirtual

Total lumi (in pb-1) for a given trigger combination .. leave blank for the unprescaled.

Implements CP::IPileupReweightingTool.

Definition at line 51 of file PileupReweightingTool.h.

51{ return m_activeTool->GetIntegratedLumi(trigger); }

◆ GetIntegratedLumi() [2/3]

virtual Double_t CP::PileupReweightingTool::GetIntegratedLumi ( Int_t periodNumber,
UInt_t start,
UInt_t end )
inlinevirtual

similar to above, but for only the given mcRunNumber/periodNumber

Implements CP::IPileupReweightingTool.

Definition at line 53 of file PileupReweightingTool.h.

53{ return m_activeTool->GetIntegratedLumi(periodNumber, start, end); }

◆ GetIntegratedLumi() [3/3]

virtual Double_t CP::PileupReweightingTool::GetIntegratedLumi ( UInt_t start,
UInt_t end )
inlinevirtual

Get the integrated luminosity (in pb-1) between start and end run (inclusive).

Implements CP::IPileupReweightingTool.

Definition at line 49 of file PileupReweightingTool.h.

49{ return m_activeTool->GetIntegratedLumi(start, end); }

◆ GetIntegratedLumiFraction() [1/2]

virtual Double_t CP::PileupReweightingTool::GetIntegratedLumiFraction ( Int_t periodNumber,
Double_t mu,
UInt_t start,
UInt_t end )
inlinevirtual

return fraction of lumi assigned to periodNumber (or mcRunNumber) with given mu, that is between start and end data run numbers

Implements CP::IPileupReweightingTool.

Definition at line 57 of file PileupReweightingTool.h.

57{ return m_activeTool->GetIntegratedLumiFraction(periodNumber, mu, start, end); }

◆ GetIntegratedLumiFraction() [2/2]

virtual Double_t CP::PileupReweightingTool::GetIntegratedLumiFraction ( Int_t periodNumber,
UInt_t start,
UInt_t end )
inlinevirtual

return fraction of lumi assigned to periodNumber (or mcRunNumber) that is between start and end data run numbers

Implements CP::IPileupReweightingTool.

Definition at line 55 of file PileupReweightingTool.h.

55{ return m_activeTool->GetIntegratedLumiFraction(periodNumber, start, end); }

◆ getKey()

SG::sgkey_t asg::AsgTool::getKey ( const void * ptr) const
inherited

Get the (hashed) key of an object that is in the event store.

This is a bit of a special one. StoreGateSvc and xAOD::TEvent both provide ways for getting the SG::sgkey_t key for an object that is in the store, based on a bare pointer. But they provide different interfaces for doing so.

In order to allow tools to efficiently perform this operation, they can use this helper function.

See also
asg::AsgTool::getName
Parameters
ptrThe bare pointer to the object that the event store should know about
Returns
The hashed key of the object in the store. If not found, an invalid (zero) key.

Definition at line 119 of file AsgTool.cxx.

119 {
120
121#ifdef XAOD_STANDALONE
122 // In case we use @c xAOD::TEvent, we have a direct function call
123 // for this.
124 return evtStore()->event()->getKey( ptr );
125#else
126 const SG::DataProxy* proxy = evtStore()->proxy( ptr );
127 return ( proxy == nullptr ? 0 : proxy->sgkey() );
128#endif // XAOD_STANDALONE
129 }
ServiceHandle< StoreGateSvc > & evtStore()

◆ GetLumiBlockIntegratedLumi()

Double_t TPileupReweighting::GetLumiBlockIntegratedLumi ( Int_t runNumber,
UInt_t lb )
inherited

get integrated lumi for specific run and lumiblock number .

. comes from the 'unprescaled lumi', and is in pb

Definition at line 154 of file TPileupReweighting.cxx.

154 {
155 if(!m_isInitialized) {
156 if (m_printInfo) {
157 Info("GetIntegratedLumi","Initializing the subtool..");
158 }
159 Initialize();
160 }
161 if(m_runs.find(runNumber)==m_runs.end()) return 0.;
162 auto& run = m_runs[runNumber];
163
164 if(run.lumiByLbn.find(lb)==run.lumiByLbn.end()) return 0.;
165 return run.lumiByLbn[lb].first*1E-6;
166}
int lb
Definition globals.cxx:23

◆ getLumiBlockIntegratedLumi()

double CP::PileupReweightingTool::getLumiBlockIntegratedLumi ( const xAOD::EventInfo & eventInfo)
virtual

Get the integrated lumi of a lumiblock (in pb-1).

Implements CP::IPileupReweightingTool.

Definition at line 178 of file PileupReweightingTool.cxx.

Double_t GetLumiBlockIntegratedLumi(Int_t runNumber, UInt_t lb)
get integrated lumi for specific run and lumiblock number .

◆ GetLumiBlockMu()

Float_t TPileupReweighting::GetLumiBlockMu ( Int_t runNumber,
UInt_t lb )
inherited

get the lumiblock mu, useful for 'updating' the mu coming from data to account for new lumitags

Definition at line 168 of file TPileupReweighting.cxx.

168 {
169 if(!m_isInitialized) {
170 if (m_printInfo) {
171 Info("GetLumiBlockMu","Initializing the subtool..");
172 }
173 Initialize();
174 }
175 if(m_runs.find(runNumber)==m_runs.end()) return -1.0;
176 auto& run = m_runs[runNumber];
177
178 if(run.lumiByLbn.find(lb)==run.lumiByLbn.end()) return -1.0;
179 return run.lumiByLbn[lb].second;
180}

◆ GetMetaData()

Double_t CP::TPileupReweighting::GetMetaData ( const TString & metadataName,
Int_t channelNumber )
inlineinherited

Definition at line 188 of file TPileupReweighting.h.

188 {
189 if(m_metadata.find(metadataName)==m_metadata.end()) {
190 Error("GetMetaData","Metadata %s not known",metadataName.Data());
191 return 0;
192 }
193 if(m_metadata[metadataName].find(channelNumber)==m_metadata[metadataName].end()) {
194 Error("GetMetaData","Metadata %s not known in channel %d",metadataName.Data(), channelNumber);
195 return 0;
196 }
197 return m_metadata[metadataName][channelNumber];
198 }

◆ GetMetaDataTree()

TTree * TPileupReweighting::GetMetaDataTree ( )
inherited

combines loaded metadata with channel sumsofweights and entry counts

Definition at line 574 of file TPileupReweighting.cxx.

574 {
576 m_metadatatree = new TTree(TString(this->GetName())+"MetaData",TString(this->GetName())+"MetaData");
577 m_metadatatree->SetDirectory(0);
578 Int_t channel=0;
579 m_metadatatree->Branch("mc_channel_number",&channel);
580 std::map<TString,Double_t> data;
581 std::map<Int_t,bool> channels;
582 //create a branch for each metadata item
583 for(std::map<TString,std::map<Int_t,Double_t> >::iterator it=m_metadata.begin();it!=m_metadata.end();++it) {
584 for(std::map<Int_t,Double_t>::iterator it2=(it->second).begin();it2!=(it->second).end();++it2) {
585 channels[it2->first]=true; //records which channels we have metadata for
586 }
587 const auto &[ptr, inserted ] = data.try_emplace(it->first, 0.);
588 if (inserted){
589 m_metadatatree->Branch(it->first,&(data[it->first]));
590 }
591 }
592 //also create branches for the NumberOfEvents and SumOfEventWeights
593 data["NumberOfEvents"]=0.;
594 m_metadatatree->Branch("NumberOfEvents",&(data["NumberOfEvents"]));
595 data["SumOfEventWeights"]=0.;
596 m_metadatatree->Branch("SumOfEventWeights",&(data["SumOfEventWeights"]));
597 //and add to channels list any channels that have events
598 auto& myMap = m_periods[-1]->sumOfWeights;
599 for(std::map<Int_t,Double_t>::iterator it=myMap.begin();it!=myMap.end();++it) {
600 if(it->first>=0 && it->second>0.) channels[it->first]=true;
601 }
602
603 //now loop over the channels and fill the TTree
604 for(std::map<Int_t,bool>::iterator it=channels.begin();it!=channels.end();++it) {
605 channel=it->first;
606 for(std::map<TString,Double_t>::iterator it2=data.begin();it2!=data.end();++it2) {
607 if(it2->first=="NumberOfEvents") {
608 //check for this in globalNumberOfEntries
609 if(myMap.find(channel)==myMap.end()) {
610 data[it2->first]=0.;
611 Warning("GetMetaDataTree","Channel %d does not have MetaData %s",it->first,(it2->first).Data());
612 } else {
613 data[it2->first]=m_periods[-1]->numberOfEntries[channel];
614 }
615 } else if(it2->first=="SumOfEventWeights") {
616 //check for this in globalTotals
617 auto& myMap2 = m_periods[-1]->sumOfWeights;
618 if(myMap2.find(channel)==myMap2.end()) {
619 data[it2->first]=0.;
620 Warning("GetMetaDataTree","Channel %d does not have MetaData %s",it->first,(it2->first).Data());
621 } else {
622 data[it2->first]=m_periods[-1]->sumOfWeights[channel];
623 }
624 } else {
625 auto& myMap2 = m_metadata[it2->first];
626 if(myMap2.find(channel)==myMap2.end()) {
627 //this channel doesn't have this property
628 data[it2->first]=0.;
629 Warning("GetMetaDataTree","Channel %d does not have MetaData %s",it->first,(it2->first).Data());
630 } else {
631 data[it2->first]=myMap2[channel];
632 }
633 }
634 }
635 m_metadatatree->Fill();
636 }
637
638 m_metadatatree->BuildIndex("mc_channel_number");
639 m_metadatatree->ResetBranchAddresses();
640
641 return m_metadatatree;
642}
JetConstituentVector::iterator iterator

◆ getName()

const std::string & asg::AsgTool::getName ( const void * ptr) const
inherited

Get the name of an object that is / should be in the event store.

This is a bit of a special one. StoreGateSvc and xAOD::TEvent both provide ways for getting the std::string name for an object that is in the store, based on a bare pointer. But they provide different interfaces for doing so.

In order to allow tools to efficiently perform this operation, they can use this helper function.

See also
asg::AsgTool::getKey
Parameters
ptrThe bare pointer to the object that the event store should know about
Returns
The string name of the object in the store. If not found, an empty string.

Definition at line 106 of file AsgTool.cxx.

106 {
107
108#ifdef XAOD_STANDALONE
109 // In case we use @c xAOD::TEvent, we have a direct function call
110 // for this.
111 return evtStore()->event()->getName( ptr );
112#else
113 const SG::DataProxy* proxy = evtStore()->proxy( ptr );
114 static const std::string dummy = "";
115 return ( proxy == nullptr ? dummy : proxy->name() );
116#endif // XAOD_STANDALONE
117 }

◆ GetNearestGoodBin()

Int_t TPileupReweighting::GetNearestGoodBin ( Int_t thisMCRunNumber,
Int_t bin )
protectedinherited

Definition at line 1373 of file TPileupReweighting.cxx.

1373 {
1374
1375 int binDistance = 1;
1376 do {
1377 int res1 = IsBadBin(thisMCRunNumber,bin+binDistance);
1378 if(!res1) return bin+binDistance;
1379 int res2 = IsBadBin(thisMCRunNumber,bin-binDistance);
1380 if(!res2) return bin-binDistance;
1381 if(res1==2 && res2==2) { //run out of bins
1382 Error("GetNearestGoodBin", "None of the bins are good!!??");
1383 return -1;
1384 }
1385 binDistance++;
1386 } while(true); //scary!
1387
1388 return -1;
1389
1390}
Int_t IsBadBin(Int_t thisMCRunNumber, Int_t bin)

◆ GetNumberOfEvents()

virtual Double_t CP::PileupReweightingTool::GetNumberOfEvents ( Int_t channel)
inlinevirtual

Implements CP::IPileupReweightingTool.

Definition at line 65 of file PileupReweightingTool.h.

65{ return m_activeTool->GetNumberOfEvents(channel) ; }

◆ GetPeriodNumbers()

std::vector< int > CP::TPileupReweighting::GetPeriodNumbers ( ) const
inlineinherited

Definition at line 242 of file TPileupReweighting.h.

242 {
243 std::vector<int> out;
244 for(auto& p : m_periods) { out.push_back(p.first); }
245 return out;
246 }

◆ GetPeriodWeight()

Float_t TPileupReweighting::GetPeriodWeight ( Int_t periodNumber,
Int_t channelNumber )
inherited

Definition at line 1629 of file TPileupReweighting.cxx.

1629 {
1630 //= L_A/L / N_A/N
1631 if(!m_isInitialized) {
1632 if (m_printInfo) Info("GetPeriodWeight","Initializing the subtool..");
1633 Initialize();
1634 }
1635 if(m_countingMode) return 0.;
1636
1637 Period* p = m_periods[periodNumber];
1638 if(!p) {
1639 Error("GetPeriodWeight","Unrecognised periodNumber: %d",periodNumber);
1640 throw std::runtime_error("Throwing 1: Unrecognised periodNumber");
1641 }
1642 if(p->sumOfWeights.find(channelNumber) == p->sumOfWeights.end()) {
1643 channelNumber = GetDefaultChannel(periodNumber);//p->defaultChannel;
1644 if(channelNumber!=0) {
1645 Warning("GetPeriodWeight","You're using a default config file ... you're gonna have a bad time!!");
1646 Warning("GetPeriodWeight","Please generate proper config files!");
1647 }
1648 }
1649
1650 double n_a = p->sumOfWeights[channelNumber];
1651 double n = m_periods[-1]->sumOfWeights[channelNumber];
1652
1653 double l_a = p->sumOfWeights[-1];
1654 double l = m_periods[-1]->sumOfWeights[-1];
1655
1656 return (l_a/l) / (n_a/n);
1657}
Int_t GetDefaultChannel(Int_t mcRunNumber=-1)
l
Printing final latex table to .tex output file.

◆ GetPrescaleWeight() [1/2]

Double_t TPileupReweighting::GetPrescaleWeight ( Int_t runNumber,
const TString & trigger )
inherited

Definition at line 1823 of file TPileupReweighting.cxx.

1823 {
1824 //special mu-independent version of GetPrescaleWeight. Will just use the global luminosity
1826 double out = GetPrescaleWeight(runNumber, trigger, 0);
1828 return out;
1829}
Double_t GetPrescaleWeight(Int_t runNumber, const TString &trigger, Double_t x, bool run_dependent=false)
Method for prescaling MC to account for prescales in data.

◆ GetPrescaleWeight() [2/2]

Double_t TPileupReweighting::GetPrescaleWeight ( Int_t runNumber,
const TString & trigger,
Double_t x,
bool run_dependent = false )
inherited

Method for prescaling MC to account for prescales in data.

Definition at line 1831 of file TPileupReweighting.cxx.

1831 {
1832
1833 m_doPrescaleWeight = true;
1834 double out = GetDataWeight(runNumber,trigger,x,runDependent);
1835 m_doPrescaleWeight = false;
1836 if(out<=0) return 0; //happens when triggers disabled/unavailable for a given mu ... therefore the prescale weight is 0
1837 return 1./out;
1838
1839}

◆ getPrescaleWeight()

float CP::PileupReweightingTool::getPrescaleWeight ( const xAOD::EventInfo & eventInfo,
const TString & trigger,
bool mu_dependent )
virtual

Get weight used to 'prescale' Monte Carlo for given trigger comibnation.

Implements CP::IPileupReweightingTool.

Definition at line 525 of file PileupReweightingTool.cxx.

525 {
526 //need to use the random run number ... only used to pick the subperiod, but in run2 so far we only have one subperiod
527 SG::ConstAccessor<unsigned int> rrnAcc (m_prefix+"RandomRunNumber");
528 unsigned int randomRunNum = rrnAcc.withDefault (eventInfo, 0);
529 if (randomRunNum == 0) {
530 randomRunNum = getRandomRunNumber( eventInfo, mu_dependent );
531 }
532 if(!mu_dependent) return m_activeTool->GetPrescaleWeight(randomRunNum, trigger);
533 return m_activeTool->GetPrescaleWeight( randomRunNum, trigger, getCorrectedAverageInteractionsPerCrossing(eventInfo,false) /*use the 'correct' mu instead of the one from the file!!*/, m_useRunDependentPrescaleWeight /*run-dependent*/ );
534}

◆ GetPrimaryDistribution()

TH1 * CP::TPileupReweighting::GetPrimaryDistribution ( Int_t channelNumber,
Int_t periodNumber )
inlineinherited

Definition at line 259 of file TPileupReweighting.h.

259 {
260 if(m_periods.find(periodNumber)==m_periods.end()||
261 m_periods[periodNumber]->primaryHists.find(channelNumber)==m_periods[periodNumber]->primaryHists.end()) {
262 return 0;
263 }
264 return m_periods[periodNumber]->primaryHists[channelNumber].get();
265 }

◆ GetPrimaryTriggerDistribution()

TH1 * CP::TPileupReweighting::GetPrimaryTriggerDistribution ( const TString & trigger,
Int_t periodNumber,
long triggerBits )
inlineinherited

Definition at line 267 of file TPileupReweighting.h.

267 {
268 if(m_triggerObjs.find(trigger)==m_triggerObjs.end() || m_triggerObjs[trigger]->triggerHists.find(periodNumber) ==m_triggerObjs[trigger]->triggerHists.end() ||
269 m_triggerObjs[trigger]->triggerHists[periodNumber].find(triggerBits) == m_triggerObjs[trigger]->triggerHists[periodNumber].end()) return 0;
270 /*
271 if(m_triggerObjs.find(trigger)==m_triggerObjs.end() || m_triggerObjs.at(trigger).second->triggerHists.find(periodNumber)==m_triggerObjs.at(trigger).second->->triggerHists.end() ||
272 m_triggerObjs.at(trigger).second->triggerHists.at(periodNumber).find(triggerBits) == m_triggerObjs.at(trigger).second.at(periodNumber).end()) return 0;
273 */
274
275 return m_triggerObjs[trigger]->triggerHists[periodNumber][triggerBits].get();
276 }

◆ GetPrimaryWeight()

Float_t TPileupReweighting::GetPrimaryWeight ( Int_t periodNumber,
Int_t channelNumber,
Float_t x )
inherited

Definition at line 1659 of file TPileupReweighting.cxx.

1659 {
1660 //= L_i/L_A / N_i/N_A .. primaryHists have already been normalized
1661 if(!m_isInitialized ) {
1662 if (m_printInfo) Info("GetPrimaryWeight","Initializing the subtool..");
1663 Initialize();
1664 }
1665 if(m_countingMode) return 0.;
1666
1667 Period* p = m_periods[periodNumber];
1668 if(!p) {
1669 Error("GetPrimaryWeight","Unrecognised periodNumber: %d",periodNumber);
1670 throw std::runtime_error("Throwing 1: Unrecognised periodNumber");
1671 }
1672 int oChanNumber = channelNumber;
1673 if(p->sumOfWeights.find(channelNumber) == p->sumOfWeights.end()) channelNumber = GetDefaultChannel(periodNumber);//p->defaultChannel;
1674
1675 if(!p->primaryHists[channelNumber]) {
1676 Error("GetPrimaryWeight","Unrecognised channelNumber %d for periodNumber %d",oChanNumber,periodNumber);
1677 throw std::runtime_error("Throwing 2: Unrecognised channelNumber");
1678 }
1679
1680 int bin = p->primaryHists[channelNumber]->FindFixBin(x);
1681
1682 double n = p->primaryHists[channelNumber]->GetBinContent(bin);
1683
1684 // There is a special case that needs some additional protection
1685 // If you have the sum of weights ==0 for a given mu then you will have 0 in the PRW
1686 // profile leading to an exception or FPE later
1687 if (n==0){
1688 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);
1689 return 1.;
1690 }
1691
1692 if(!p->primaryHists[-1]) {
1693 Error("GetPrimaryWeight","No data loaded for period %d. Did you forget to load a lumicalc file or data config file?",periodNumber);
1694 throw std::runtime_error("Throwing 3: No data loaded. Did you forget to load a lumicalc file or data config file?");
1695 }
1696
1697 double l = p->primaryHists[-1]->GetBinContent(bin);
1698
1699 if (l==0 && n==0){
1700 Error("GetPrimaryWeight","No events expected with this mu. Incorrect PRW profile? Throwing exception ...");
1701 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 ));
1702 }
1703
1704 return l/n;
1705}

◆ getProperty()

template<class T>
const T * asg::AsgTool::getProperty ( const std::string & name) const
inherited

Get one of the tool's properties.

◆ GetPRWHash()

ULong64_t TPileupReweighting::GetPRWHash ( Int_t periodNumber,
Int_t channelNumber,
Float_t x,
Float_t y = 0. )
inherited

Definition at line 1590 of file TPileupReweighting.cxx.

1590 {
1591 if(!m_isInitialized) {
1592 if (m_printInfo) Info("GetPRWHash","Initializing the subtool..");
1593 Initialize();
1594 }
1595 TH1* hist = m_emptyHistogram.get();
1596 if(!hist) {
1597 Error("GetPRWHash","Tool not configured properly ... please report this!");
1598 throw std::runtime_error("Throwing 47: Tool not configured properly ... please report this!");
1599 }
1600
1601 ULong64_t out = hist->FindFixBin(x,y);
1602 out += (unsigned long)(channelNumber)*10000000000;
1603 out += (unsigned long)(periodNumber)*10000;
1604
1605 return out;
1606
1607}

◆ getPRWHash()

ULong64_t CP::PileupReweightingTool::getPRWHash ( const xAOD::EventInfo & eventInfo)
virtual

return the prw hash used for fast updates of weights at the post-processing level ... see the share/makeWeightTree.C script for usage

Implements CP::IPileupReweightingTool.

Definition at line 403 of file PileupReweightingTool.cxx.

403 {
404 return m_activeTool->GetPRWHash(eventInfo.runNumber(), eventInfo.mcChannelNumber(), eventInfo.averageInteractionsPerCrossing() );
405}

◆ GetRandomLumiBlockNumber()

virtual UInt_t CP::PileupReweightingTool::GetRandomLumiBlockNumber ( UInt_t runNumber)
inlinevirtual

Get a random lumiblock number for the given run number.

Implements CP::IPileupReweightingTool.

Definition at line 47 of file PileupReweightingTool.h.

47{ return m_activeTool->GetRandomLumiBlockNumber(runNumber); }

◆ GetRandomPeriodNumber()

Int_t TPileupReweighting::GetRandomPeriodNumber ( Int_t mcRunNumber)
inherited

Get random period number from the sub-periods assigned to this run number.

Definition at line 1498 of file TPileupReweighting.cxx.

1498 {
1499 if(!m_isInitialized) {
1500 if (m_printInfo) Info("GetRandomPeriodNumber","Initializing the subtool..");
1501 Initialize();
1502 }
1503 if(m_countingMode) { return 0; } //do nothing when in counting mode
1504
1505 Period* p = m_periods[periodNumber];
1506 if(!p) {
1507 Error("GetRandomPeriodNumber","Unrecognised periodNumber: %d",periodNumber);
1508 throw std::runtime_error("Throwing 1: Unrecognised periodNumber");
1509 }
1510
1511 //if no subperiods, we just return ourselves
1512 if(p->subPeriods.size()==0) return p->id;
1513
1514 //need the total lumi of this period
1515 double lumi = p->sumOfWeights[-1] * m_random3->Rndm();
1516
1517 //loop over subPeriods ..
1518 double lumiSum=0;
1519 for(auto subp : p->subPeriods) {
1520 lumiSum += subp->sumOfWeights[-1];
1521 if(lumiSum >= lumi) return subp->id;
1522 }
1523
1524 Error("GetRandomPeriodNumber","overran integrated luminosity for periodNumber=%d",periodNumber);
1525 throw std::runtime_error("Throwing 46.1: overran integrated luminosity for GetRandomPeriodNumber");
1526 return 0;
1527
1528}
std::unique_ptr< TRandom3 > m_random3

◆ GetRandomRunNumber() [1/2]

UInt_t TPileupReweighting::GetRandomRunNumber ( Int_t mcRunNumber)
inherited

Gets a random data run number according to the integrated lumi distribution associated to this mcRunNumber.

allows use of custom reweighting config files

Definition at line 1418 of file TPileupReweighting.cxx.

1418 {
1419 if(!m_isInitialized) {
1420 if (m_printInfo)Info("GetRandomRunNumber","Initializing the subtool..");
1421 Initialize();
1422 }
1423 if(m_countingMode) { return 0; } //do nothing when in counting mode
1424
1425 Period* p = m_periods[periodNumber];
1426 if(!p || !p->primaryHists[-1]) {
1427 Error("GetRandomRunNumber","Unrecognised periodNumber or no data loaded for: %d",periodNumber);
1428 throw std::runtime_error("Throwing 1: Unrecognised periodNumber");
1429 }
1430
1431 double lumi = p->sumOfWeights[-1] * m_random3->Rndm();
1432
1433 //go through the runs assigned to this period ...
1434 double lumiSum=0;
1435 for(auto runNum : p->runNumbers) {
1436 lumiSum += m_runs[runNum].inputHists["None"]->GetSumOfWeights();
1437 if(lumiSum >= lumi-0.00001) return runNum; //small difference is to catch rounding errors
1438 }
1439 Error("GetRandomRunNumber","overran integrated luminosity for periodNumber=%d (%f vs %f)",periodNumber,lumiSum,lumi);
1440 throw std::runtime_error("Throwing 46.1: overran integrated luminosity for GetRandomRunNumber");
1441 return 0;
1442}

◆ GetRandomRunNumber() [2/2]

UInt_t TPileupReweighting::GetRandomRunNumber ( Int_t mcRunNumber,
Double_t mu )
inherited

Get random run number according to integrated lumi distribution for the given mu value (uses the binning of the mu histogram).

Definition at line 1444 of file TPileupReweighting.cxx.

1444 {
1445 if(!m_isInitialized) {
1446 if (m_printInfo) Info("GetRandomRunNumber","Initializing the subtool..");
1447 Initialize();
1448 }
1449 if(m_countingMode) { return 0; } //do nothing when in counting mode
1450
1451 Period* p = m_periods[periodNumber];
1452 if(!p || !p->primaryHists[-1]) {
1453 Error("GetRandomRunNumber","Unrecognised periodNumber or no data loaded for: %d",periodNumber);
1454 throw std::runtime_error("Throwing 1: Unrecognised periodNumber");
1455 }
1456
1457 int bin = m_emptyHistogram->FindFixBin(x);
1458
1459 double lumi = p->primaryHists[-1]->GetBinContent(bin) * p->sumOfWeights[-1] * m_random3->Rndm();
1460
1461 if(!lumi) { return 0; } //no lumi with that mu
1462
1463
1464 //go through the runs assigned to this period ...
1465 double lumiSum=0;
1466 for(auto runNum : p->runNumbers) {
1467 lumiSum += m_runs[runNum].inputHists["None"]->GetBinContent(bin);
1468 if(lumiSum >= lumi-0.00001) return runNum; //small difference is to catch rounding errors
1469 }
1470 Error("GetRandomRunNumber","overran integrated luminosity for periodNumber=%d (%f vs %f)",periodNumber,lumiSum,lumi);
1471 throw std::runtime_error("Throwing 46.1: overran integrated luminosity for GetRandomRunNumber");
1472 return 0;
1473}

◆ getRandomRunNumber()

int CP::PileupReweightingTool::getRandomRunNumber ( const xAOD::EventInfo & eventInfo,
bool mu_dependent )
virtual

Get a random run number for this MC event, using mu-dependent randomization by default ... jetetmiss seem to like it muchly.

Get a random run number for this MC event, mu_dependency is not recommended for this.

Implements CP::IPileupReweightingTool.

Definition at line 429 of file PileupReweightingTool.cxx.

429 {
430 CP::TPileupReweighting* tool = (m_varyRunNumber) ? m_activeTool : this;
431 tool->SetRandomSeed(314159+eventInfo.mcChannelNumber()*2718+eventInfo.eventNumber()); //to make randomization repeatable
432 if(mu_dependent) return tool->GetRandomRunNumber( eventInfo.runNumber(), eventInfo.averageInteractionsPerCrossing() );
433 else return tool->GetRandomRunNumber( eventInfo.runNumber() );
434}
uint64_t eventNumber() const
The current event's event number.

◆ GetRandomSeed()

int CP::TPileupReweighting::GetRandomSeed ( )
inlineinherited

Definition at line 223 of file TPileupReweighting.h.

223{return m_random3->GetSeed();}

◆ GetRunAverageMu()

double CP::TPileupReweighting::GetRunAverageMu ( int run)
inlineinherited

Definition at line 303 of file TPileupReweighting.h.

303{ return m_runs[run].inputHists["None"]->GetMean(); }

◆ GetRunMap()

std::map< UInt_t, Run > & CP::TPileupReweighting::GetRunMap ( )
inlineinherited

Definition at line 454 of file TPileupReweighting.h.

454{ return m_runs; }

◆ GetSecondaryWeight()

Float_t TPileupReweighting::GetSecondaryWeight ( Int_t periodNumber,
Int_t channelNumber,
Float_t x,
Float_t y )
inherited

Definition at line 1707 of file TPileupReweighting.cxx.

1707 {
1708 //= L_j/L_i / N_j/N_i .. secondary hists have already been normalized
1709 if(!m_isInitialized ) {
1710 if (m_printInfo) Info("GetSecondaryWeight","Initializing the subtool..");
1711 Initialize();
1712 }
1713 if(m_countingMode) return 0.;
1714
1715 Period* p = m_periods[periodNumber];
1716 if(!p) {
1717 Error("GetSecondaryWeight","Unrecognised periodNumber: %d",periodNumber);
1718 throw std::runtime_error("Throwing 1: Unrecognised periodNumber");
1719 }
1720 if(p->sumOfWeights.find(channelNumber) == p->sumOfWeights.end()) channelNumber = GetDefaultChannel(periodNumber);//p->defaultChannel;
1721 int bin = p->secondaryHists[channelNumber]->FindFixBin(x,y);
1722 double n = p->secondaryHists[channelNumber]->GetBinContent(bin);
1723 double l = p->secondaryHists[-1]->GetBinContent(bin);
1724
1725 return l/n;
1726}

◆ GetSumOfEventWeights()

virtual Double_t CP::PileupReweightingTool::GetSumOfEventWeights ( Int_t channel)
inlinevirtual

helpful alternative to using the EventBookkeepers info ... assuming you made your PRW Config file!!

Implements CP::IPileupReweightingTool.

Definition at line 64 of file PileupReweightingTool.h.

64{ return m_activeTool->GetSumOfEventWeights(channel); }

◆ GetUnrepresentedDataFraction()

Double_t TPileupReweighting::GetUnrepresentedDataFraction ( Int_t periodNumber,
Int_t channel )
inherited

return the unrepresented data fraction in a given channel .

. when using action=2, you will want to scale up all MC events by 1/(1-unrepFraction) to account for missed data

Definition at line 1392 of file TPileupReweighting.cxx.

1392 {
1393
1394 //return unrepDataByChannel[channel]/GetSumOfEventWeights(-1); //the denominator is equivalent to asking for the total data!
1395
1396
1397 Period* p = m_periods[periodNumber];
1398 if(!p) {
1399 Error("GetUnrepresentedDataFraction","Unrecognised periodNumber: %d",periodNumber);
1400 throw std::runtime_error("Throwing 1: Unrecognised periodNumber");
1401 }
1402
1403 //look for channel through sumOfWeights - because if the channel has no unrepData, it will have no entry in the unrepData map
1404 if(p->sumOfWeights.find(channel) == p->sumOfWeights.end()) channel = GetDefaultChannel(periodNumber);
1405
1406
1407 if(p->sumOfWeights.find(channel) == p->sumOfWeights.end()) {
1408 Error("GetUnrepresentedDataFraction","Unrecognised channel: %d",channel);
1409 throw std::runtime_error("GetUnrepresentedDataFraction: Unrecognised channel");
1410 }
1411
1412 return p->unrepData[channel]/p->sumOfWeights[-1];
1413
1414}

◆ GetUnrepresentedDataWeight()

Float_t CP::TPileupReweighting::GetUnrepresentedDataWeight ( Int_t periodNumber,
Int_t channel )
inlineinherited

Definition at line 134 of file TPileupReweighting.h.

134 {
136 Warning("GetUnrepresentedDataWeight","You should not be applying this weight unless the UnrepresentedDataAction=2");
137 }
138 return 1./(1. - GetUnrepresentedDataFraction(periodNumber,channel));
139 }
Double_t GetUnrepresentedDataFraction(Int_t periodNumber, Int_t channel)
return the unrepresented data fraction in a given channel .

◆ getUnrepresentedDataWeight()

float CP::PileupReweightingTool::getUnrepresentedDataWeight ( const xAOD::EventInfo & eventInfo)
virtual

When using UnrepresentedDataAction=2, you may want to apply this additional weight to ensure sum of weights are preserved.

Implements CP::IPileupReweightingTool.

Definition at line 423 of file PileupReweightingTool.cxx.

423 {
424 return m_activeTool->GetUnrepresentedDataWeight( eventInfo.runNumber(), eventInfo.mcChannelNumber() );
425}

◆ IgnoreConfigFilePeriods()

void CP::TPileupReweighting::IgnoreConfigFilePeriods ( Bool_t in)
inlineinherited

Should the tool ignore period assignments encoded in config file.

Definition at line 146 of file TPileupReweighting.h.

◆ Initialize()

Int_t TPileupReweighting::Initialize ( )
inherited

Initialize this class once before the event loop starts If distribution information is provided, it is assumed to be for the standard pileup reweighting.

Definition at line 1021 of file TPileupReweighting.cxx.

1021 {
1022
1023 //Need to calculate a period weight for each period
1024 //Need a reweighting histogram for each period
1025 //for merged mc run numbers, we must generate or modify the existing mc distributions
1026
1027 //print out the period assignments if in debug mode
1028 if(m_debugging) {
1029 PrintPeriods();
1030 }
1031
1032 if(m_countingMode) {
1033 if (m_printInfo) {
1034 Info("Initialize","In Config File Generating mode. Remember to call WriteToFile!");
1035 }
1036 //need to check no periods have subperiods, this is not allowed in counting mode
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.");
1041 }
1042 }
1043 //histograms are instantiated in the event loop as the channels occur
1044 //can delay period definition here
1045 m_isInitialized=true;
1046 return 0;
1047 }
1048
1049 //find all channels that have too much unrepresented data (more than tolerance). We will remove these channels entirely
1050
1051 std::map<int,std::map<int,bool>> trackWarnings; //map used to avoid reprinting warnings as loop over histogram bins
1052
1053 double totalData(0);
1054 //count up the unrepresented data, indexed by channel
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);
1062 Double_t value = hist->GetBinContent(bin);
1063 totalData += value;
1064 if(value==0.) continue;
1065 bool isUnrep(false);
1066 std::map<Int_t, bool> doneChannels;
1067 for(auto& period : m_periods) {
1068 if(period.first != period.second->id) continue; //skip remappings
1069 if(period.first == -1) continue; //don't look at the global period when calculating unrepresented data
1070 if(!period.second->contains(run.first)) continue;
1071 for(auto& inHist : m_periods[-1]->inputHists) { //use global period to iterate over channels
1072 if(inHist.first<0) continue; //skips any data hists (shouldn't happen really)
1073 if(doneChannels[inHist.first]) continue; //dont doublecount the data if the channel was to blame across multiple period
1074 if(period.second->inputHists.find(inHist.first)==period.second->inputHists.end()) {
1075 //all the data is missing ..
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);
1081 }
1082 } else if(period.second->inputHists[inHist.first]->GetBinContent(bin)==0) {
1083 //hist for this channel in this period exists, but this bin is empty
1084 isUnrep=true;doneChannels[inHist.first]=true;
1085 unrepDataByChannel[inHist.first] += value;
1086 }
1087 }
1088 }
1089 if(isUnrep) unrepDataByChannel[-1] += value; //store total unrep data
1090 }
1091 }
1092 }
1093 if (totalData == 0.){ //should be impossible
1094 Error("Initialize", "totalData is still zero.");
1095 }
1096 if(m_ignoreBadChannels && unrepDataByChannel[-1] && totalData && (unrepDataByChannel[-1]/totalData)>m_unrepDataTolerance) {
1097 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);
1098 //remove channels one-by-one until we are under tolerance
1099 while( (unrepDataByChannel[-1]/totalData)>m_unrepDataTolerance ) {
1100 int worstChannel = -1;
1101 double worstFraction = 0;
1102 for(auto& channel : unrepDataByChannel) {
1103 if(channel.first<0) continue; //ignore the data
1104 if(channel.second/totalData > worstFraction) { worstChannel=channel.first; worstFraction = channel.second/totalData; }
1105 }
1106 if(worstChannel==-1) {
1107 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");
1108 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 }
1110
1111 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]);
1112 //remove the bad channel
1113 RemoveChannel(worstChannel);
1114 unrepDataByChannel.erase(unrepDataByChannel.find(worstChannel));
1115
1116 //recalculate the total unrep data
1117 unrepDataByChannel[-1] = 0;
1118 for(auto& run : m_runs) {
1119 if(run.second.inputHists.find("None") == run.second.inputHists.end()) continue;
1120 TH1* hist = run.second.inputHists["None"].get();
1121 Int_t bin,binx,biny;
1122 for(biny=1; biny<=hist->GetNbinsY(); biny++) {
1123 for(binx=1; binx<=hist->GetNbinsX(); binx++) {
1124 bin = hist->GetBin(binx,biny);
1125 Double_t value = hist->GetBinContent(bin);
1126 if(value==0.) continue;
1127 for(auto& period : m_periods) {
1128 if(period.first != period.second->id) continue; //skip remappings
1129 if(!period.second->contains(run.first)) continue;
1130 bool done(false);
1131 for(auto& inHist : period.second->inputHists) {
1132 if(inHist.first<0) continue; //skips any data hists (shouldn't happen really)
1133 if((inHist.second)->GetBinContent(bin)==0) {
1134 unrepDataByChannel[-1] += value; done=true; break;
1135 }
1136 }
1137 if(done) break;
1138 }
1139 }
1140 }
1141 }
1142 }
1143 }
1144
1145
1146 //need a CompositeTrigger to hold the unprescaled lumi hists ...
1147 m_triggerObjs["None"] = std::make_unique< CompositeTrigger >();
1148
1149 //go through all periods, use inputHists to populate the primary and secondary dists, and fill sumOfWeights and numberOfEntries
1150 for(auto period : m_periods) {
1151 if(period.first != period.second->id) continue; //skips remappings
1152 for(auto& inputHist : period.second->inputHists) {
1153 int channel = inputHist.first;
1154 TH1* hist = inputHist.second.get();
1155 period.second->sumOfWeights[channel] += hist->GetSumOfWeights();
1156 period.second->numberOfEntries[channel] += hist->GetEntries();
1157 if(hist->GetDimension()==1) {
1158 period.second->primaryHists[channel] = CloneEmptyHistogram(period.first,channel);
1159 period.second->primaryHists[channel]->Add(hist);
1160 }
1161 }
1162 //also add all runs that belong to us ... only do the "None" trigger
1163 for(auto& run : m_runs) {
1164 if(!period.second->contains(run.first)) continue;
1165 if(run.second.inputHists.find("None") == run.second.inputHists.end()) continue;
1166 //add to list of runNumbers for this period
1167 period.second->runNumbers.push_back(run.first);
1168 TH1* hist = run.second.inputHists["None"].get();
1169
1170 //sweep over bins, checking for unrepresented data and acting accordingly
1171 Int_t bin,binx,biny;
1172 for(biny=1; biny<=hist->GetNbinsY(); biny++) {
1173 for(binx=1; binx<=hist->GetNbinsX(); binx++) {
1174 bin = hist->GetBin(binx,biny);
1175 Double_t value = hist->GetBinContent(bin);
1176 if(value==0.) continue;
1177 //loop over channels, check for zero in this bin ... only need to do if we haven't checked ourselves
1178 if(period.second->inputBinRedirect.find(bin) == period.second->inputBinRedirect.end()) {
1179 for(auto& inputHist : period.second->inputHists) {
1180 if(inputHist.first<0) continue; //skips data
1181 Double_t mcValue = (inputHist.second)->GetBinContent(bin);
1182 if(mcValue==0.) {
1184 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 }
1186 //if we are doing unrepaction=2, just set to 'not the bin number'. if we are doing action=3, find the nearest good bin
1187 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);}
1188 if(m_unrepresentedDataAction==1||m_unrepresentedDataAction==2) period.second->inputBinRedirect[bin] = bin-1;
1189 else if(m_unrepresentedDataAction==3) period.second->inputBinRedirect[bin] = GetNearestGoodBin(period.first, bin);
1190 break;
1191 }
1192 }
1193 if(period.second->inputBinRedirect.find(bin) == period.second->inputBinRedirect.end()) period.second->inputBinRedirect[bin] = bin; //a good bin
1194 }
1195 //if is a bad bin, act accordingly
1196 if(period.second->inputBinRedirect[bin] != bin) {
1197 run.second.badBins[bin]=value;
1199 //remove this data. we have to remember to do this for the trigger data too if this is the pileup weight
1200 hist->SetBinContent(bin,0);
1201 //also modify the m_inputTriggerHistograms ...
1202 for(auto& triggerDists : run.second.inputHists) triggerDists.second->SetBinContent(bin,0);
1203 } else if(m_unrepresentedDataAction==3) {
1204 //reassign the content to that bin
1205 hist->SetBinContent(period.second->inputBinRedirect[bin],hist->GetBinContent(period.second->inputBinRedirect[bin])+hist->GetBinContent(bin));
1206 hist->SetBinContent(bin,0);
1207 //also modify the m_inputTriggerHistograms ...
1208 for(auto& triggerDists : run.second.inputHists) {
1209 triggerDists.second->SetBinContent(period.second->inputBinRedirect[bin],triggerDists.second->GetBinContent(period.second->inputBinRedirect[bin])+triggerDists.second->GetBinContent(bin));
1210 triggerDists.second->SetBinContent(bin,0);
1211 }
1212 }
1213 }
1214 }
1215 }
1216
1217 //ensure hist is normalized correctly, if was read in from the 'actual mu' config files (where the normalization can be slightly wrong)
1218 if(run.second.nominalFromHists) {
1219 //get the total lumi for the run ...
1220 double totLumi(0);
1221 for(auto lb : run.second.lumiByLbn) {
1222 totLumi += lb.second.first;
1223 }
1224 const double integral = hist->Integral();
1225 if (std::abs(integral) > 0.) {
1226 hist->Scale(totLumi / integral);
1227 }
1228
1229 }
1230
1231 //create the period's 'data' hist if necessary
1232 if( hist->GetDimension()==1 ) {
1233 if(!period.second->primaryHists[-1] ) {
1234 period.second->primaryHists[-1] = CloneEmptyHistogram(period.first,-1);
1235
1236 //this will remain unnormalized, unlike the 'primaryHist'
1237 m_triggerObjs["None"]->triggerHists[period.second->id][0] =
1238 CloneEmptyHistogram( period. first, -1 );
1239 }
1240 }
1241 else if( hist->GetDimension()==2 ) {
1242 if(!period.second->secondaryHists[-1] ) {
1243 auto h = CloneEmptyHistogram(period.first,-1);
1244 period.second->secondaryHists[-1].reset( dynamic_cast< TH2* >( h.release() ) );
1245 period.second->primaryHists[-1].reset(
1246 period.second->secondaryHists[-1]->ProjectionX() );
1247 period.second->primaryHists[-1]->SetDirectory(0);
1248 period.second->primaryHists[-1]->Reset();
1249 m_triggerObjs["None"]->triggerHists[period.second->id][0].reset(
1250 static_cast<TH1*>(period.second->primaryHists[-1]->Clone("triggerHist")) );
1251 m_triggerObjs["None"]->triggerHists[period.second->id][0]->SetDirectory(0);
1252 }
1253
1254 }
1255
1256 }
1257
1258 }
1259
1260
1261 //now that all periods and runs have been checked, with redirects set up where necessary, we actually accumulate the data across the runs
1262 //we should also check if there are any data runs that are not covered by the period assignments
1263
1264 double ignoredData(0);
1265 for(auto& run : m_runs) {
1266 bool covered(false);
1267 TH1* hist = run.second.inputHists["None"].get();
1268 for(auto& period : m_periods) {
1269 if(!period.second->contains(run.first)) continue;
1270 if(period.first!=-1) covered=true; //don't count the global period
1271 if(hist->GetDimension()==1) {
1272 period.second->primaryHists[-1]->Add(hist);
1273 m_triggerObjs["None"]->triggerHists[period.second->id][0]->Add(hist);
1274 } else if(hist->GetDimension()==2) {
1275 period.second->secondaryHists[-1]->Add(hist);
1276 TH1* proj = static_cast<TH2*>(hist)->ProjectionX();
1277 period.second->primaryHists[-1]->Add(proj);
1278 m_triggerObjs["None"]->triggerHists[period.second->id][0]->Add(proj);
1279 delete proj;
1280 }
1281 period.second->sumOfWeights[-1] += hist->GetSumOfWeights();
1282 period.second->numberOfEntries[-1] += hist->GetEntries();
1283 }
1284 if(!covered && m_periods.size()>1) {
1285 Warning("Initialize","loaded data in run %d that is not covered by period assignments",run.first);
1286 ignoredData += hist->GetSumOfWeights();
1287 }
1288 }
1289 //double totalData = (m_unrepresentedDataAction==1) ? (m_periods[-1]->sumOfWeights[-1]+unrepDataByChannel[-1]) : m_periods[-1]->sumOfWeights[-1];
1290 if (totalData == 0){
1291 Error("Initialize", "totalData is zero.");
1292 throw std::runtime_error("totalData is zero after summing. This should never happen.");
1293 }
1294 if(ignoredData>0.) Warning("Initialize", "Period Assignments missed %f%% data",100.*ignoredData/totalData);
1295 if(unrepDataByChannel[-1]) {
1296 double frac = unrepDataByChannel[-1]/totalData;
1297 if( frac > m_unrepDataTolerance) {
1298 Error("Initialize", "%f%% unrepresented data, which suggests something is wrong with your prw config. Try EnableDebugging(true) to investigate",100.* (unrepDataByChannel[-1]/totalData));
1299 }
1301 Warning("Initialize","has %f%% unrepresented data. This was removed (UnrepresentedDataAction=1)",100.*frac);
1302 } else if(m_unrepresentedDataAction==2) {
1303 Warning("Initialize","has %f%% unrepresented data. This was kept in (UnrepresentedDataAction=2)",100.*frac);
1304 } else if(m_unrepresentedDataAction==3) {
1305 if(frac >= m_unrepDataWarningThreshold) {
1306 Warning("Initialize","has %f%% unrepresented data."
1307 " This was reassigned (UnrepresentedDataAction=3)",
1308 100.*frac);
1309 }
1310 } else if(m_unrepresentedDataAction==0) {
1311 Error("Initialize","has %f%% unrepresented data:",100.*frac);
1312 //print the report of which channels caused it
1313 for(auto& it : unrepDataByChannel) {
1314 if(it.first<0) continue; //ignore data
1315 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]);
1316 }
1317 Error("Initialize","Exiting. You must decide how to proceed...");
1318 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");
1319 Error("Initialize","2) use SetUnrepresentedDataAction(1) to remove this data from the weight calculations. You should also veto such data events (using IsUnrepresentedData(..,..) method)");
1320 Error("Initialize","3) use SetUnrepresentedDataAction(2) to leave this data in the calculation. I hope you know what you're doing!!");
1321 Error("Initialize","4) use SetUnrepresentedDataAction(3) to reassign the data to the nearest representable bin");
1322 throw std::runtime_error("Throwing exception 22: Unrepresented data exists. Make a choice how to handle this. See err log for details");
1323 }
1324 //if get here, through the exception if frac is bad
1325 if( frac > m_unrepDataTolerance) {
1326 throw std::runtime_error("Throwing exception 222: Some channel had too much unrepresented data. You should fix your prw file");
1327 }
1328 }
1329
1330
1331 if(m_debugging && m_printInfo) Info("Initialize","Normalizing histograms and cleaning up...");
1332 //now that all the distributions are built. Normalize them all
1333 for(auto period : m_periods) {
1334 if(period.first != period.second->id) continue;
1335 for(auto& pHist : period.second->primaryHists) {
1336 normalizeHistogram(pHist.second.get());
1337 }
1338 for(auto& pHist : period.second->secondaryHists) {
1339 normalizeHistogram(pHist.second.get());
1340 }
1341 period.second->inputHists.clear();
1342 }
1343
1344 //we keep the inputHists for data, because can use that to do random run numbers based on mu
1345
1346 if(m_debugging && m_printInfo) Info("Initialize","...Done");
1347 //if no input histograms were added, we are in counting mode
1348
1349
1350 m_isInitialized=true;
1351
1352 return 0;
1353}
void normalizeHistogram(TH1 *histo)
Normalize histograms.
std::map< Int_t, Double_t > unrepDataByChannel
Int_t GetNearestGoodBin(Int_t thisMCRunNumber, Int_t bin)
Bool_t RemoveChannel(int chanNum)
Removes a channel from the inputs ... this is for experts only.
double integral(TH1 *h)
Definition computils.cxx:59

◆ initialize()

StatusCode CP::PileupReweightingTool::initialize ( void )
virtual

Function initialising the tool.

Reimplemented from asg::AsgTool.

Definition at line 180 of file PileupReweightingTool.cxx.

180 {
181
182 //set debugging if debugging is on:
183 EnableDebugging(this->msgLvl(MSG::DEBUG));
184 PrintInfo(msgLvl(MSG::INFO));
185
186 //convert custom periods vector to a vector of vectors (length 3) ...
187 std::vector<std::vector<int>> customPeriods;
188 for(auto& num : m_customPeriods) {
189 if(customPeriods.size()==0 || customPeriods.back().size()==3) customPeriods.resize(customPeriods.size()+1);
190 customPeriods.back().push_back(num);
191 }
192
193 for(auto& period : customPeriods) {
194 if(period.size()!=3) {
195 ATH_MSG_FATAL("Recevied period with " << period.size() << " numbers. Period configuration requires 3 numbers: periodNumber, startNumber, endNumber");
196 return StatusCode::FAILURE;
197 }
198 AddPeriod(period[0],period[1],period[2]);
199 }
200
201 //see if we need variations
202 if(m_upVariation && (m_prwFiles.size()+m_toolLumicalcFiles.size())!=0) {
203 m_upTool.reset( new TPileupReweighting((name()+"_upVariation").c_str()) );
204 m_upTool->PrintInfo(msgLvl(MSG::INFO));
205 m_upTool->SetParentTool(this);
206 m_upTool->CopyProperties(this);
207 m_upTool->SetDataScaleFactors(m_upVariation);
208 for(auto& period : customPeriods) m_upTool->AddPeriod(period[0],period[1],period[2]); //already checked sizes above
209 }
210 if(m_downVariation && (m_prwFiles.size()+m_toolLumicalcFiles.size())!=0) {
211 m_downTool.reset( new TPileupReweighting((name()+"_downVariation").c_str()) );
212 m_downTool->PrintInfo(msgLvl(MSG::INFO));
213 m_downTool->SetParentTool(this);
214 m_downTool->CopyProperties(this);
215 m_downTool->SetDataScaleFactors(m_downVariation);
216 for(auto& period : customPeriods) m_downTool->AddPeriod(period[0],period[1],period[2]); //already checked sizes above
217 }
218
219 SetDefaultChannel(m_defaultChannel); //handled in GetDefaultChannel method now! if(m_upTool) m_upTool->SetDefaultChannel(m_defaultChannel); if(m_downTool) m_downTool->SetDefaultChannel(m_defaultChannel);
220
221
222 //should we set the period config (file maker mode)
223 if(m_prwFiles.size()+m_toolLumicalcFiles.size()==0) {
224 m_inConfigMode=true;
225 ATH_MSG_INFO("In Config file making mode.");
226 if(m_usePeriodConfig!="auto" && m_usePeriodConfig!="") {
228 }
229#ifndef XAOD_STANDALONE
230 //retrieve histsvc now, otherwise it wont get correctly configured by the time it's used in the finalize ... so it seems
231 ServiceHandle<ITHistSvc> histSvc("THistSvc",name());
232 CHECK( histSvc.retrieve() );
233#endif
234 } else {
235 //have we any prw to load
236 if(m_prwFiles.size() && m_usePeriodConfig=="auto") {
237 //will override the input config period assignments, will assume PRW is so standardized by r21 that we know best!
239 if(m_upTool) m_upTool->IgnoreConfigFilePeriods(true);
240 if(m_downTool) m_downTool->IgnoreConfigFilePeriods(true);
241 UsePeriodConfig("MC16"); //hardcoded period assignments
242 if(m_upTool) m_upTool->UsePeriodConfig("MC16");
243 if(m_downTool) m_downTool->UsePeriodConfig("MC16");
244 }
245
246 for(unsigned int j=0;j<m_prwFiles.size();j++) {
247 ATH_MSG_VERBOSE("Locating File: " << m_prwFiles[j]);
248 std::string file = PathResolverFindCalibFile(m_prwFiles[j]);
249 if(file=="") { ATH_MSG_ERROR("Unable to find the PRW Config file: " << m_prwFiles[j]); return StatusCode::FAILURE; }
250 ATH_MSG_VERBOSE("Adding Config file: " << file);
251 /*m_tool->*/AddConfigFile(file.c_str());
252 if(m_upTool) m_upTool->AddConfigFile(file.c_str());
253 if(m_downTool) m_downTool->AddConfigFile(file.c_str());
254 }
255
256 //have we any lumicalc files to load? .. if we do and had no prwFiles then the user must specify the period configuration
257 if(m_toolLumicalcFiles.size()>0 && m_prwFiles.size()==0) {
258 if(m_usePeriodConfig!="auto" && m_usePeriodConfig!="") {
259 ATH_MSG_INFO("Setting up without a PRW config file, but with period config " << m_usePeriodConfig << ". You will only be able to use random run number and data weight functionality... no reweighting!");
261 ATH_MSG_ERROR("Unrecognised PeriodConfig: " << m_usePeriodConfig); return StatusCode::FAILURE;
262 }
263 m_noWeightsMode=true; //will stop the prw weight being decorated in apply method
264 if(m_upTool) m_upTool->UsePeriodConfig(m_usePeriodConfig);
265 if(m_downTool) m_downTool->UsePeriodConfig(m_usePeriodConfig);
266 } else {
267 ATH_MSG_WARNING("No config files provided, but " << m_toolLumicalcFiles.size() << " lumicalc file provided. Assuming a period config of MC16 ");
268 UsePeriodConfig("MC16");
269 m_noWeightsMode=true; //will stop the prw weight being decorated in apply method
270 if(m_upTool) m_upTool->UsePeriodConfig("MC16");
271 if(m_downTool) m_downTool->UsePeriodConfig("MC16");
272 }
273 }
274
275 for(unsigned int j=0;j<m_toolLumicalcFiles.size();j++) {
276 //see if there's a trigger at the end of the filename .. format is "file:trigger"
277 TString myFile = m_toolLumicalcFiles[j];
278 TString myTrigger = (myFile.Contains(':')) ? TString(myFile(myFile.Last(':')+1,myFile.Length()-myFile.Last(':'))) : TString("None");
279 myFile = (myFile.Contains(':')) ? TString(myFile(0,myFile.Last(':'))) : myFile;
280 ATH_MSG_VERBOSE("Locating File: " << myFile);
281 std::string file = PathResolverFindCalibFile(myFile.Data());
282 if(file=="") { ATH_MSG_ERROR("Unable to find the Lumicalc file: " << myFile); return StatusCode::FAILURE; }
283 /*m_tool->*/AddLumiCalcFile(file.c_str(),myTrigger);
284 if(m_upTool) m_upTool->AddLumiCalcFile(file.c_str(),myTrigger);
285 if(m_downTool) m_downTool->AddLumiCalcFile(file.c_str(),myTrigger);
286 }
287 }
288
289 //register ourselves with the systematic registry!
290 CP::SystematicRegistry& registry = CP::SystematicRegistry::getInstance();
291 if( registry.registerSystematics( *this ) != StatusCode::SUCCESS ) return StatusCode::FAILURE;
292
293
294 //delay initializing underlying tool until first usage, just in case user wants to do any advanced initialization options
295
296 ATH_MSG_DEBUG("Retrieving weight tool...");
297 StatusCode sc = m_weightTool.retrieve();
298 if (sc != StatusCode::SUCCESS) {
299 ATH_MSG_ERROR(" " << m_weightTool->name() << " could not be retrieved.");
300 return sc;
301 }
302 else {
303 ATH_MSG_DEBUG(" " << m_weightTool->name() << " retrieved.");
304 m_weightTool->print();
305 }
306
307 return StatusCode::SUCCESS;
308}
#define ATH_MSG_FATAL(x)
#define ATH_MSG_INFO(x)
#define ATH_MSG_DEBUG(x)
static Double_t sc
std::string PathResolverFindCalibFile(const std::string &logical_file_name)
bool msgLvl(const MSG::Level lvl) const
virtual Int_t AddPeriod(Int_t periodNumber, UInt_t start, UInt_t end)
use these methods when generating config files
static SystematicRegistry & getInstance()
Get the singleton instance of the registry for the curren thread.
StatusCode registerSystematics(const IReentrantSystematicsTool &tool)
effects: register all the systematics from the tool
void EnableDebugging(Bool_t in)
Indicate if additional debugging information should be output.
void SetDefaultChannel(Int_t channel, Int_t mcRunNumber=-1)
Set which channel should be used as a default when specific mc channel distributions cannot be found.
void PrintInfo(Bool_t in)
disable info
Int_t AddLumiCalcFile(const TString &fileName, const TString &trigger="None")
Int_t AddConfigFile(const TString &fileName)
TPileupReweighting(const char *name="TPileupReweighting")
Standard constructor.
void IgnoreConfigFilePeriods(Bool_t in)
Should the tool ignore period assignments encoded in config file.
::StatusCode StatusCode
StatusCode definition for legacy code.

◆ inputHandles()

virtual std::vector< Gaudi::DataHandle * > AthCommonDataStore< AthCommonMsg< AlgTool > >::inputHandles ( ) const
overridevirtualinherited

Return this algorithm's input handles.

We override this to include handle instances from key arrays if they have not yet been declared. See comments on updateVHKA.

◆ isAffectedBySystematic()

bool CP::PileupReweightingTool::isAffectedBySystematic ( const CP::SystematicVariation & systematic) const
virtual

The ISystematicsTool methods.

Implements CP::ISystematicsTool.

Definition at line 121 of file PileupReweightingTool.cxx.

121 {
122 CP::SystematicSet sys = affectingSystematics(); return sys.find( systematic ) != sys.end();
123}
CP::SystematicSet affectingSystematics() const
the list of all systematics this tool can be affected by

◆ IsBadBin()

Int_t TPileupReweighting::IsBadBin ( Int_t thisMCRunNumber,
Int_t bin )
protectedinherited

Definition at line 1357 of file TPileupReweighting.cxx.

1357 {
1358
1359 if(bin<0) return 2; //out of range
1360
1361 Period* p = m_periods[periodNumber];
1362 for(auto& inHist : p->inputHists) {
1363 int channelNumber = inHist.first;
1364 if(channelNumber<0) continue; //skip data hists
1365 if(bin > (inHist.second->GetNbinsX()+2)*(inHist.second->GetNbinsY()+2)*(inHist.second->GetNbinsZ()+2)) return 2; //definitely out of range by this point!
1366 if(inHist.second->GetBinContent(bin)==0) return 1;
1367 }
1368 return 0;
1369
1370}

◆ IsInitialized()

Bool_t CP::TPileupReweighting::IsInitialized ( )
inlineinherited

Definition at line 288 of file TPileupReweighting.h.

288{ return m_isInitialized; }

◆ IsUnrepresentedData()

Bool_t TPileupReweighting::IsUnrepresentedData ( Int_t runNumber,
Float_t x,
Float_t y = 0. )
inherited

Definition at line 1530 of file TPileupReweighting.cxx.

1530 {
1531 int bin = m_emptyHistogram->FindFixBin(x,y);
1532 return ( m_runs[runNumber].badBins[bin] );
1533}

◆ makeTrigger()

std::unique_ptr< CP::TPileupReweighting::CompositeTrigger > TPileupReweighting::makeTrigger ( const TString & s)
protectedinherited

Definition at line 2284 of file TPileupReweighting.cxx.

2284 {
2285
2286 if( m_debugging && m_printInfo ) {
2287 Info( "makeTrigger", "Doing %s", s.Data() );
2288 }
2289
2290 // Find the first operand
2291 TString oper1;
2292 std::unique_ptr< CompositeTrigger > cOper1;
2293 if( s.BeginsWith( "(" ) ) {
2294 // Find closing bracket
2295 int bCounter=1; int i=1;
2296 while( ( bCounter != 0 ) && ( i <= s.Length() ) ) {
2297 if( s( i ) == '(' ) {
2298 bCounter++;
2299 } else if( s( i ) == ')' ) {
2300 bCounter--;
2301 }
2302 i++;
2303 }
2304 if( bCounter != 0 ) {
2305 Error( "makeTrigger", "Missing closing bracket" );
2306 return std::unique_ptr< CompositeTrigger >();
2307 }
2308 oper1 = s( 1, i - 2 );
2309 if( i == s.Length() + 1 ) {
2310 return makeTrigger( oper1 ); //meainingless brackets, just return evaluation
2311 } else {
2312 cOper1 = makeTrigger( oper1 );
2313 if( ! cOper1 ) {
2314 return 0;
2315 }
2316 }
2317 }
2318
2319 // Find the second operand. Do this by finding the first operation at
2320 // this level. If cannot find, then just set val
2321 int i=0;int bCounter=0; int op=0;
2322 while( i <= s.Length() ) {
2323 if( s( i ) == '(' ) {
2324 bCounter++;
2325 } else if( s( i ) == ')' ) {
2326 bCounter--;
2327 } else if( ( s( i ) == '&' ) && ( bCounter == 0 ) ) {
2328 op = 2;
2329 break;
2330 } else if( ( s( i ) == '|' ) && ( bCounter == 0 ) ) {
2331 op = 1;
2332 break;
2333 }
2334 i++;
2335 }
2336
2337
2338 if( op == 0 ) {
2339 if( m_lumicalcFiles.find( s ) == m_lumicalcFiles.end() ) {
2340 Error( "GetDataWeight", "Could not find subTrigger %s", s.Data() );
2341 return std::unique_ptr< CompositeTrigger >();
2342 }
2343 if( cOper1 ) {
2344 return cOper1;
2345 }
2346 auto out = std::make_unique< CompositeTrigger >();
2347 out->op = op;
2348 out->val = s;
2349 return out; //just a value trigger
2350 }
2351
2352 auto out = std::make_unique< CompositeTrigger >();
2353 out->op = op;
2354
2355 if( op == 1 ) { //an OR
2356 if( cOper1 ) {
2357 out->trig1 = std::move( cOper1 );
2358 } else {
2359 oper1 = s( 0, i );
2360 out->trig1 = makeTrigger( oper1 );
2361 if( ! out->trig1 ) {
2362 return std::unique_ptr< CompositeTrigger >();
2363 }
2364 }
2365 TString oper2 = s( i + 1, s.Length() );
2366 out->trig2 = makeTrigger( oper2 );
2367 if( ! out->trig2 ) {
2368 return std::unique_ptr< CompositeTrigger >();
2369 }
2370 return out;
2371 }
2372
2373 // Got here, must be an AND keep going until we hit an OR at this level,
2374 // then make all that the first operand (delete cOper if necessary)
2375 int j = i;
2376 bCounter = 0;
2377 while( j <= s.Length() ) {
2378 if( s( j ) == '(' ) {
2379 bCounter++;
2380 } else if( s( j )== ')' ) {
2381 bCounter--;
2382 } else if( ( s( j ) == '|' ) && ( bCounter == 0 ) ) {
2383 op=1;
2384 break;
2385 }
2386 j++;
2387 }
2388 if( ( j == s.Length() + 1 ) && ( op == 2 ) ) { //no more OR found, set oper2 to remainder
2389 if( cOper1 ) {
2390 out->trig1 = std::move( cOper1 );
2391 } else {
2392 oper1 = s( 0, i );
2393 out->trig1 = makeTrigger( oper1 );
2394 }
2395 TString oper2 = s( i + 1, s.Length() );
2396 if( m_debugging && m_printInfo ) {
2397 Info( "makeTrigger", "Found & %s %s", oper1.Data(), oper2.Data() );
2398 }
2399 out->trig2 = makeTrigger( oper2 );
2400 if( ! out->trig2 ) {
2401 return std::unique_ptr< CompositeTrigger >();
2402 }
2403 return out;
2404 } else if( op ==1 ) { //found an OR, set oper1 to everything up to this
2405
2406 oper1 = s( 0, j );
2407 TString oper2 = s( j + 1, s.Length() );
2408 if( m_debugging && m_printInfo ) {
2409 Info( "makeTrigger", "Found & then | %s %s", oper1.Data(),
2410 oper2.Data() );
2411 }
2412 out->op = op; //updates to an OR
2413 out->trig1 = makeTrigger( oper1 );
2414 if( ! out->trig1 ) {
2415 return std::unique_ptr< CompositeTrigger >();
2416 }
2417 out->trig2 = makeTrigger( oper2 );
2418 if( ! out->trig2 ) {
2419 return std::unique_ptr< CompositeTrigger >();
2420 }
2421 return out;
2422 }
2423 Error( "makeTrigger", "Should never have got here!, but did with %s",
2424 s.Data() );
2425 return std::unique_ptr< CompositeTrigger >();
2426}

◆ MakeWeightTree()

Bool_t TPileupReweighting::MakeWeightTree ( TString channelNumbers,
TString outFile,
TString hashBranch = "PRWHash",
TString weightBranch = "PileupWeight" )
inherited

Definition at line 1536 of file TPileupReweighting.cxx.

1536 {
1537 if(!m_isInitialized ) {
1538 if (m_printInfo) Info("MakeWeightTree","Initializing the subtool..");
1539 Initialize();
1540 }
1541 TH1* hist = m_emptyHistogram.get();
1542 if(!hist) {
1543 Error("MakeWeightTree","Tool not configured properly ... please report this!");
1544 throw std::runtime_error("Throwing 47: Tool not configured properly ... please report this!");
1545 }
1546
1547 //loop over given channels, and loop over all periods (except the global period) and get the pileup weight in each case for each bin
1548 TFile f1(outFile,"RECREATE");
1549
1550 TTree* outTree = new TTree("prwTree","prwTree");
1551 ULong64_t prwHash(0);Float_t weight(0.);
1552 outTree->Branch(hashBranch,&prwHash);
1553 outTree->Branch(weightBranch,&weight);
1554
1555 TObjArray *tx = channelNumbers.Tokenize(",");
1556 for (Int_t i = 0; i < tx->GetEntries(); i++) {
1557 int channelNumber = ((TObjString *)(tx->At(i)))->String().Atoi();
1558 if(channelNumber>999999 || channelNumber<0) {
1559 Error("MakeWeightTree","ChannelNumber can not be bigger than 999999 or less than 0 ... got %d",channelNumber);
1560 f1.Close();
1561 return 0;
1562 }
1563 for(auto& period : m_periods) {
1564 if(period.first==-1) continue;
1565 int periodNumber = period.first;
1566 for(int i=1;i<=hist->GetNbinsX();i++) {
1567 double x = hist->GetXaxis()->GetBinCenter(i);
1568 for(int j=1;j<=hist->GetNbinsY();j++) {
1569 double y = hist->GetYaxis()->GetBinCenter(j);
1570 weight = GetCombinedWeight(periodNumber,channelNumber,x,y);
1571 prwHash = GetPRWHash(periodNumber,channelNumber,x,y);
1572 outTree->Fill();
1573 }
1574 }
1575
1576 }
1577 }
1578
1579 outTree->BuildIndex(hashBranch.Data());
1580 outTree->Write();
1581 f1.Close();
1582
1583 if (m_printInfo) {
1584 Info("MakeWeightTree","Successfully wrote prwTree to %s",outFile.Data());
1585 }
1586
1587 return true;
1588}
Float_t GetCombinedWeight(Int_t periodNumber, Int_t channelNumber, Float_t x, Float_t y=0.)
ULong64_t GetPRWHash(Int_t periodNumber, Int_t channelNumber, Float_t x, Float_t y=0.)
outFile
Comment Out Those You do not wish to run.

◆ Merge()

Int_t TPileupReweighting::Merge ( TCollection * coll)

Definition at line 238 of file TPileupReweighting.cxx.

2045 {
2046 if(!coll) return 0;
2047 if(coll->IsEmpty()) return 0;
2048
2049 // Iterate over the elements of the collection:
2050 TIter next( coll );
2051 TObject* obj = 0;
2052 while( ( obj = next() ) ) {
2053
2054 // Check that the element is of the right type:
2055 CP::TPileupReweighting* vobj = dynamic_cast< CP::TPileupReweighting* >( obj );
2056 if( ! vobj ) {
2057 Error( "Merge", "Unknown object type encountered: %s",obj->ClassName() );
2058 return 0;
2059 }
2060
2061 //merge the inputHistograms ... all the periods should be identical
2062 for(auto period : vobj->m_periods) {
2063 if(period.first != period.second->id) continue;
2064 for(auto& iHist : period.second->inputHists) {
2065 if(GetInputHistogram(period.first,iHist.first)==0) {
2066 m_periods[period.first]->inputHists[iHist.first].reset(
2067 dynamic_cast<TH1*>(iHist.second->Clone(iHist.second->GetName())) );
2068 m_periods[period.first]->inputHists[iHist.first]->SetDirectory(0);
2069 } else {
2070 GetInputHistogram(period.first,iHist.first)->Add(iHist.second.get());
2071 }
2072 }
2073 }
2074 //also must remember to merge the runs too (where the data is held)
2075 for(auto& run : vobj->m_runs) {
2076 for(auto& iHist : run.second.inputHists) {
2077 if( ! m_runs[run.first].inputHists[iHist.first] ) {
2078 m_runs[run.first].inputHists[iHist.first].reset(
2079 dynamic_cast<TH1*>( iHist.second->Clone(iHist.second->GetName())) );
2080 m_runs[run.first].inputHists[iHist.first]->SetDirectory(0);
2081 } else {
2082 m_runs[run.first].inputHists[iHist.first]->Add(iHist.second.get());
2083 }
2084 }
2085 }
2086 }
2087
2088 return 1;
2089}
TH1 * GetInputHistogram(Int_t channelNumber, Int_t periodNumber)

◆ msg()

MsgStream & AthCommonMsg< AlgTool >::msg ( ) const
inlineinherited

Definition at line 24 of file AthCommonMsg.h.

24 {
25 return this->msgStream();
26 }

◆ msg_level_name()

const std::string & asg::AsgTool::msg_level_name ( ) const
inherited

A deprecated function for getting the message level's name.

Instead of using this, weirdly named function, user code should get the string name of the current minimum message level (in case they really need it...), with:

MSG::name( msg().level() )

This function's name doesn't follow the ATLAS coding rules, and as such will be removed in the not too distant future.

Returns
The string name of the current minimum message level that's printed

Definition at line 101 of file AsgTool.cxx.

101 {
102
103 return MSG::name( msg().level() );
104 }
MsgStream & msg() const
const std::string & name(Level lvl)
Convenience function for translating message levels to strings.
Definition MsgLevel.cxx:19

◆ msgLvl()

bool AthCommonMsg< AlgTool >::msgLvl ( const MSG::Level lvl) const
inlineinherited

Definition at line 30 of file AthCommonMsg.h.

30 {
31 return this->msgLevel(lvl);
32 }

◆ normalizeHistogram()

void TPileupReweighting::normalizeHistogram ( TH1 * histo)
protectedinherited

Normalize histograms.

Definition at line 2002 of file TPileupReweighting.cxx.

2002 {
2003 // normalize the data histogram based on which sort of histogram it is
2004 if(hist){
2005 if(hist->InheritsFrom("TH3")) {
2006 Error("normalizeHistogram","3D reweighting not supported yet");
2007 throw std::runtime_error("Throwing 3: 3D reweighting not supported yet");
2008 }
2009 else if(hist->InheritsFrom("TH2")) {
2010 bool skipNorm=false;
2011 //normalize each bin according to the projection in x
2012 TH1D* proj = static_cast<TH2*>(hist)->ProjectionX();
2013 Int_t bin,binx,biny,binz;
2014 for(binz=1; binz<=hist->GetNbinsZ(); binz++) {
2015 for(biny=1; biny<=hist->GetNbinsY(); biny++) {
2016 for(binx=1; binx<=hist->GetNbinsX(); binx++) {
2017 bin = hist->GetBin(binx,biny,binz);
2018 Double_t value = hist->GetBinContent(bin);
2019 Double_t normalizer = proj->GetBinContent(binx);
2020 if(normalizer!=0.0) {
2021 hist->SetBinContent(bin,value/normalizer);
2022 } else {
2023 skipNorm=true;
2024 }
2025 }
2026 }
2027 }
2028 delete proj;
2029 if(skipNorm && m_debugging) Warning("normalizeHistogram","Skipped normalization in hist %s",hist->GetName());
2030 } else {
2031 //normalize to the sum of weights
2032 if(hist->GetSumOfWeights()!=0.0) {
2033 hist->Scale(1.0/hist->GetSumOfWeights());
2034 } else {
2035 if (m_debugging) Warning("normalizeHistogram","Skipping Normalizing histogram %s to ~zero: %f",hist->GetName(),hist->GetSumOfWeights());
2036 }
2037 }
2038 } else {
2039 Error("normalizeHistogram","Non existent histogram for normalizing");throw std::runtime_error("Throwing 56");
2040 }
2041}

◆ outputHandles()

virtual std::vector< Gaudi::DataHandle * > AthCommonDataStore< AthCommonMsg< AlgTool > >::outputHandles ( ) const
overridevirtualinherited

Return this algorithm's output handles.

We override this to include handle instances from key arrays if they have not yet been declared. See comments on updateVHKA.

◆ passTriggerBeforePrescale()

bool CP::PileupReweightingTool::passTriggerBeforePrescale ( const TString & trigger) const
protectedvirtual

Reimplemented from CP::TPileupReweighting.

Definition at line 112 of file PileupReweightingTool.cxx.

112 {
113 if(m_tdt.empty()) return TPileupReweighting::passTriggerBeforePrescale(trigger);
114 ATH_MSG_VERBOSE("Checking tdt decision of " << trigger);
115 //Note that the trigger *must* be a rerun trigger if this result is to be valid ... could check this in the trigconf is absolutely necessary
116 //but for now we just assume it's a rerun
117 //if it's not rerun, all we will get back here is the TAP result
118 return m_tdt->isPassed( trigger.Data() , TrigDefs::Physics | TrigDefs::allowResurrectedDecision ); // Definitions in TrigDecisionInterface/Conditions.h
119}
virtual bool passTriggerBeforePrescale(const TString &trigger) const

◆ print()

◆ PrintInfo()

void CP::TPileupReweighting::PrintInfo ( Bool_t in)
inlineinherited

disable info

Definition at line 120 of file TPileupReweighting.h.

120{ m_printInfo = in; }

◆ PrintPeriods()

void CP::TPileupReweighting::PrintPeriods ( )
inlineinherited

Definition at line 414 of file TPileupReweighting.h.

414{ for(auto p : m_periods) {std::cout << p.first << " -> "; p.second->print("");} }

◆ recommendedSystematics()

CP::SystematicSet CP::PileupReweightingTool::recommendedSystematics ( ) const
virtual

the list of all systematics this tool recommends to use

Implements CP::IReentrantSystematicsTool.

Definition at line 132 of file PileupReweightingTool.cxx.

132 {
133 return affectingSystematics();
134}

◆ RemapPeriod()

void TPileupReweighting::RemapPeriod ( Int_t periodNumber1,
Int_t periodNumber2 )
inherited

Combine two period numbers.

Histos are merged and the first number will be redirected to the second (the second is created if it doesn't exist)

Definition at line 63 of file TPileupReweighting.cxx.

63 {
64 //check if periodNumber2 exists
65 if(m_periods.find(periodNumber2)==m_periods.end()) {
66 m_periodList.emplace_back( periodNumber2, 0, 0, GetDefaultChannel(-1) );
67 m_periods[periodNumber2] = &( m_periodList.back() );
68 }
69 m_periods[periodNumber1] = m_periods[periodNumber2];
70}
std::list< Period > m_periodList
List physically holding (owning) period objects.

◆ RemoveChannel()

Bool_t TPileupReweighting::RemoveChannel ( int chanNum)
inherited

Removes a channel from the inputs ... this is for experts only.

Definition at line 1001 of file TPileupReweighting.cxx.

1001 {
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!");
1005 }
1006
1007 bool found(false);
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;
1012 else {
1013 found=true;
1014 itr = period.second->inputHists.erase(itr);
1015 }
1016 }
1017 }
1018 return found;
1019}

◆ renounce()

std::enable_if_t< std::is_void_v< std::result_of_t< decltype(&T::renounce)(T)> > &&!std::is_base_of_v< SG::VarHandleKeyArray, T > &&std::is_base_of_v< Gaudi::DataHandle, T >, void > AthCommonDataStore< AthCommonMsg< AlgTool > >::renounce ( T & h)
inlineprotectedinherited

Definition at line 380 of file AthCommonDataStore.h.

381 {
382 h.renounce();
384 }
std::enable_if_t< std::is_void_v< std::result_of_t< decltype(&T::renounce)(T)> > &&!std::is_base_of_v< SG::VarHandleKeyArray, T > &&std::is_base_of_v< Gaudi::DataHandle, T >, void > renounce(T &h)

◆ renounceArray()

void AthCommonDataStore< AthCommonMsg< AlgTool > >::renounceArray ( SG::VarHandleKeyArray & handlesArray)
inlineprotectedinherited

remove all handles from I/O resolution

Definition at line 364 of file AthCommonDataStore.h.

364 {
366 }

◆ ResetCountingMode()

void CP::TPileupReweighting::ResetCountingMode ( )
inlineinherited

This method is DEFINITELY EXPERT USE ONLY.

Used in the checkPRWConfigFile utitlity

Definition at line 293 of file TPileupReweighting.h.

293{ m_countingMode=true; }

◆ ResetTriggerBits()

void CP::TPileupReweighting::ResetTriggerBits ( )
inlineinherited

Definition at line 301 of file TPileupReweighting.h.

301{ m_triggerPassBits.clear(); }
std::map< TString, bool > m_triggerPassBits

◆ runLbnOK()

bool CP::PileupReweightingTool::runLbnOK ( Int_t runNbr,
Int_t lbn )
protectedvirtual

Reimplemented from CP::TPileupReweighting.

Definition at line 107 of file PileupReweightingTool.cxx.

107 {
108 if(m_grlTool.empty()) return true;
109 return m_grlTool->passRunLB(runNbr,lbn);
110}

◆ SetBinning() [1/2]

virtual Int_t CP::PileupReweightingTool::SetBinning ( Int_t nbinsx,
Double_t * xbins,
Int_t nbinsy = 0,
Double_t * ybins = 0 )
inlinevirtual

Implements CP::IPileupReweightingTool.

Definition at line 60 of file PileupReweightingTool.h.

60{ return m_activeTool->SetBinning(nbinsx, xbins, nbinsy, ybins); }

◆ SetBinning() [2/2]

virtual Int_t CP::PileupReweightingTool::SetBinning ( TH1 * hist)
inlinevirtual

Implements CP::IPileupReweightingTool.

Definition at line 62 of file PileupReweightingTool.h.

62{ return m_activeTool->SetBinning(hist); }

◆ SetDataScaleFactors()

void CP::TPileupReweighting::SetDataScaleFactors ( Float_t x,
Float_t y = 1. )
inlineinherited

Scale the LumiMetaData mu values by this factor.

Definition at line 156 of file TPileupReweighting.h.

◆ SetDefaultChannel()

void TPileupReweighting::SetDefaultChannel ( Int_t channel,
Int_t mcRunNumber = -1 )
inherited

Set which channel should be used as a default when specific mc channel distributions cannot be found.

default channels can now be assigned for each mc run number .. mcRunNumber=-1 is the global default

Definition at line 72 of file TPileupReweighting.cxx.

72 {
73 //check if periodNumber2 exists
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() );
77 } else {
78 m_periods[periodNumber]->SetDefaultChannel(channel);
79 }
80}

◆ SetMCScaleFactors()

void CP::TPileupReweighting::SetMCScaleFactors ( Float_t x,
Float_t y = 1. )
inlineinherited

Definition at line 157 of file TPileupReweighting.h.

◆ SetParentTool()

void CP::TPileupReweighting::SetParentTool ( TPileupReweighting * tool)
inlineinherited

Definition at line 296 of file TPileupReweighting.h.

296{ m_parentTool = tool; }

◆ SetRandomSeed()

void CP::TPileupReweighting::SetRandomSeed ( int seed)
inlineinherited

Definition at line 222 of file TPileupReweighting.h.

222{m_random3->SetSeed(seed);}

◆ SetTriggerBit()

void CP::TPileupReweighting::SetTriggerBit ( const TString & trigger,
bool in = true )
inlineinherited

Definition at line 300 of file TPileupReweighting.h.

300{ m_triggerPassBits[trigger]=in; }

◆ SetUniformBinning()

virtual Int_t CP::PileupReweightingTool::SetUniformBinning ( Int_t nbinsx,
Double_t xlow,
Double_t xup,
Int_t nbinsy = 0,
Double_t ylow = 0,
Double_t yup = 0 )
inlinevirtual

Implements CP::IPileupReweightingTool.

Definition at line 61 of file PileupReweightingTool.h.

61{ return m_activeTool->SetUniformBinning(nbinsx, xlow, xup, nbinsy, ylow, yup); }

◆ SetUnrepresentedDataAction()

void CP::TPileupReweighting::SetUnrepresentedDataAction ( Int_t action,
Double_t tolerance = 0.05 )
inlineinherited

Set how to handle configurations where some of your data has no corresponding mc to describe it 0=Default (Throw exception), 1=Subtract lumi from normalizations (i.e.

discard data), 2=keep lumi and continue

Definition at line 124 of file TPileupReweighting.h.

124 {
125 if(action<0 || action>3) {
126 Fatal("SetUnrepresentedDataAction","Set action=%d - I'm afraid I can't let you do that, Dave",action);
127 throw std::runtime_error("Throwing 2001");
128 }
130 m_unrepDataTolerance=tolerance; //applicable for action=2 mode. Default is 5%
131 }
@ Fatal
Definition ZDCMsg.h:23
constexpr double tolerance

◆ sysInitialize()

virtual StatusCode AthCommonDataStore< AthCommonMsg< AlgTool > >::sysInitialize ( )
overridevirtualinherited

Perform system initialization for an algorithm.

We override this to declare all the elements of handle key arrays at the end of initialization. See comments on updateVHKA.

Reimplemented in asg::AsgMetadataTool, AthCheckedComponent< AthAlgTool >, AthCheckedComponent<::AthAlgTool >, and DerivationFramework::CfAthAlgTool.

◆ sysStart()

virtual StatusCode AthCommonDataStore< AthCommonMsg< AlgTool > >::sysStart ( )
overridevirtualinherited

Handle START transition.

We override this in order to make sure that conditions handle keys can cache a pointer to the conditions container.

◆ updateHandler()

void CP::PileupReweightingTool::updateHandler ( Gaudi::Details::PropertyBase & )

Definition at line 98 of file PileupReweightingTool.cxx.

98 {
99 // commenting this out as it doesn't compile anymore
100 // leaving it to domain expert to decide whether to keep or remove it
101 // //call the original update handler
102 // this->msg_update_handler(p);
103 EnableDebugging(this->msgLvl(MSG::DEBUG));
104}

◆ updateVHKA()

void AthCommonDataStore< AthCommonMsg< AlgTool > >::updateVHKA ( Gaudi::Details::PropertyBase & )
inlineinherited

Definition at line 308 of file AthCommonDataStore.h.

308 {
309 // debug() << "updateVHKA for property " << p.name() << " " << p.toString()
310 // << " size: " << m_vhka.size() << endmsg;
311 for (auto &a : m_vhka) {
313 for (auto k : keys) {
314 k->setOwner(this);
315 }
316 }
317 }
std::vector< SG::VarHandleKeyArray * > m_vhka

◆ UsePeriodConfig()

Int_t TPileupReweighting::UsePeriodConfig ( const TString & configName)
inherited

use a hardcoded period configuration

Definition at line 234 of file TPileupReweighting.cxx.

234 {
235 if(configName=="MC11a") {
236 AddPeriod(180164, 177986,180481); //associates mc runnumber 180164 with data period 177986 to 180481 (period B-D)
237 AddPeriod(183003, 180614,184169); //period E-H
238 AddPeriod(185649, 185353,186934); //period I-K1. For I-K you would change the last number to 187815
239 AddPeriod(185761, 186935,191933); //everything else. Thanks Ellie!
240 SetUniformBinning(100,0,50);
241 if (m_printInfo) {
242 Info("UsePeriodConfig","Using MC11a Period configuration");
243 }
244 return 0;
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);
251 if (m_printInfo) {
252 Info("UsePeriodConfig","Using MC11b/c Period configuration");
253 }
254 return 0;
255 } else if(configName=="MC12a") {
256 AddPeriod(195847,200804,216432);
257 //mc12a binning is in integer values of mu
258
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");
262 return -1;
263 }
264
265 SetUniformBinning(50,-0.5,49.5);
266 if (m_printInfo) {
267 Info("UsePeriodConfig","Using MC12a Period configuration");
268 }
269 return 0;
270 } else if(configName=="MC12b") {
271 AddPeriod(195848,200804,216432);
272 //mc12b binning is in integer values of mu
273
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");
277 return -1;
278 }
279
280 SetUniformBinning(50,-0.5,49.5);
281 if (m_printInfo) {
282 Info("UsePeriodConfig","Using MC12b Period configuration");
283 }
284 return 0;
285 } else if(configName=="MC12ab") {
286 AddPeriod(195847,200804,216432);
287 AddPeriod(195848,200804,216432);
288
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");
292 return -1;
293 }
294
295 //mc12a/b binning is in integer values of mu
296 SetUniformBinning(50,-0.5,49.5);
297 if (m_printInfo) {
298 Info("UsePeriodConfig","Using MC12ab Period configuration");
299 }
300 return 0;
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");
306 return -1;
307 }
308 SetUniformBinning(50,-0.5,49.5);
309 if (m_printInfo) {
310 Info("UsePeriodConfig","Using MC14_8TeV Period configuration");
311 }
312 return 0;
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");
318 return -1;
319 }
320 SetUniformBinning(100,-0.5,99.5);
321 if (m_printInfo) {
322 Info("UsePeriodConfig","Using MC14_13TeV Period configuration");
323 }
324 return 0;
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); //mc15c for pPb data in 2016
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");
334 return -1;
335 }
336 SetUniformBinning(100,0,100);
337 if (m_printInfo) {
338 Info("UsePeriodConfig","Using MC15 Period configuration");
339 }
340 return 0;
341 } else if(configName=="Run2") {
342 m_autoRunStart = 222222; m_autoRunEnd = 999999; //periods will be automatically added during Fill
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");
346 return -1;
347 }
348 SetUniformBinning(100,0,100);
349 if (m_printInfo) {
350 Info("UsePeriodConfig","Using Run2 Period configuration, which assumes period assignment of 222222 to 999999");
351 }
352 return 0;
353 } else if(configName=="MC16") {
354 /* period configs are now assigned through the parent tool for MC16 */
355
356 SetUniformBinning(100,0,100);
357 if (m_printInfo) {
358 Info("UsePeriodConfig","Using MC16 Period configuration");
359 }
360 return 0;
361 }
362 Error("UsePeriodConfig","Unrecognized period config");
363 return -1;
364}
Int_t SetUniformBinning(Int_t nbinsx, Double_t xlow, Double_t xup, Int_t nbinsy=0, Double_t ylow=0, Double_t yup=0)

◆ WriteToFile() [1/2]

Int_t TPileupReweighting::WriteToFile ( const TString & filename = "")
inherited

Definition at line 1894 of file TPileupReweighting.cxx.

1894 {
1895
1896 if(!m_countingMode) {Warning("WriteToFile","Not in counting mode, so no file will be written");return 0;}
1897
1898
1899 //build a TTree with the correct mc structure, and dump the mc histogram info in to it
1900 //also build aggregate histograms across all channels - shouldn't be used as input histograms unless for a single channel
1901 TString filename = fname;
1902 filename += (filename=="") ? TString(this->GetName()) + ".prw.root" : "";
1903
1904 //loop over the weights. "pileup" gets it own MCPileupReweighting ttree. ... since we got rid of weightNames in this version, everything goes in MCPileupReweighting now!
1905 //data goes in to DataCustomReweighting. other goes in to MCCustomReweighting
1906 TFile* outFile = TFile::Open(filename,"RECREATE");
1907 Int_t r = WriteToFile(outFile);
1908 outFile->Close();
1909 return r;
1910}

◆ WriteToFile() [2/2]

Int_t TPileupReweighting::WriteToFile ( TFile * outFile)
inherited

Definition at line 1913 of file TPileupReweighting.cxx.

1913 {
1914 if(!m_countingMode) {Warning("WriteToFile","Not in counting mode, so no file will be written");return 0;}
1915
1916 TDirectory* origDir = gDirectory;
1917
1918 outFile->cd();
1919
1920 std::unique_ptr< TTree > outTreeMC;
1921 std::unique_ptr< TTree > outTreeData;
1922 Int_t channel = 0; UInt_t runNumber = 0;
1923 auto pStarts = std::make_unique< std::vector< UInt_t > >();
1924 auto pStartsPtr = pStarts.get();
1925 auto pEnds = std::make_unique< std::vector< UInt_t > >();
1926 auto pEndsPtr = pEnds.get();
1927 Char_t histName[150];
1928
1929
1930 //loop over periods ... periods only get entry in table if they have an input histogram
1931 for(auto period : m_periods) {
1932 if(period.first != period.second->id) continue; //skips redirects
1933 if(period.first<0) continue; //avoid the global run number
1934 runNumber = period.first;
1935 pStarts->clear();
1936 pEnds->clear();
1937 if(period.second->subPeriods.size()==0) {
1938 pStarts->push_back(period.second->start); pEnds->push_back(period.second->end);
1939 }
1940 else {
1941 for(auto subp : period.second->subPeriods) {
1942 pStarts->push_back(subp->start); pEnds->push_back(subp->end);
1943 }
1944 }
1945 for(auto& inHist : period.second->inputHists) {
1946 channel = inHist.first;
1947 TH1* hist = inHist.second.get();
1948 strncpy(histName,hist->GetName(),sizeof(histName)-1);
1949 hist->Write();
1950
1951 if(!outTreeMC) {
1952 outTreeMC.reset( new TTree("MCPileupReweighting","MCPileupReweighting") );
1953 outTreeMC->Branch("Channel",&channel);
1954 outTreeMC->Branch("RunNumber",&runNumber);
1955 outTreeMC->Branch("PeriodStarts",&pStartsPtr);
1956 outTreeMC->Branch("PeriodEnds",&pEndsPtr);
1957 outTreeMC->Branch("HistName",&histName,"HistName/C");
1958 }
1959 outTreeMC->Fill();
1960 }
1961 }
1962
1963 //loop over data
1964 for(auto& run : m_runs) {
1965 runNumber = run.first;
1966 if(run.second.inputHists.find("None")==run.second.inputHists.end()) continue;
1967
1968 TH1* hist = run.second.inputHists["None"].get();
1969 strncpy(histName,hist->GetName(),sizeof(histName)-1);
1970 hist->Write();
1971 if(!outTreeData) {
1972 outTreeData.reset( new TTree("DataPileupReweighting","DataPileupReweighting") );
1973 outTreeData->Branch("RunNumber",&runNumber);
1974 outTreeData->Branch("HistName",&histName,"HistName/C");
1975 }
1976 outTreeData->Fill();
1977 }
1978
1979
1980 //write the non-zero ttrees
1981 if( outTreeMC ) {
1982 outTreeMC->Write();
1983 }
1984 if( outTreeData ) {
1985 outTreeData->Write();
1986 }
1987
1988 if (m_printInfo) {
1989 Info("WriteToFile", "Successfully generated config file: %s",outFile->GetName());
1990 Info("WriteToFile", "Happy Reweighting :-)");
1991 }
1992
1994
1995 return 0;
1996}

Member Data Documentation

◆ m_activeTool

CP::TPileupReweighting* CP::PileupReweightingTool::m_activeTool
private

Definition at line 149 of file PileupReweightingTool.h.

◆ m_autoRunEnd

int CP::TPileupReweighting::m_autoRunEnd = 0
protectedinherited

Definition at line 476 of file TPileupReweighting.h.

◆ m_autoRunStart

int CP::TPileupReweighting::m_autoRunStart = 0
protectedinherited

Definition at line 475 of file TPileupReweighting.h.

◆ m_configStream

std::string CP::PileupReweightingTool::m_configStream
private

Definition at line 140 of file PileupReweightingTool.h.

◆ m_countingMode

Bool_t CP::TPileupReweighting::m_countingMode
protectedinherited

Definition at line 335 of file TPileupReweighting.h.

◆ m_customPeriods

std::vector<int> CP::PileupReweightingTool::m_customPeriods
private

Default weight tool in standalone mode.

Definition at line 165 of file PileupReweightingTool.h.

◆ m_dataScaleFactorX

Float_t CP::TPileupReweighting::m_dataScaleFactorX
protectedinherited

Definition at line 338 of file TPileupReweighting.h.

◆ m_dataScaleFactorY

Float_t CP::TPileupReweighting::m_dataScaleFactorY
protectedinherited

Definition at line 338 of file TPileupReweighting.h.

◆ m_debugging

Bool_t CP::TPileupReweighting::m_debugging
protectedinherited

Definition at line 333 of file TPileupReweighting.h.

◆ m_defaultChannel

int CP::PileupReweightingTool::m_defaultChannel
private

Definition at line 156 of file PileupReweightingTool.h.

◆ m_defaultWeightTool

std::unique_ptr< IWeightTool > CP::PileupReweightingTool::m_defaultWeightTool
private

Definition at line 168 of file PileupReweightingTool.h.

◆ m_detStore

StoreGateSvc_t AthCommonDataStore< AthCommonMsg< AlgTool > >::m_detStore
privateinherited

Pointer to StoreGate (detector store by default).

Definition at line 393 of file AthCommonDataStore.h.

◆ m_doGlobalDataWeight

Bool_t CP::TPileupReweighting::m_doGlobalDataWeight
protectedinherited

Definition at line 345 of file TPileupReweighting.h.

◆ m_doneConfigs

std::map<int, bool> CP::PileupReweightingTool::m_doneConfigs
private

Definition at line 158 of file PileupReweightingTool.h.

◆ m_doPrescaleWeight

Bool_t CP::TPileupReweighting::m_doPrescaleWeight = false
protectedinherited

Definition at line 346 of file TPileupReweighting.h.

◆ m_downTool

std::unique_ptr< CP::TPileupReweighting > CP::PileupReweightingTool::m_downTool
private

Definition at line 145 of file PileupReweightingTool.h.

◆ m_downVariation

double CP::PileupReweightingTool::m_downVariation
private

Definition at line 147 of file PileupReweightingTool.h.

◆ m_emptyHistogram

std::unique_ptr< TH1 > CP::TPileupReweighting::m_emptyHistogram
protectedinherited

the empty histogram used for this weight... effectively holds the configuration of the binning

Definition at line 359 of file TPileupReweighting.h.

◆ m_evtStore

StoreGateSvc_t AthCommonDataStore< AthCommonMsg< AlgTool > >::m_evtStore
privateinherited

Pointer to StoreGate (event store by default).

Definition at line 390 of file AthCommonDataStore.h.

◆ m_grlTool

ToolHandle<IGoodRunsListSelectionTool> CP::PileupReweightingTool::m_grlTool
private

Definition at line 171 of file PileupReweightingTool.h.

◆ m_ignoreBadChannels

Bool_t CP::TPileupReweighting::m_ignoreBadChannels
protectedinherited

Definition at line 471 of file TPileupReweighting.h.

◆ m_ignoreFilePeriods

Bool_t CP::TPileupReweighting::m_ignoreFilePeriods
protectedinherited

Definition at line 341 of file TPileupReweighting.h.

◆ m_inConfigMode

bool CP::PileupReweightingTool::m_inConfigMode
private

Definition at line 141 of file PileupReweightingTool.h.

◆ m_isInitialized

Bool_t CP::TPileupReweighting::m_isInitialized
protectedinherited

Definition at line 337 of file TPileupReweighting.h.

◆ m_lumicalcFiles

std::map<TString,std::vector<TString> > CP::TPileupReweighting::m_lumicalcFiles
protectedinherited

map storing the lumicalc file locations - used when building DataPileupWeights

Definition at line 350 of file TPileupReweighting.h.

◆ m_lumicalcRunNumberOffset

Int_t CP::TPileupReweighting::m_lumicalcRunNumberOffset
protectedinherited

Definition at line 347 of file TPileupReweighting.h.

◆ m_lumiVectorIsLoaded

Bool_t CP::TPileupReweighting::m_lumiVectorIsLoaded
protectedinherited

Definition at line 337 of file TPileupReweighting.h.

◆ m_mcScaleFactorX

Float_t CP::TPileupReweighting::m_mcScaleFactorX
protectedinherited

Definition at line 339 of file TPileupReweighting.h.

◆ m_mcScaleFactorY

Float_t CP::TPileupReweighting::m_mcScaleFactorY
protectedinherited

Definition at line 339 of file TPileupReweighting.h.

◆ m_metadata

std::map<TString, std::map<Int_t, Double_t> > CP::TPileupReweighting::m_metadata
protectedinherited

channel metadata map

Definition at line 364 of file TPileupReweighting.h.

◆ m_metadatatree

TTree* CP::TPileupReweighting::m_metadatatree
protectedinherited

Definition at line 342 of file TPileupReweighting.h.

◆ m_nextPeriodNumber

Int_t CP::TPileupReweighting::m_nextPeriodNumber
protectedinherited

Definition at line 340 of file TPileupReweighting.h.

◆ m_noWeightsMode

bool CP::PileupReweightingTool::m_noWeightsMode
private

Definition at line 160 of file PileupReweightingTool.h.

◆ m_parentTool

TPileupReweighting* CP::TPileupReweighting::m_parentTool
protectedinherited

Definition at line 331 of file TPileupReweighting.h.

◆ m_periodList

std::list< Period > CP::TPileupReweighting::m_periodList
protectedinherited

List physically holding (owning) period objects.

Definition at line 457 of file TPileupReweighting.h.

◆ m_periods

std::map<Int_t, Period*> CP::TPileupReweighting::m_periods
protectedinherited

Definition at line 458 of file TPileupReweighting.h.

◆ m_prefix

std::string CP::PileupReweightingTool::m_prefix
private

Definition at line 154 of file PileupReweightingTool.h.

◆ m_printInfo

Bool_t CP::TPileupReweighting::m_printInfo
protectedinherited

Definition at line 334 of file TPileupReweighting.h.

◆ m_prwFiles

std::vector<std::string> CP::PileupReweightingTool::m_prwFiles
private

Definition at line 151 of file PileupReweightingTool.h.

◆ m_prwFilesPathPrefix

std::string CP::TPileupReweighting::m_prwFilesPathPrefix
protectedinherited

Definition at line 463 of file TPileupReweighting.h.

◆ m_random3

std::unique_ptr< TRandom3 > CP::TPileupReweighting::m_random3
protectedinherited

Definition at line 469 of file TPileupReweighting.h.

◆ m_runs

std::map<UInt_t, Run> CP::TPileupReweighting::m_runs
protectedinherited

Definition at line 459 of file TPileupReweighting.h.

◆ m_SetWarnings

Bool_t CP::TPileupReweighting::m_SetWarnings
protectedinherited

Definition at line 332 of file TPileupReweighting.h.

◆ m_systDown

CP::SystematicVariation CP::PileupReweightingTool::m_systDown
private

Definition at line 148 of file PileupReweightingTool.h.

◆ m_systUp

CP::SystematicVariation CP::PileupReweightingTool::m_systUp
private

Definition at line 148 of file PileupReweightingTool.h.

◆ m_tdt

ToolHandle<Trig::ITrigDecisionTool> CP::PileupReweightingTool::m_tdt
private

Definition at line 172 of file PileupReweightingTool.h.

◆ m_toolLumicalcFiles

std::vector<std::string> CP::PileupReweightingTool::m_toolLumicalcFiles
private

Definition at line 152 of file PileupReweightingTool.h.

◆ m_triggerObjs

std::map<TString, std::unique_ptr<CompositeTrigger> > CP::TPileupReweighting::m_triggerObjs
protectedinherited

Definition at line 408 of file TPileupReweighting.h.

◆ m_triggerPassBits

std::map<TString, bool> CP::TPileupReweighting::m_triggerPassBits
protectedinherited

Definition at line 315 of file TPileupReweighting.h.

◆ m_unrepDataTolerance

Double_t CP::TPileupReweighting::m_unrepDataTolerance
protectedinherited

Definition at line 343 of file TPileupReweighting.h.

◆ m_unrepDataWarningThreshold

Double_t CP::TPileupReweighting::m_unrepDataWarningThreshold {0.0}
protectedinherited

Definition at line 344 of file TPileupReweighting.h.

344{0.0};

◆ m_unrepresentedDataAction

Int_t CP::TPileupReweighting::m_unrepresentedDataAction
protectedinherited

Definition at line 336 of file TPileupReweighting.h.

◆ m_upTool

std::unique_ptr< CP::TPileupReweighting > CP::PileupReweightingTool::m_upTool
private

Definition at line 144 of file PileupReweightingTool.h.

◆ m_upVariation

double CP::PileupReweightingTool::m_upVariation
private

Definition at line 147 of file PileupReweightingTool.h.

◆ m_useMultiPeriods

Bool_t CP::TPileupReweighting::m_useMultiPeriods = true
protectedinherited

Definition at line 472 of file TPileupReweighting.h.

◆ m_usePeriodConfig

std::string CP::PileupReweightingTool::m_usePeriodConfig
private

Definition at line 157 of file PileupReweightingTool.h.

◆ m_useRunDependentPrescaleWeight

bool CP::PileupReweightingTool::m_useRunDependentPrescaleWeight
private

Definition at line 163 of file PileupReweightingTool.h.

◆ m_varHandleArraysDeclared

bool AthCommonDataStore< AthCommonMsg< AlgTool > >::m_varHandleArraysDeclared
privateinherited

Definition at line 399 of file AthCommonDataStore.h.

◆ m_varyRunNumber

bool CP::PileupReweightingTool::m_varyRunNumber
private

Definition at line 162 of file PileupReweightingTool.h.

◆ m_vhka

std::vector<SG::VarHandleKeyArray*> AthCommonDataStore< AthCommonMsg< AlgTool > >::m_vhka
privateinherited

Definition at line 398 of file AthCommonDataStore.h.

◆ m_weightTool

ToolHandle<IWeightTool> CP::PileupReweightingTool::m_weightTool
private

Definition at line 170 of file PileupReweightingTool.h.

◆ unrepDataByChannel

std::map<Int_t, Double_t> CP::TPileupReweighting::unrepDataByChannel
protectedinherited

Definition at line 461 of file TPileupReweighting.h.


The documentation for this class was generated from the following files: