diff --git a/inc/LauAbsFitModel.hh b/inc/LauAbsFitModel.hh index 5dfaec1..7f3531b 100644 --- a/inc/LauAbsFitModel.hh +++ b/inc/LauAbsFitModel.hh @@ -1,878 +1,886 @@ /* Copyright 2004 University of Warwick Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Laura++ package authors: John Back Paul Harrison Thomas Latham */ /*! \file LauAbsFitModel.hh \brief File containing declaration of LauAbsFitModel class. */ /*! \class LauAbsFitModel \brief Abstract interface to the fitting and toy MC model Abstract interface to the fitting and toy MC model Any class inheriting from this must implement the following functions: - cacheInputFitVars() - checkInitFitParams() - finaliseFitResults() - fixdSpeciesNames() - freeSpeciesNames() - genExpt() - getEventSum() - getTotEvtLikelihood() - initialise() - initialiseDPModels() - propagateParUpdates() - recalculateNormalisation() - scfDPSmear() - setAmpCoeffSet() - setNBkgndEvents() - setNSigEvents() - setupBkgndVectors() - setupGenNtupleBranches() - setupSPlotNtupleBranches() - splitSignal() - storePerEvtLlhds() - twodimPDFs() - updateCoeffs() - variableNames() - weightEvents() - writeOutTable() */ #ifndef LAU_ABS_FIT_MODEL #define LAU_ABS_FIT_MODEL #include "TMatrixDfwd.h" #include "TString.h" #include "TStopwatch.h" #include #include #include #include "LauFitObject.hh" #include "LauFormulaPar.hh" #include "LauSimFitTask.hh" // LauSPlot included to get LauSPlot::NameSet typedef #include "LauSPlot.hh" class LauAbsCoeffSet; class LauAbsPdf; class LauFitDataTree; class LauGenNtuple; class LauAbsRValue; class LauParameter; class LauAbsFitModel : public LauSimFitTask { public: //! Constructor LauAbsFitModel(); //! Destructor virtual ~LauAbsFitModel(); //! Is the Dalitz plot term in the likelihood Bool_t useDP() const { return usingDP_; } //! Switch on/off the Dalitz plot term in the Likelihood (allows fits to other quantities, e.g. B mass) /*! \param [in] usingDP the boolean flag */ void useDP(Bool_t usingDP) { usingDP_ = usingDP; } //! Return the flag to store the status of using an sFit or not Bool_t doSFit() const { return doSFit_; } //! Do an sFit (use sWeights to isolate signal decays rather than using background histograms) /*! \param [in] sWeightBranchName name of the branch of the tree containing the sWeights \param [in] scaleFactor scaling factor to get the uncertainties correct */ void doSFit( const TString& sWeightBranchName, Double_t scaleFactor = 1.0 ); //! Determine whether an extended maximum likelihood fit it being performed Bool_t doEMLFit() const {return emlFit_;} //! Choice to perform an extended maximum likelihood fit /*! \param [in] emlFit boolean specifying whether or not to perform the EML */ void doEMLFit(Bool_t emlFit) {emlFit_ = emlFit;} //! Determine whether Poisson smearing is enabled for the toy MC generation Bool_t doPoissonSmearing() const {return poissonSmear_;} //! Turn Poisson smearing (for the toy MC generation) on or off /*! \param [in] poissonSmear boolean specifying whether or not to do Poisson smearing */ void doPoissonSmearing(Bool_t poissonSmear) {poissonSmear_ = poissonSmear;} //! Determine whether embedding of events is enabled in the generation Bool_t enableEmbedding() const {return enableEmbedding_;} //! Turn on or off embedding of events in the generation /*! \param [in] enable boolean specifying whether to embed events */ void enableEmbedding(Bool_t enable) {enableEmbedding_ = enable;} //! Determine whether writing out of the latex table is enabled Bool_t writeLatexTable() const {return writeLatexTable_;} //! Turn on or off the writing out of the latex table /*! \param [in] writeTable boolean specifying whether or not the latex table should be written out */ void writeLatexTable(Bool_t writeTable) {writeLatexTable_ = writeTable;} //! save files containing graphs of the resonance's PDFs Bool_t saveFilePDF() const {return savePDF_;} //! Turn on or off the save of files containing graphs of the resonance's PDFs /*! \param [in] savePDF boolean specifying whether or not the save of files containing graphs of the resonance's PDFs */ void saveFilePDF(Bool_t savePDF) {savePDF_ = savePDF;} //! Set up the sPlot ntuple /*! \param [in] fileName the sPlot file name \param [in] treeName the sPlot tree name \param [in] storeDPEfficiency whether or not to store the efficiency information too \param [in] verbosity define the level of printout \see LauSPlot::runCalculations */ void writeSPlotData(const TString& fileName, const TString& treeName, Bool_t storeDPEfficiency, const LauOutputLevel verbosity = LauOutputLevel::Quiet); //! Determine whether the sPlot data is to be written out Bool_t writeSPlotData() const {return writeSPlotData_;} //! Determine whether the efficiency information should be stored in the sPlot ntuple Bool_t storeDPEff() const {return storeDPEff_;} //! Determine whether the initial values of the fit parameters, in particular the isobar coefficient parameters, are to be randomised Bool_t useRandomInitFitPars() const {return randomFit_;} //! Randomise the initial values of the fit parameters, in particular the isobar coefficient parameters void useRandomInitFitPars(Bool_t boolean) {randomFit_ = boolean;} //! Setup the background class names /*! \param [in] names a vector of all the background names */ virtual void setBkgndClassNames( const std::vector& names ); //! Returns the number of background classes inline UInt_t nBkgndClasses() const {return bkgndClassNames_.size();} //! Set the number of signal events /*! \param [in] nSigEvents contains the signal yield and option to fix it */ virtual void setNSigEvents(LauParameter* nSigEvents) = 0; //! Set the number of background events /*! The name of the parameter must be that of the corresponding background category (so that it can be correctly assigned) \param [in] nBkgndEvents contains the name, yield and option to fix the yield of the background */ virtual void setNBkgndEvents(LauAbsRValue* nBkgndEvents) = 0; //! Set the DP amplitude coefficients /*! The name of the coeffSet must match the name of one of the resonances in the DP model. The supplied order of coefficients will be rearranged to match the order in which the resonances are stored in the dynamics, see LauIsobarDynamics::addResonance. \param [in] coeffSet the set of coefficients */ virtual void setAmpCoeffSet(LauAbsCoeffSet* coeffSet) = 0; //! Specify that a toy MC sample should be created for a successful fit to an experiment /*! Generation uses the fitted parameters so that the user can compare the fit to the data \param [in] toyMCScale the scale factor to get the number of events to generate \param [in] mcFileName the file name where the toy sample will be stored \param [in] tableFileName name of the output tex file \param [in] poissonSmearing turn smearing on or off */ void compareFitData(UInt_t toyMCScale = 10, const TString& mcFileName = "fitToyMC.root", const TString& tableFileName = "fitToyMCTable.tex", Bool_t poissonSmearing = kTRUE); //! Start the toy generation / fitting /*! \param [in] applicationCode specifies what to do, perform a fit ("fit") or generate toy MC ("gen") \param [in] dataFileName the name of the input data file \param [in] dataTreeName the name of the tree containing the data \param [in] histFileName the file name for the output histograms \param [in] tableFileName the file name for the latex output file */ void run(const TString& applicationCode, const TString& dataFileName, const TString& dataTreeName, const TString& histFileName, const TString& tableFileName = ""); //! This function sets the parameter values from Minuit /*! This function has to be public since it is called from the global FCN. It should not be called otherwise! \param [in] par an array storing the various parameter values \param [in] npar the number of free parameters */ virtual void setParsFromMinuit(Double_t* par, Int_t npar); //! Calculates the total negative log-likelihood /*! This function has to be public since it is called from the global FCN. It should not be called otherwise! */ virtual Double_t getTotNegLogLikelihood(); //! Set model parameters from a file /*! \param [in] fileName the name of the file with parameters to set \param [in] treeName the name of the tree in the file corresponding to the parameters to set \param [in] fix whether to fix (set constant) the loaded parameters, or leave them floating */ void setParametersFromFile(const TString& fileName, const TString& treeName, const Bool_t fix); //! Set model parameters from a given std::map /*! Only parameters named in the map are imported, all others are set to their values specified in the model configuration. \param [in] parameters map from parameter name to imported value \param [in] fix whether to fix (set constant) the loaded parameters, or leave them floating */ void setParametersFromMap(const std::map& parameters, const Bool_t fix); //! Set named model parameters from a file /*! Identical to setParametersFromFile, but only import parameters named from parameters set. All others are set to their values specified in the model configuration. \param [in] fileName the name of the file with parameters to set \param [in] treeName the name of the tree in the file corresponding to the parameters to set \param [in] parameters the set of parameters to import from the file \param [in] fix whether to fix (set constant) the loaded parameters, or leave them floating */ void setNamedParameters(const TString& fileName, const TString& treeName, const std::set& parameters, const Bool_t fix); //! Set named model parameters from a given std::map, with fallback to those from a file /*! Parameters named in the map are imported with their specified values. All other parameters are set to the values corresponding to the value in the given file. \param [in] fileName the name of the file with parameters to set \param [in] treeName the name of the tree in the file corresponding to the parameters to set \param [in] parameters map from parameter name to imported value (override parameters form the file) \param [in] fix whether to fix (set constant) the loaded parameters, or leave them floating */ void setParametersFileFallback(const TString& fileName, const TString& treeName, const std::map& parameters, const Bool_t fix); protected: // Some typedefs //! List of Pdfs typedef std::vector LauPdfPList; //! List of parameter pointers typedef std::vector LauParameterPList; //! List of parameter pointers typedef std::vector LauAbsRValuePList; //! Set of parameter pointers typedef std::set LauParameterPSet; //! List of parameters typedef std::vector LauParameterList; //! A type to store background classes typedef std::map LauBkgndClassMap; //! Clear the vectors containing fit parameters void clearFitParVectors(); //! Clear the vectors containing extra ntuple variables void clearExtraVarVectors(); //! Weighting - allows e.g. MC events to be weighted by the DP model /*! \param [in] dataFileName the name of the data file \param [in] dataTreeName the name of the tree containing the data */ virtual void weightEvents( const TString& dataFileName, const TString& dataTreeName ) = 0; //! Generate toy MC /*! \param [in] dataFileName the name of the file where the generated events are stored \param [in] dataTreeName the name of the tree used to store the variables \param [in] histFileName the name of the histogram output file (currently not used) \param [in] tableFileNameBase the name the latex output file */ virtual void generate(const TString& dataFileName, const TString& dataTreeName, const TString& histFileName, const TString& tableFileNameBase); //! The method that actually generates the toy MC events for the given experiment /*! \return the success/failure flag of the generation procedure */ virtual Bool_t genExpt() = 0; //! Perform the total fit /*! \param [in] dataFileName the name of the data file \param [in] dataTreeName the name of the tree containing the data \param [in] histFileName the name of the histogram output file \param [in] tableFileNameBase the name the of latex output file */ void fit(const TString& dataFileName, const TString& dataTreeName, const TString& histFileName, const TString& tableFileNameBase); //! Routine to perform the actual fit for a given experiment void fitExpt(); //! Routine to perform the minimisation /*! \return the success/failure flag of the fit */ Bool_t runMinimisation(); //! Create a toy MC sample from the fitted parameters /*! \param [in] mcFileName the file name where the toy sample will be stored \param [in] tableFileName name of the output tex file */ void createFitToyMC(const TString& mcFileName, const TString& tableFileName); //! Read in the data for the current experiment /*! \return the number of events read in */ virtual UInt_t readExperimentData(); //! Open the input file and verify that all required variables are present /*! \param [in] dataFileName the name of the input file \param [in] dataTreeName the name of the input tree */ virtual Bool_t verifyFitData(const TString& dataFileName, const TString& dataTreeName); //! Cache the input data values to calculate the likelihood during the fit virtual void cacheInputFitVars() = 0; //! Cache the value of the sWeights to be used in the sFit virtual void cacheInputSWeights(); //! Initialise the fit par vectors /*! Each class that inherits from this one must implement this sensibly for all vectors specified in clearFitParVectors, i.e. specify parameter names, initial, min, max and fixed values */ virtual void initialise() = 0; //! Recalculate normalisation the signal DP model(s) virtual void recalculateNormalisation() = 0; //! Initialise the DP models virtual void initialiseDPModels() = 0; /*! For each amp in the fit this function takes its particular parameters and from them calculates the single complex number that is its coefficient. The vector of these coeffs can then be passed to the signal dynamics. */ virtual void updateCoeffs() = 0; //! This function (specific to each model) calculates anything that depends on the fit parameter values virtual void propagateParUpdates() = 0; //! Calculate the sum of the log-likelihood over the specified events /*! \param [in] iStart the event number of the first event to be considered \param [in] iEnd the event number of the final event to be considered */ Double_t getLogLikelihood( UInt_t iStart, UInt_t iEnd ); //! Calculate the penalty terms to the log likelihood from Gaussian constraints Double_t getLogLikelihoodPenalty(); //! Calculates the likelihood for a given event /*! \param [in] iEvt the event number */ virtual Double_t getTotEvtLikelihood(UInt_t iEvt) = 0; //! Returns the sum of the expected events over all hypotheses; used in the EML fit scenario virtual Double_t getEventSum() const = 0; //! Prints the values of all the fit variables for the specified event - useful for diagnostics /*! \param [in] iEvt the event number */ virtual void printEventInfo(UInt_t iEvt) const; //! Same as printEventInfo, but printing out the values of the variables in the fit virtual void printVarsInfo() const; //! Update initial fit parameters if required virtual void checkInitFitParams() = 0; //! Setup saving of fit results to ntuple/LaTeX table etc. /*! \param [in] histFileName the file name for the output histograms \param [in] tableFileName the file name for the latex output file */ virtual void setupResultsOutputs( const TString& histFileName, const TString& tableFileName ); //! Package the initial fit parameters for transmission to the coordinator /*! \param [out] array the array to be filled with the LauParameter objects */ virtual void prepareInitialParArray( TObjArray& array ); //! Perform all finalisation actions /*! - Receive the results of the fit from the coordinator - Perform any finalisation routines - Package the finalised fit parameters for transmission back to the coordinator \param [in] fitStat the status of the fit, e.g. status code, EDM, NLL \param [in] parsFromCoordinator the parameters at the fit minimum \param [in] covMat the fit covariance matrix \param [out] parsToCoordinator the array to be filled with the finalised LauParameter objects */ virtual void finaliseExperiment( const LauAbsFitter::FitStatus& fitStat, const TObjArray* parsFromCoordinator, const TMatrixD* covMat, TObjArray& parsToCoordinator ); //! Write the results of the fit into the ntuple /*! \param [in] tableFileName the structure containing the results of the fit */ virtual void finaliseFitResults(const TString& tableFileName) = 0; //! Save the pdf Plots for all the resonances of experiment number fitExp /*! \param [in] label prefix for the file name to be saved */ virtual void savePDFPlots(const TString& label) = 0; //! Save the pdf Plots for the sum of ressonances correspondint to "sin" of experiment number fitExp /*! \param [in] label prefix for the file name to be saved \param [in] spin spin of the wave to be saved */ virtual void savePDFPlotsWave(const TString& label, const Int_t& spin) = 0; //! Write the latex table /*! \param [in] outputFile the name of the output file */ virtual void writeOutTable(const TString& outputFile) = 0; //! Store the per-event likelihood values virtual void storePerEvtLlhds() = 0; //! Calculate the sPlot data virtual void calculateSPlotData(); //! Make sure all parameters hold their genValue as the current value void setGenValues(); //! Method to set up the storage for background-related quantities called by setBkgndClassNames virtual void setupBkgndVectors() = 0; //! Check if the given background class is in the list /*! \param [in] className the name of the class to check \return true or false */ Bool_t validBkgndClass( const TString& className ) const; //! The number assigned to a background class /*! \param [in] className the name of the class to check \return the background class ID number */ UInt_t bkgndClassID( const TString& className ) const; //! Get the name of a background class from the number /*! \param [in] classID the ID number of the background class \return the class name */ const TString& bkgndClassName( UInt_t classID ) const; //! Setup the generation ntuple branches virtual void setupGenNtupleBranches() = 0; //! Add a branch to the gen tree for storing an integer /*! \param [in] name the name of the branch */ virtual void addGenNtupleIntegerBranch(const TString& name); //! Add a branch to the gen tree for storing a double /*! \param [in] name the name of the branch */ virtual void addGenNtupleDoubleBranch(const TString& name); //! Set the value of an integer branch in the gen tree /*! \param [in] name the name of the branch \param [in] value the value to be stored */ virtual void setGenNtupleIntegerBranchValue(const TString& name, Int_t value); //! Set the value of a double branch in the gen tree /*! \param [in] name the name of the branch \param [in] value the value to be stored */ virtual void setGenNtupleDoubleBranchValue(const TString& name, Double_t value); //! Get the value of an integer branch in the gen tree /*! \param [in] name the name of the branch \return the value of the parameter */ virtual Int_t getGenNtupleIntegerBranchValue(const TString& name) const; //! Get the value of a double branch in the gen tree /*! \param [in] name the name of the branch \return the value of the parameter */ virtual Double_t getGenNtupleDoubleBranchValue(const TString& name) const; //! Fill the gen tuple branches virtual void fillGenNtupleBranches(); //! Setup the branches of the sPlot tuple virtual void setupSPlotNtupleBranches() = 0; //! Add a branch to the sPlot tree for storing an integer /*! \param [in] name the name of the branch */ virtual void addSPlotNtupleIntegerBranch(const TString& name); //! Add a branch to the sPlot tree for storing a double /*! \param [in] name the name of the branch */ virtual void addSPlotNtupleDoubleBranch(const TString& name); //! Set the value of an integer branch in the sPlot tree /*! \param [in] name the name of the branch \param [in] value the value to be stored */ virtual void setSPlotNtupleIntegerBranchValue(const TString& name, Int_t value); //! Set the value of a double branch in the sPlot tree /*! \param [in] name the name of the branch \param [in] value the value to be stored */ virtual void setSPlotNtupleDoubleBranchValue(const TString& name, Double_t value); //! Fill the sPlot tuple virtual void fillSPlotNtupleBranches(); //! Returns the names of all variables in the fit virtual LauSPlot::NameSet variableNames() const = 0; //! Returns the names and yields of species that are free in the fit virtual LauSPlot::NumbMap freeSpeciesNames() const = 0; //! Returns the names and yields of species that are fixed in the fit virtual LauSPlot::NumbMap fixdSpeciesNames() const = 0; //! Returns the species and variables for all 2D PDFs in the fit virtual LauSPlot::TwoDMap twodimPDFs() const = 0; //! Check if the signal is split into well-reconstructed and mis-reconstructed types virtual Bool_t splitSignal() const = 0; //! Check if the mis-reconstructed signal is to be smeared in the DP virtual Bool_t scfDPSmear() const = 0; //! Add the given parameter to the list of all fit parameters /*! \param [in] param the parameter \param [in] addFixed if true add the parameter even if it is not floating \return the number of parameters added */ UInt_t addFitParameters(LauParameter* param, const Bool_t addFixed = kFALSE); //! Add the given parameter(s) to the list of all fit parameters /*! \param [in] param the parameter (which may depend on other parameters) \param [in] addFixed if true add the parameter even if it is not floating \return the number of parameters added */ UInt_t addFitParameters(LauAbsRValue* param, const Bool_t addFixed = kFALSE); //! Add the given parameter(s) to the list of all fit parameters /*! \param [in] paramList a list of parameters \param [in] addFixed if true add the parameter even if it is not floating \return the number of parameters added */ UInt_t addFitParameters(LauParameterPList& paramList, const Bool_t addFixed = kFALSE); //! Add the given parameter(s) to the list of all fit parameters /*! \param [in] paramList a list of parameters \param [in] addFixed if true add the parameter even if it is not floating \return the number of parameters added */ UInt_t addFitParameters(LauAbsRValuePList& paramList, const Bool_t addFixed = kFALSE); + //! Add the given parameter(s) to the list of all fit parameters + /*! + \param [in] paramList a list of parameters + \param [in] addFixed if true add the parameter even if it is not floating + \return the number of parameters added + */ + UInt_t addFitParameters(std::vector>& paramList, const Bool_t addFixed = kFALSE); + //! Add parameters of the PDFs in the list to the list of all fit parameters /*! \param [in] pdfList a list of Pdfs \param [in] addFixed if true add the parameter even if it is not floating \return the number of parameters added */ UInt_t addFitParameters(LauPdfPList& pdfList, const Bool_t addFixed = kFALSE); //! Add the given parameter to the list of resonance parameters and the list of all fit parameters /*! \param [in] param a resonance parameter \return the number of parameters added */ UInt_t addResonanceParameters(LauParameter* param); //! Add the given parameter(s) to the list of resonance parameters and the list of all fit parameters /*! \param [in] paramList a list of resonance parameters \return the number of parameters added */ UInt_t addResonanceParameters(LauParameterPList& paramList); //! Add parameters to the list of Gaussian constrained parameters void addConParameters(); //! Print the fit parameters for all PDFs in the list /*! \param [in] pdfList a list of Pdfs \param [in] fout the output stream to write to */ void printFitParameters(const LauPdfPList& pdfList, std::ostream& fout) const; //! Update the fit parameters for all PDFs in the list /*! \param [in] pdfList a list of Pdfs */ void updateFitParameters(LauPdfPList& pdfList); //! Have all PDFs in the list cache the data /*! \param [in] pdfList the list of pdfs \param [in] theData the data from the fit */ void cacheInfo(LauPdfPList& pdfList, const LauFitDataTree& theData); //! Calculate the product of the per-event likelihoods of the PDFs in the list /*! \param [in] pdfList the list of pdfs \param [in] iEvt the event number */ Double_t prodPdfValue(LauPdfPList& pdfList, UInt_t iEvt); //! Do any of the PDFs have a dependence on the DP? /*! \return the flag to indicated if there is a DP dependence */ Bool_t pdfsDependOnDP() const {return pdfsDependOnDP_;} //! Do any of the PDFs have a dependence on the DP? /*! \param [in] dependOnDP the flag to indicated if there is a DP dependence */ void pdfsDependOnDP(Bool_t dependOnDP) { pdfsDependOnDP_ = dependOnDP; } //! Const access to the fit variables const LauParameterPList& fitPars() const {return fitVars_;} //! Const access the fit variables which affect the DP normalisation const LauParameterPSet& resPars() const {return resVars_;} //! Const access the extra variables const LauParameterList& extraPars() const {return extraVars_;} //! Non-const access the extra variables LauParameterList& extraPars() {return extraVars_;} //! Const access the Gaussian constrained variables const LauAbsRValuePList& conPars() const {return conVars_;} //! Const access the gen ntuple const LauGenNtuple* genNtuple() const {return genNtuple_;} //! Access the gen ntuple LauGenNtuple* genNtuple() {return genNtuple_;} //! Const access the sPlot ntuple const LauGenNtuple* sPlotNtuple() const {return sPlotNtuple_;} //! Access the sPlot ntuple LauGenNtuple* sPlotNtuple() {return sPlotNtuple_;} //! Const access the data store const LauFitDataTree* fitData() const {return inputFitData_;} //! Access the data store LauFitDataTree* fitData() {return inputFitData_;} //! Imported parameters file name TString fixParamFileName_; //! Imported parameters tree name TString fixParamTreeName_; //! Map from imported parameter name to value std::map fixParamMap_; //! Imported parameter names std::set fixParamNames_; //! Whether to fix the loaded parameters (kTRUE) or leave them floating (kFALSE) Bool_t fixParams_; //! The set of parameters that are imported (either from a file or by value) and not // set to be fixed in the fit. In addition to those from fixParamNames_, these // include those imported from a file. std::set allImportedFreeParams_; private: //! Copy constructor (not implemented) LauAbsFitModel(const LauAbsFitModel& rhs); //! Copy assignment operator (not implemented) LauAbsFitModel& operator=(const LauAbsFitModel& rhs); // Various control booleans //! Option to make toy from 1st successful experiment Bool_t compareFitData_; //! Option to output a .C file of PDF's Bool_t savePDF_; //! Option to output a Latex format table Bool_t writeLatexTable_; //! Option to write sPlot data Bool_t writeSPlotData_; //! Option to store DP efficiencies in the sPlot ntuple Bool_t storeDPEff_; //! Option to randomise the initial values of the fit parameters Bool_t randomFit_; //! Option to perform an extended ML fit Bool_t emlFit_; //! Option to perform Poisson smearing Bool_t poissonSmear_; //! Option to enable embedding Bool_t enableEmbedding_; //! Option to include the DP as part of the fit Bool_t usingDP_; //! Option to state if pdfs depend on DP position Bool_t pdfsDependOnDP_; // Info on number of experiments and number of events //! Internal vector of fit parameters LauParameterPList fitVars_; //! Internal set of the same fit parameters (used to check uniqueness) LauParameterPSet fitVarsSet_; //! Internal set of fit parameters upon which the DP normalisation depends LauParameterPSet resVars_; //! Extra variables that aren't in the fit but are stored in the ntuple LauParameterList extraVars_; //! Internal vectors of Gaussian parameters LauAbsRValuePList conVars_; // Input data and output ntuple //! The input data LauFitDataTree* inputFitData_; //! The generated ntuple LauGenNtuple* genNtuple_; //! The sPlot ntuple LauGenNtuple* sPlotNtuple_; // Background class names //! The background class names LauBkgndClassMap bkgndClassNames_; //! An empty string const TString nullString_; // sFit related variables //! Option to perfom the sFit Bool_t doSFit_; //! The name of the sWeight branch TString sWeightBranchName_; //! The vector of sWeights std::vector sWeights_; //! The sWeight scaling factor Double_t sWeightScaleFactor_; // Fit timers //! The fit timer TStopwatch timer_; //! The total fit timer TStopwatch cumulTimer_; //! The output table name TString outputTableName_; // Comparison toy MC related variables //! The output file name for Toy MC TString fitToyMCFileName_; //! The output table name for Toy MC TString fitToyMCTableName_; //! The scaling factor (toy vs data statistics) UInt_t fitToyMCScale_; //! Option to perform Poisson smearing Bool_t fitToyMCPoissonSmear_; // sPlot related variables //! The name of the sPlot file TString sPlotFileName_; //! The name of the sPlot tree TString sPlotTreeName_; //! Control the verbosity of the sPlot calculations LauOutputLevel sPlotVerbosity_; ClassDef(LauAbsFitModel,0) // Abstract interface to fit/toyMC model }; #endif diff --git a/inc/LauFlavTag.hh b/inc/LauFlavTag.hh index 53f2f76..2f40d53 100644 --- a/inc/LauFlavTag.hh +++ b/inc/LauFlavTag.hh @@ -1,496 +1,539 @@ /* Copyright 2017 University of Warwick Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Laura++ package authors: John Back Paul Harrison Thomas Latham */ /*! \file LauFlavTag.hh \brief File containing declaration of LauFlavTag class. */ /*! \class LauFlavTag \brief Class for defining the flavour tagging approach. Define the flavour tagging categories and all associated parameters to be passed to the relevant fit models. */ #ifndef LAU_FLAVTAG #define LAU_FLAVTAG #include #include #include "TString.h" #include "LauParameter.hh" class LauAbsPdf; class LauFitDataTree; class LauFlavTag final { public: //! Define sign convention for B and Bbar flavours enum Flavour { Bbar = -1, //< Bbar flavour Unknown = 0, //< Unknown flavour B = +1 //< B flavour }; //! Define different types of background to control the behaviour for each source // TODO Might want to move this somewhere more general later enum class BkgndType { Combinatorial, //< combinatorial background FlavourSpecific, //< flavour-specific decay (i.e. the flavour of the parent can be determined from the decay products), e.g. B0 -> K+ pi- pi0 SelfConjugate, //< decays where both B and Bbar can decay to a single self-conjugate final state, e.g. B0 -> pi+ pi- K_S0 NonSelfConjugate //< decays where both B and Bbar can decay to either of two final states that are conjugates of each other, e.g. B0 -> K+ pi- K_S0 and B0 -> K- pi+ K_S0 }; //! Constructor /*! \param [in] useAveDelta use average and delta variables for tagging calibration and efficiency \param [in] useEtaPrime use eta prime rather the eta as the mistag throughout \param [in] bkgndInfo map containing names and types of the background sources (if applicable) */ LauFlavTag(const Bool_t useAveDelta = kFALSE, const Bool_t useEtaPrime = kFALSE, const std::map bkgndInfo={}); //! Initialise // TODO is this needed? Commented for the moment (here and where called in LauTimeDepFitModel) //void initialise(); // TODO - need to decide which functions need to be public (interface) and which should be private (implementation details) // - improve/extend Doxygen comments //! Change the dilutions, delta dilutions and tagCatFrac for signal if needed /*! \param [in] name the name of the tagger \param [in] tagVarName the tagging variable name of the tagger in the ntuple \param [in] mistagVarName the associated mistag variable name of the same tagger in the ntuple \param [in] etapdf the mistag distribution for the tagger \param [in] tagEff tagging efficiency - (particle, antiparticle) or (average, delta) depending on useAveDelta_ flag \param [in] calib_p0 calibration parameter p0 - (particle, antiparticle) or (average, delta) depending on useAveDelta_ flag \param [in] calib_p1 calibration parameter p1 - (particle, antiparticle) or (average, delta) depending on useAveDelta_ flag */ void addTagger(const TString& name, const TString& tagVarName, const TString& mistagVarName, LauAbsPdf* etapdf, const std::pair tagEff, const std::pair calib_p0, const std::pair calib_p1); //! Change the dilutions, delta dilutions and tagCatFrac for signal if needed /*! \param [in] name the name of the tagger \param [in] tagVarName the tagging variable name of the tagger in the ntuple \param [in] mistagVarName the associated mistag variable name of the same tagger in the ntuple \param [in] etapdf the mistag distribution for the tagger \param [in] tagEff tagging efficiency histograms - (particle, antiparticle) or (average, delta) depending on useAveDelta_ flag \param [in] calib_p0 calibration parameter p0 - (particle, antiparticle) or (average, delta) depending on useAveDelta_ flag \param [in] calib_p1 calibration parameter p1 - (particle, antiparticle) or (average, delta) depending on useAveDelta_ flag */ void addTagger(const TString& name, const TString& tagVarName, const TString& mistagVarName, LauAbsPdf* etapdf, const std::pair tagEff, const std::pair calib_p0, const std::pair calib_p1); //! Read in the input fit data variables /*! \param [in] inputFitData the data source \param [in] decayTimeVarName the name of the decay time variable within the input data (used if the tagging efficiencies depend on decay time) */ void cacheInputFitVars(LauFitDataTree* inputFitData, const TString& decayTimeVarName=""); //! Generate values for the signal tag decisions and mis-tag probabilities /*! \param [in] trueTagFlv the true tag flavour \param [in] curEvtDecayTime the generated decay time value (used if the tagging efficiencies depend on decay time) */ void generateEventInfo(const Flavour trueTagFlv, const Double_t curEvtDecayTime); //! Generate values for the background tag decisions and mis-tag probabilities /*! \param [in] bkgndID the background category ID for which to generate \param [in] trueTagFlv the true tag flavour + \param [in] trueDecayFlv the true decay flavour (if known) \param [in] curEvtDecayTime the generated decay time value (used if the tagging efficiencies depend on decay time) */ - void generateBkgndEventInfo(const ULong_t bkgndID, const Flavour trueTagFlv, const Double_t curEvtDecayTime); + void generateBkgndEventInfo(const std::size_t bkgndID, const Flavour trueTagFlv, const Flavour trueDecayFlv, const Double_t curEvtDecayTime); //! Retrieve the cached info for a given event /*! \param [in] iEvt the event to retrieve */ - void updateEventInfo(const ULong_t iEvt); + void updateEventInfo(const std::size_t iEvt); //! Retrieve the name of the true tag variable const TString& getTrueTagVarName() const {return trueTagVarName_;}; //! Retrieve the name of the decay flavour variable const TString& getDecayFlvVarName() const {return decayFlvVarName_;}; //! Retrieve the names of the tag decision variables for each tagger const std::vector& getTagVarNames() const {return tagVarNames_;}; //! Retrieve the names of the mis-tag probability variables for each tagger const std::vector& getMistagVarNames() const {return mistagVarNames_;}; //! Retrieve the current value of the true tag variable Flavour getCurEvtTrueTagFlv() const {return curEvtTrueTagFlv_;}; //! Retrieve the current value of the decay flavour variable Flavour getCurEvtDecayFlv() const {return curEvtDecayFlv_;}; //! Retrieve the current values of the tag decision variables for each tagger const std::vector& getCurEvtTagFlv() const {return curEvtTagFlv_;}; //! Retrieve the current values of the mis-tag probability variables for each tagger const std::vector& getCurEvtMistag() const {return curEvtMistag_;}; //! Retrieve the number of taggers - ULong_t getNTaggers() const {return tagVarNames_.size();} + std::size_t getNTaggers() const {return tagVarNames_.size();} //! Get vector of calibration p0 for B0 parameters for each tagger std::vector getCalibP0B0(){return calib_p0_B0_;}; //! Get vector of calibration p0 for B0bar parameters for each tagger std::vector getCalibP0B0bar(){return calib_p0_B0bar_;}; //! Get vector of calibration p1 for B0 parameters for each tagger std::vector getCalibP1B0(){return calib_p1_B0_;}; //! Get vector of calibration p1 for B0bar parameters for each tagger std::vector getCalibP1B0bar(){return calib_p1_B0bar_;}; //! Get vector of calibration p0 average parameters for each tagging category std::vector getCalibP0Ave(){return calib_p0_ave_;}; //! Get vector of calibration p0 difference parameters for each tagging category std::vector getCalibP0Delta(){return calib_p0_delta_;}; //! Get vector of calibration p1 average parameters for each tagging category std::vector getCalibP1Ave(){return calib_p1_ave_;}; //! Get vector of calibration p1 difference parameters for each tagging category std::vector getCalibP1Delta(){return calib_p1_delta_;}; //! Get vector of tagging efficiency for B0 parameters for each tagging category std::vector getTagEffB0(){return tagEff_B0_;}; //! Get vector of tagging efficiency for B0bar parameters for each tagging category std::vector getTagEffB0bar(){return tagEff_B0bar_;}; //! Get vector of tagging efficiency average parameters for each tagging category std::vector getTagEffAve(){return tagEff_ave_;}; //! Get vector of tagging efficiency difference parameters for each tagging category std::vector getTagEffDelta(){return tagEff_delta_;}; //! Get 2D vector of background tagging efficiency for B0 parameters for each tagger (inner vec) and background source (outer vec) - std::vector> getTagEffBkgndB0(){return tagEffBkgnd_B0_;}; + auto getTagEffBkgndB0(){return tagEffBkgnd_B0_;}; //! Get 2D vector of background tagging efficiency for B0bar parameters for each tagger (inner vec) and background source (outer vec) - std::vector> getTagEffBkgndB0bar(){return tagEffBkgnd_B0bar_;}; + auto getTagEffBkgndB0bar(){return tagEffBkgnd_B0bar_;}; //! Get 2D vector of background tagging efficiency average parameters for each tagger (inner vec) and background source (outer vec) - std::vector> getTagEffBkgndAve(){return tagEffBkgnd_ave_;}; + auto getTagEffBkgndAve(){return tagEffBkgnd_ave_;}; //! Get 2D vector of background tagging efficiency difference parameters for each tagger (inner vec) and background source (outer vec) - std::vector> getTagEffBkgndDelta(){return tagEffBkgnd_delta_;}; + auto getTagEffBkgndDelta(){return tagEffBkgnd_delta_;}; - //! Set some things for backgrounds - //! Set background eta PDF for a given background and given tagger + //! Set background parameters for a given background and given tagger /*! - \param [in] bkgndName background category name + Set the eta (mis-tag probability) distribution and tagging efficiency constants for B and Bbar + + \param [in] bkgndName background category name \param [in] taggerName name of the tagger \param [in] etaPdf the eta PDF itself \param [in] tagEff the tagging efficiency parameters */ - void setBkgndParams(const TString& bkgndName, const TString& taggerName, LauAbsPdf* etaPdf, std::pair tagEff); + void setBkgndParams(const TString& bkgndName, const TString& taggerName, LauAbsPdf* etaPdf, std::pair tagEff); - //! Set background eta PDF for a given background and given tagger + //! Set background parameters for a given background and given tagger /*! - \param [in] bkgndName background category name + Set the eta (mis-tag probability) distribution and tagging efficiencies (as a function of decay time) for B and Bbar + + \param [in] bkgndName background category name \param [in] taggerName name of the tagger \param [in] etaPdf the eta PDF itself \param [in] tagEff the tagging efficiency histograms */ - void setBkgndParams(const TString& bkgndName, const TString& taggerName, LauAbsPdf* etaPdf, std::pair tagEff); + void setBkgndParams(const TString& bkgndName, const TString& taggerName, LauAbsPdf* etaPdf, std::pair tagEff); + + //! Set background parameters for a given background and given tagger + /*! + Set the eta (mis-tag probability) distribution and tagging efficiency constants for B and Bbar + This version provides different parameters for each decay flavour (used for Combinatorial background in QFS modes) + + \param [in] bkgndName background category name + \param [in] taggerName name of the tagger + \param [in] etaPdfB the eta PDF for decay flavour = B + \param [in] tagEffB the tagging efficiency parameters for decay flavour = B + \param [in] etaPdfBbar the eta PDF for decay flavour = Bbar + \param [in] tagEffBbar the tagging efficiency parameters for decay flavour = Bbar + */ + void setBkgndParams(const TString& bkgndName, const TString& taggerName, LauAbsPdf* etaPdfB, std::pair tagEffB, LauAbsPdf* etaPdfBbar, std::pair tagEffBbar); + + //! Set background parameters for a given background and given tagger + /*! + Set the eta (mis-tag probability) distribution and tagging efficiencies (as a function of decay time) for B and Bbar + This version provides different parameters for each decay flavour (used for Combinatorial background in QFS modes) + + \param [in] bkgndName background category name + \param [in] taggerName name of the tagger + \param [in] etaPdfB the eta PDF for decay flavour = B + \param [in] tagEffB the tagging efficiency histograms for decay flavour = B + \param [in] etaPdfBbar the eta PDF for decay flavour = Bbar + \param [in] tagEffBbar the tagging efficiency histograms for decay flavour = Bbar + */ + void setBkgndParams(const TString& bkgndName, const TString& taggerName, LauAbsPdf* etaPdfB, std::pair tagEffB, LauAbsPdf* etaPdfBbar, std::pair tagEffBbar); //! Returns little omega (calibrated mistag) /*! - \param [in] position index of the tagger in the taggers vector + \param [in] taggerID index of the tagger in the taggers vectors \param [in] flag choose to calculate omega or omegabar (corrsonding to B or Bbar) */ - Double_t getLittleOmega(const ULong_t position, const Flavour flag) const; + Double_t getLittleOmega(const std::size_t taggerID, const Flavour flag) const; //! Capital Omega for signal decays /*! - \param [in] position index of the tagger in the taggers vector + \param [in] taggerID index of the tagger in the taggers vectors \param [in] flag choose to calculate Omega or Omegabar (corrsonding to B or Bbar) */ - Double_t getCapitalOmega(const ULong_t position, const Flavour flag) const; + Double_t getCapitalOmega(const std::size_t taggerID, const Flavour flag) const; //! Returns little omega (calibrated mistag) for backgrounds /*! - \param [in] position index of the tagger in the taggers vector + \param [in] bkgndID index of the background vector + \param [in] taggerID index of the tagger in the taggers vectors \param [in] flag choose to calculate omega or omegabar (corrsonding to B or Bbar) - \param [in] classID index of the background vector + \param [in] decayFlv the decay flavour of the B */ - Double_t getLittleOmegaBkgnd(const ULong_t position, const Flavour flag, const UInt_t classID) const; + Double_t getLittleOmegaBkgnd(const std::size_t bkgndID, const std::size_t taggerID, const Flavour flag, const Flavour decayFlv) const; //! Capital Omega for backgrounds /*! - \param [in] position index of the tagger in the taggers vector + \param [in] bkgndID index of the background vector + \param [in] taggerID index of the tagger in the taggers vectors \param [in] flag choose to calculate Omega or Omegabar (corrsonding to B or Bbar) - \param [in] classID index of the background vector + \param [in] decayFlv the decay flavour of the B */ - Double_t getCapitalOmegaBkgnd(const ULong_t position, const Flavour flag, const UInt_t classID) const; + Double_t getCapitalOmegaBkgnd(const std::size_t bkgndID, const std::size_t taggerID, const Flavour flag, const Flavour decayFlv) const; //! Get the generated value of signal eta for the given tagger /*! - \param [in] position index of the tagger in the taggers vector + \param [in] taggerID index of the tagger in the taggers vectors */ - Double_t getEtaGen(const ULong_t position); + Double_t getEtaGen(const std::size_t taggerID); //! Get the generated value of background eta for the given tagger and background category /*! - \param [in] position index of the tagger in the taggers vector - \param [in] bkgndID index of the background vector + \param [in] taggerID index of the tagger in the taggers vectors + \param [in] bkgndID index of the background in the backgrounds vectors */ - Double_t getEtaGenBkgnd(const ULong_t position, const ULong_t bkgndID); + Double_t getEtaGenBkgnd(const std::size_t taggerID, const std::size_t bkgndID, const Flavour decayFlv); //! Return the Boolean controlling if we use the alternative tagging calibration and efficiency parameters Bool_t getUseAveDelta() const {return useAveDelta_;}; //! Specify the name of the true tag variable /*! \param [in] trueTagVarName the name of the true tag variable */ void setTrueTagVarName(TString trueTagVarName); //! Specify the name of the decay flavour variable /*! \param [in] decayFlvVarName the name of the decay flavour variable */ void setDecayFlvVarName(TString decayFlvVarName); //! Gaussian constraints for P0 parameters for a given tagger /*! - \param [in] name name of the tagger + \param [in] taggerName name of the tagger \param [in] constraint1 the (mean, sigma) for the particle or average parameter \param [in] constraint2 the (mean, sigma) for the antiparticle or delta parameter */ - void addP0GaussianConstraints(const TString name, const std::pair constraint1, const std::pair constraint2); + void addP0GaussianConstraints(const TString& taggerName, const std::pair constraint1, const std::pair constraint2); //! Gaussian constraints for P1 parameters for a given tagger /*! - \param [in] name name of the tagger + \param [in] taggerName name of the tagger \param [in] constraint1 the (mean, sigma) for the particle or average parameter \param [in] constraint2 the (mean, sigma) for the antiparticle or delta parameter */ - void addP1GaussianConstraints(const TString name, const std::pair constraint1, const std::pair constraint2); + void addP1GaussianConstraints(const TString& taggerName, const std::pair constraint1, const std::pair constraint2); //! Gaussian constraints for tagging efficiency parameters for a given tagger /*! - \param [in] name name of the tagger + \param [in] taggerName name of the tagger \param [in] constraint1 the (mean, sigma) for the particle or average parameter \param [in] constraint2 the (mean, sigma) for the antiparticle or delta parameter */ - void addTagEffGaussianConstraints(const TString name, const std::pair constraint1, const std::pair constraint2); + void addTagEffGaussianConstraints(const TString& taggerName, const std::pair constraint1, const std::pair constraint2); //! Retrieve the names of the background categories - const std::vector getBkgndNames(){return bkgndNames_;}; + std::vector getBkgndNames(); + //! Retrieve the types of the background categories - const std::vector getBkgndTypes(){return bkgndTypes_;}; + std::vector getBkgndTypes(){return bkgndTypes_;} //! Float the P0 calibration parameters for B tags /*! - \param [in] name name of the tagger, defaults to empty to float for all taggers + \param [in] taggerName name of the tagger, defaults to empty to float for all taggers */ - void floatCalibParP0B0(const TString name = ""); + void floatCalibParP0B0(const TString& taggerName = ""); //! Float the P1 calibration parameters for B tags /*! - \param [in] name name of the tagger, defaults to empty to float for all taggers + \param [in] taggerName name of the tagger, defaults to empty to float for all taggers */ - void floatCalibParP1B0(const TString name = ""); + void floatCalibParP1B0(const TString& taggerName = ""); //! Float the P0 calibration parameters for Bbar tags /*! - \param [in] name name of the tagger, defaults to empty to float for all taggers + \param [in] taggerName name of the tagger, defaults to empty to float for all taggers */ - void floatCalibParP0B0bar(const TString name = ""); + void floatCalibParP0B0bar(const TString& taggerName = ""); //! Float the P1 calibration parameters for Bbar tags /*! - \param [in] name name of the tagger, defaults to empty to float for all taggers + \param [in] taggerName name of the tagger, defaults to empty to float for all taggers */ - void floatCalibParP1B0bar(const TString name = ""); + void floatCalibParP1B0bar(const TString& taggerName = ""); //! Float the P0 average calibration parameters /*! - \param [in] name name of the tagger, defaults to empty to float for all taggers + \param [in] taggerName name of the tagger, defaults to empty to float for all taggers */ - void floatCalibParP0Ave(const TString name = ""); + void floatCalibParP0Ave(const TString& taggerName = ""); //! Float the P0 delta calibration parameters /*! - \param [in] name name of the tagger, defaults to empty to float for all taggers + \param [in] taggerName name of the tagger, defaults to empty to float for all taggers */ - void floatCalibParP0Delta(const TString name = ""); + void floatCalibParP0Delta(const TString& taggerName = ""); //! Float the P1 average calibration parameters /*! - \param [in] name name of the tagger, defaults to empty to float for all taggers + \param [in] taggerName name of the tagger, defaults to empty to float for all taggers */ - void floatCalibParP1Ave(const TString name = ""); + void floatCalibParP1Ave(const TString& taggerName = ""); //! Float the P1 delta calibration parameters /*! - \param [in] name name of the tagger, defaults to empty to float for all taggers + \param [in] taggerName name of the tagger, defaults to empty to float for all taggers */ - void floatCalibParP1Delta(const TString name = ""); + void floatCalibParP1Delta(const TString& taggerName = ""); //! Float all calibration parameters void floatAllCalibPars(); - protected: + private: //! Internal function to extend vectors void extendVectors(const TString& tagVarName, const TString& mistagVarName); //! Internal function to setup Calib parameters - void setupCalibParams(const TString& name, const ULong_t position, const std::pair calib_p0, const std::pair calib_p1); + void setupCalibParams(const TString& taggerName, const std::pair calib_p0, const std::pair calib_p1); + + //! Internal function to find parameters in per-tagger vectors + LauParameter* findParameter( const TString& taggerName, std::vector& parameters ); - private: //! Flag to use alternative calibration parameters const Bool_t useAveDelta_; //! Flag to use eta prime not eta for the mistag const Bool_t useEtaPrime_; - //! Map to link taggers to their vector position - std::map taggerPosition_; + //! Map to link tagger names to their index in all the vectors + std::map taggerIndex_; + + //! Map to link background names to their index in all the vectors + std::map bkgndIndex_; //! Flavour tagging variable name std::vector tagVarNames_; //! Per event mistag variable name std::vector mistagVarNames_; //! True tag variable name for normalisation decays TString trueTagVarName_; //! Decay flavour tag variable name for normalisation decays TString decayFlvVarName_; //! Vector of background names std::vector bkgndNames_; //! Vector of background types std::vector bkgndTypes_; + //! Vector of flags indicating if the background parameters depend on the decay flavour + std::vector bkgndDecayFlvDep_; + //! Vector of flavour tags for each event std::vector> evtTagFlv_; //! Flavour tag for current event std::vector curEvtTagFlv_; //! Vector of mistags for each event std::vector> evtMistag_; //! Per event mistag for current event std::vector curEvtMistag_; //! Vector of true tags for each event std::vector evtTrueTagFlv_; //! Vector of decay tags for each event std::vector evtDecayFlv_; //! True tag from normalisation mode for current event - Flavour curEvtTrueTagFlv_{Unknown}; + Flavour curEvtTrueTagFlv_{Flavour::Unknown}; //! True tag from normalisation mode for current event - Flavour curEvtDecayFlv_{Unknown}; + Flavour curEvtDecayFlv_{Flavour::Unknown}; //! Average background mistag value (eta hat) - std::vector> avgMistagBkgnd_; + std::vector>> avgMistagBkgnd_; //! Per-event average mistag value (eta hat) std::vector perEvtAvgMistag_; //! Decay time values for each event std::vector evtDecayTime_; //! Decay time value of the current event Double_t curEvtDecayTime_; //! Calibration parameters p0 for B0 std::vector calib_p0_B0_; //! Calibration parameters p0 for B0bar std::vector calib_p0_B0bar_; //! Calibration parameters p1 for B0 std::vector calib_p1_B0_; //! Calibration parameters p1 for B0bar std::vector calib_p1_B0bar_; //! Alternative calibration parameters p0 average std::vector calib_p0_ave_; //! Alternative calibration parameters p0 difference std::vector calib_p0_delta_; //! Alternative calibration parameters p1 average std::vector calib_p1_ave_; //! Alternative calibration parameters p1 difference std::vector calib_p1_delta_; //! Tagging efficiency parameters for B0 std::vector tagEff_B0_; //! Tagging efficiency parameters for B0bar std::vector tagEff_B0bar_; //! Tagging efficiency parameters average of B0 and B0bar std::vector tagEff_ave_; //! Tagging efficiency parameters difference between B0 and B0bar std::vector tagEff_delta_; //! Tagging efficiency histograms for B0 std::vector tagEff_hist_B0_; //! Tagging efficiency histograms for B0bar std::vector tagEff_hist_B0bar_; //! Tagging efficiency histograms average of B0 and B0bar std::vector tagEff_hist_ave_; //! Tagging efficiency histograms difference between B0 and B0bar std::vector tagEff_hist_delta_; //! Background tagging efficiency parameters for B0 - std::vector> tagEffBkgnd_B0_; + std::vector>> tagEffBkgnd_B0_; //! Background tagging efficiency parameters for B0bar - std::vector> tagEffBkgnd_B0bar_; + std::vector>> tagEffBkgnd_B0bar_; //! Background tagging efficiency parameters average of B0 and B0bar - std::vector> tagEffBkgnd_ave_; + std::vector>> tagEffBkgnd_ave_; //! Background tagging efficiency parameters difference between B0 and B0bar - std::vector> tagEffBkgnd_delta_; + std::vector>> tagEffBkgnd_delta_; //! Background tagging efficiency histograms for B0 - std::vector> tagEffBkgnd_hist_B0_; + std::vector>> tagEffBkgnd_hist_B0_; //! Background tagging efficiency histograms for B0bar - std::vector> tagEffBkgnd_hist_B0bar_; + std::vector>> tagEffBkgnd_hist_B0bar_; //! Background tagging efficiency histograms average of B0 and B0bar - std::vector> tagEffBkgnd_hist_ave_; + std::vector>> tagEffBkgnd_hist_ave_; //! Background tagging efficiency histograms difference between B0 and B0bar - std::vector> tagEffBkgnd_hist_delta_; + std::vector>> tagEffBkgnd_hist_delta_; //! Eta PDFs std::vector etaPdfs_; //! Eta PDFs for backgrounds per tagger (inner vec) and per background source (outer vec) - std::vector> etaBkgndPdfs_; + std::vector>> etaBkgndPdfs_; ClassDef(LauFlavTag,0) // Flavour tagging set up }; //! output stream operator /*! \param [in,out] stream the output stream to which the background type is to be printed \param [in] bkgndType the type to be written out return the output stream */ std::ostream& operator<<( std::ostream& stream, const LauFlavTag::BkgndType bkgndType ); #endif diff --git a/inc/LauTimeDepFitModel.hh b/inc/LauTimeDepFitModel.hh index 8fbd076..9f42bde 100644 --- a/inc/LauTimeDepFitModel.hh +++ b/inc/LauTimeDepFitModel.hh @@ -1,725 +1,723 @@ /* Copyright 2006 University of Warwick Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Laura++ package authors: John Back Paul Harrison Thomas Latham */ /*! \file LauTimeDepFitModel.hh \brief File containing declaration of LauTimeDepFitModel class. */ /*! \class LauTimeDepFitModel \brief Class for defining a time-dependent fit model. LauTimeDepFitModel is a class that allows the user to define a three-body Dalitz plot according to the isobar model, i.e. defining a set of resonances that have complex amplitudes that can interfere with each other. It extends the LauSimpleFitModel and LauCPFitModel models in that it allows the fitting of time-dependent particle/antiparticle decays to flavour-conjugate Dalitz plots, including their interference through mixing. */ #ifndef LAU_TIMEDEP_FIT_MODEL #define LAU_TIMEDEP_FIT_MODEL #include #include #include #include #include "TString.h" #include "TStopwatch.h" #include "TSystem.h" #include "LauAbsFitModel.hh" #include "LauComplex.hh" #include "LauConstants.hh" #include "LauEmbeddedData.hh" #include "LauFlavTag.hh" #include "LauParameter.hh" -//#include "LauCategoryFlavTag.hh" - class LauAbsBkgndDPModel; class LauAbsCoeffSet; class LauAbsPdf; class LauDecayTimePdf; class LauIsobarDynamics; class LauKinematics; class LauScfMap; class LauTimeDepFitModel : public LauAbsFitModel { public: //! Possible CP eigenvalues (the intrinsic CP of the final state particles) enum CPEigenvalue { CPOdd = -1, /*!< CP odd final state */ QFS = 0, /*!< Quasi Flavour Specific final state */ CPEven = 1 /*!< CP even final state */ }; //! Constructor /*! \param [in] modelB0bar DP model for the antiparticle \param [in] modelB0 DP model for the particle \param [in] flavTag flavour tagging information */ LauTimeDepFitModel(LauIsobarDynamics* modelB0bar, LauIsobarDynamics* modelB0, LauFlavTag* flavTag); //! Destructor virtual ~LauTimeDepFitModel(); //! Set the signal event yield /*! \param [in] nSigEvents contains the signal yield and option to fix it */ virtual void setNSigEvents(LauParameter* nSigEvents); //! Set the signal event yield and asymmetry /*! \param [in] nSigEvents contains the signal yield and option to fix it \param [in] sigAsym contains the signal asymmetry and option to fix it */ virtual void setNSigEvents(LauParameter* nSigEvents, LauParameter* sigAsym); //! Set the number of background events /*! The name of the parameter must be that of the corresponding background category (so that it can be correctly assigned) \param [in] nBkgndEvents contains the name, yield and option to fix the yield of the background */ virtual void setNBkgndEvents(LauAbsRValue* nBkgndEvents); //! Set the background event yield and asymmetry /*! The name of the parameters must be that of the corresponding background category (so that they can be correctly assigned) \param [in] nBkgndEvents contains the background yield and option to fix it \param [in] bkgndAsym contains the background asymmetry and option to fix it */ virtual void setNBkgndEvents(LauAbsRValue* nBkgndEvents, LauAbsRValue* bkgndAsym); //! Set the background DP models (null pointer for BbarModel implies same model for both) /*! \param [in] bkgndClass the name of the background class \param [in] BModel the DP model of the background for B (particle) decays \param [in] BbarModel the DP model of the background for Bbar (anti-particle) decays */ void setBkgndDPModels(const TString& bkgndClass, LauAbsBkgndDPModel* BModel, LauAbsBkgndDPModel* BbarModel); //! Switch on/off storage of amplitude info in generated ntuple void storeGenAmpInfo(Bool_t storeInfo) { storeGenAmpInfo_ = storeInfo; } //! Set CP eigenvalue /*! The CP eigenvalue can be supplied on an event-by-event basis, e.g. if the data contains daughters that are D0 mesons that can decay to either K+ K- (CP even) or KS pi0 (CP odd). This method allows you to set the default value that should be used if the data does not contain this information as well as the name of the variable in the data that will specify this information. If completely unspecified all events will be assumed to be CP even. \param defaultCPEV the default for the eigenvalue \param cpevVarName the variable name in the data tree that specifies the CP eigenvalue */ inline void setCPEigenvalue( const CPEigenvalue defaultCPEV, const TString& cpevVarName = "" ) { cpEigenValue_ = defaultCPEV; cpevVarName_ = cpevVarName; } //! Set the DP amplitude coefficients /*! \param [in] coeffSet the set of coefficients */ void setAmpCoeffSet(LauAbsCoeffSet* coeffSet); //! Set the signal decay time PDF /*! \param [in] pdf the signal decay time PDF */ void setSignalDtPdf(LauDecayTimePdf* pdf); //! Set the decay time PDF for a given background class /*! \param [in] bkgndClass the name of the background class \param [in] pdf the background decay time PDF */ void setBkgndDtPdf(const TString& bkgndClass, LauDecayTimePdf* pdf); //! Set the signal PDF for a given variable /*! \param [in] pdf the PDF to be added to the signal model */ void setSignalPdfs(LauAbsPdf* pdf); //! Set the background PDF for a given variable and background class /*! \param [in] bkgndClass the name of the background class \param [in] pdf the PDF to be added to the background model */ void setBkgndPdf(const TString& bkgndClass, LauAbsPdf* pdf); //! Embed full simulation events for the signal, rather than generating toy from the PDFs /*! \param [in] fileName the name of the file containing the events \param [in] treeName the name of the tree \param [in] reuseEventsWithinEnsemble sample with replacement but only replace events once each experiment has been generated \param [in] reuseEventsWithinExperiment sample with immediate replacement \param [in] useReweighting perform an accept/reject routine using the configured signal amplitude model based on the MC-truth DP coordinate */ void embedSignal(const TString& fileName, const TString& treeName, const Bool_t reuseEventsWithinEnsemble, const Bool_t reuseEventsWithinExperiment = kFALSE, const Bool_t useReweighting = kFALSE); //! Embed full simulation events for the signal, rather than generating toy from the PDFs /*! \param [in] bkgndClass the name of the background class \param [in] fileName the name of the file containing the events \param [in] treeName the name of the tree \param [in] reuseEventsWithinEnsemble sample with replacement but only replace events once each experiment has been generated \param [in] reuseEventsWithinExperiment sample with immediate replacement \param [in] useReweighting perform an accept/reject routine using the configured signal amplitude model based on the MC-truth DP coordinate */ void embedBkgnd(const TString& bkgndClass, const TString& fileName, const TString& treeName, const Bool_t reuseEventsWithinEnsemble, const Bool_t reuseEventsWithinExperiment = kFALSE, const Bool_t useReweighting = kFALSE); //! Set the value of the mixing phase /*! \param [in] phiMix the value of the mixing phase \param [in] fixPhiMix whether the value should be fixed or floated \param [in] useSinCos whether to use the sine and cosine as separate parameters or to just use the mixing phase itself */ void setPhiMix(const Double_t phiMix, const Bool_t fixPhiMix, const Bool_t useSinCos = kFALSE); //! Initialise the fit virtual void initialise(); //! Initialise the signal DP model virtual void initialiseDPModels(); //! Recalculate Normalization the signal DP models virtual void recalculateNormalisation(); //! Update the coefficients virtual void updateCoeffs(); // Toy MC generation and fitting overloaded functions virtual Bool_t genExpt(); //! Set the maximum value of A squared to be used in the accept/reject /*! \param [in] value the new value */ inline void setASqMaxValue(const Double_t value) {aSqMaxSet_ = value;} //! Weight events based on the DP model /*! \param [in] dataFileName the name of the data file \param [in] dataTreeName the name of the data tree */ virtual void weightEvents( const TString& dataFileName, const TString& dataTreeName ); //! Calculate things that depend on the fit parameters after they have been updated by Minuit virtual void propagateParUpdates(); //! Read in the input fit data variables, e.g. m13Sq and m23Sq virtual void cacheInputFitVars(); //! Check the initial fit parameters virtual void checkInitFitParams(); //! Get the fit results and store them /*! \param [in] tablePrefixName prefix for the name of the output file */ virtual void finaliseFitResults(const TString& tablePrefixName); //! Save the pdf Plots for all the resonances of experiment number fitExp /*! TODO - not working in this model!! \param [in] label prefix for the file name to be saved */ virtual void savePDFPlots(const TString& label); //! Save the pdf Plots for the sum of ressonances correspondint to "sin" of experiment number fitExp /*! TODO - not working in this model!! \param [in] label prefix for the file name to be saved \param [in] spin spin of the wave to be saved */ virtual void savePDFPlotsWave(const TString& label, const Int_t& spin); //! Print the fit fractions, total DP rate and mean efficiency /*! \param [out] output the stream to which to print */ virtual void printFitFractions(std::ostream& output); //! Print the asymmetries /*! \param [out] output the stream to which to print */ virtual void printAsymmetries(std::ostream& output); //! Write the fit results in latex table format /*! \param [in] outputFile the name of the output file */ virtual void writeOutTable(const TString& outputFile); //! Store the per event likelihood values virtual void storePerEvtLlhds(); // Methods to do with calculating the likelihood functions // and manipulating the fitting parameters. //! Get the total likelihood for each event /*! \param [in] iEvt the event number */ virtual Double_t getTotEvtLikelihood(const UInt_t iEvt); //! Calculate the signal and background likelihoods for the DP for a given event /*! \param [in] iEvt the event number */ virtual void getEvtDPDtLikelihood(const UInt_t iEvt); //! Determine the signal and background likelihood for the extra variables for a given event /*! \param [in] iEvt the event number */ virtual void getEvtExtraLikelihoods(const UInt_t iEvt); //! Get the total number of events /*! \return the total number of events */ virtual Double_t getEventSum() const; //! Set the fit parameters for the DP model void setSignalDPParameters(); //! Set the fit parameters for the decay time PDFs void setDecayTimeParameters(); //! Set the fit parameters for the extra PDFs void setExtraPdfParameters(); //! Set the initial yields void setFitNEvents(); //! Set the calibration parameters void setCalibParams(); //! Set the tagging efficiency parameters void setTagEffParams(); //! Set the asymmetry parameters void setAsymParams(); //! Set the tagging asymmetry parameters void setFlavTagAsymParams(); //! Set-up other parameters that are derived from the fit results, e.g. fit fractions void setExtraNtupleVars(); //! Set production and detections asymmetries /*! \param [in] AProd is the production asymmetry definied as (N_BqBar-N_Bq)/(N_BqBar+N_Bq) \param [in] AProdFix whether the production asymmetry should be fixed in the fit */ void setAsymmetries(const Double_t AProd, const Bool_t AProdFix); //! Set production and detections asymmetries /*! \param [in] bkgndClass the name of the background class \param [in] AProd is the production asymmetry definied as (N_BqBar-N_Bq)/(N_BqBar+N_Bq) \param [in] AProdFix whether the production asymmetry should be fixed in the fit */ void setBkgndAsymmetries(const TString& bkgndClass, const Double_t AProd, const Bool_t AProdFix); //! Randomise the initial fit parameters void randomiseInitFitPars(); //! Method to set up the storage for background-related quantities called by setBkgndClassNames virtual void setupBkgndVectors(); //! Calculate the CP asymmetries /*! \param [in] initValues is this before or after the fit */ void calcAsymmetries(const Bool_t initValues = kFALSE); //! Finalise value of mixing phase void checkMixingPhase(); protected: //! container to hold information on the number of events (and their weight) to generate for each category typedef std::map> LauGenInfo; //! container of background DP models typedef std::vector LauBkgndDPModelList; //! container of background PDFs typedef std::vector LauBkgndPdfsList; //! container of background yields or asymmetries typedef std::vector LauBkgndYieldList; //! container of boolean toggles for each background category typedef std::vector LauBkgndReuseEventsList; //! Determine the number of events to generate for each event category LauGenInfo eventsToGenerate(); //! Generate signal event /*! \return whether the generation was successful (kTRUE) or not (kFALSE) */ Bool_t generateSignalEvent(); //! Generate background event /*! \param [in] bgID ID number of the background class \return whether the generation was successful (kTRUE) or not (kFALSE) */ Bool_t generateBkgndEvent(UInt_t bgID); //! Setup the required ntuple branches void setupGenNtupleBranches(); //! Store all of the DP and decay time information void setDPDtBranchValues(); //! Generate from the extra PDFs /*! \param [in] extraPdfs the list of extra PDFs \param [in] embeddedData the embedded data sample */ void generateExtraPdfValues(LauPdfPList& extraPdfs, LauEmbeddedData* embeddedData); //! Add sPlot branches for the extra PDFs /*! \param [in] extraPdfs the list of extra PDFs \param [in] prefix the list of prefixes for the branch names */ void addSPlotNtupleBranches(const LauPdfPList& extraPdfs, const TString& prefix); //! Set the branches for the sPlot ntuple with extra PDFs /*! \param [in] extraPdfs the list of extra PDFs \param [in] prefix the prefix for the branch names \param [in] iEvt the event number */ Double_t setSPlotNtupleBranchValues(LauPdfPList& extraPdfs, const TString& prefix, const UInt_t iEvt); //! Update the signal events after Minuit sets background parameters void updateSigEvents(); //! Add branches to store experiment number and the event number within the experiment virtual void setupSPlotNtupleBranches(); //! Returns the names of all variables in the fit virtual LauSPlot::NameSet variableNames() const; //! Returns the names and yields of species that are free in the fit virtual LauSPlot::NumbMap freeSpeciesNames() const; //! Returns the names and yields of species that are fixed in the fit virtual LauSPlot::NumbMap fixdSpeciesNames() const; //! Returns the species and variables for all 2D PDFs in the fit virtual LauSPlot::TwoDMap twodimPDFs() const; //! Check if the signal is split into well-reconstructed and mis-reconstructed types virtual Bool_t splitSignal() const { return kFALSE; } //! Check if the mis-reconstructed signal is to be smeared in the DP virtual Bool_t scfDPSmear() const { return kFALSE; } //! Calculate the component integrals of the interference term void calcInterferenceTermIntegrals(); //! Calculate the total integral of the interference term void calcInterferenceTermNorm(); private: //! Keep access to the base class methods that we're further overloading using LauAbsFitModel::addFitParameters; //! Add the parameters from a decay time PDF into the fit /*! \param [in] decayTimePdf the container of PDFs */ UInt_t addFitParameters(LauDecayTimePdf* decayTimePdf); //! Add the parameters from each decay time PDF into the fit /*! \param [in] decayTimePdfList the container of PDFs */ UInt_t addFitParameters(std::vector& decayTimePdfList); //! Dalitz plot PDF for the antiparticle LauIsobarDynamics* sigModelB0bar_; //! Dalitz plot PDF for the particle LauIsobarDynamics* sigModelB0_; //! Kinematics object for antiparticle LauKinematics* kinematicsB0bar_; //! Kinematics object for particle LauKinematics* kinematicsB0_; //! The background Dalitz plot models for particles LauBkgndDPModelList BkgndDPModelsB_; //! The background Dalitz plot models for anti-particles LauBkgndDPModelList BkgndDPModelsBbar_; //! The background PDFs LauBkgndPdfsList BkgndPdfs_; //! Background boolean Bool_t usingBkgnd_; //! LauFlavTag object for flavour tagging LauFlavTag* flavTag_; //! Flavour tag for current event std::vector curEvtTagFlv_; //! Per event mistag for current event std::vector curEvtMistag_; //! Per event transformed mistag for current event std::vector curEvtMistagPrime_; //! True tag flavour (i.e. flavour at production) for the current event (only relevant for toy generation) LauFlavTag::Flavour curEvtTrueTagFlv_; //! Flavour at decay for the current event (only relevant for QFS) LauFlavTag::Flavour curEvtDecayFlv_; //! Number of signal components UInt_t nSigComp_; //! Number of signal DP parameters UInt_t nSigDPPar_; //! Number of decay time PDF parameters UInt_t nDecayTimePar_; //! Number of extra PDF parameters UInt_t nExtraPdfPar_; //! Number of normalisation parameters (yields, asymmetries) UInt_t nNormPar_; //! Number of calibration parameters (p0, p1) UInt_t nCalibPar_; //! Number of tagging efficneyc parameters UInt_t nTagEffPar_; //! Number of efficiency parameters (p0, p1) UInt_t nEffiPar_; //! Number of asymmetry parameters UInt_t nAsymPar_; //! Number of tagging asymmetry parameters UInt_t nTagAsymPar_; //! The complex coefficients for antiparticle std::vector coeffsB0bar_; //! The complex coefficients for particle std::vector coeffsB0_; //! Magnitudes and Phases or Real and Imaginary Parts std::vector coeffPars_; //! The integrals of the efficiency corrected amplitude cross terms for each pair of amplitude components /*! Calculated as the sum of A* x Abar x efficiency */ std::vector< std::vector > fifjEffSum_; //! The normalisation for the term 2.0*Re(A*Abar*phiMix) Double_t interTermReNorm_; //! The normalisation for the term 2.0*Im(A*Abar*phiMix) Double_t interTermImNorm_; //! The antiparticle fit fractions LauParArray fitFracB0bar_; //! The particle fit fractions LauParArray fitFracB0_; //! The fit fraction asymmetries std::vector fitFracAsymm_; //! A_CP parameter std::vector acp_; //! The mean efficiency for the antiparticle LauParameter meanEffB0bar_; //! The mean efficiency for the particle LauParameter meanEffB0_; //! The average DP rate for the antiparticle LauParameter DPRateB0bar_; //! The average DP rate for the particle LauParameter DPRateB0_; //! Signal yields LauParameter* signalEvents_; //! Signal asymmetry LauParameter* signalAsym_; //! Background yield(s) LauBkgndYieldList bkgndEvents_; //! Background asymmetries(s) LauBkgndYieldList bkgndAsym_; //! CP eigenvalue variable name TString cpevVarName_; //! CP eigenvalue for current event CPEigenvalue cpEigenValue_; //! Vector to store event CP eigenvalues std::vector evtCPEigenVals_; //! The mass difference between the neutral mass eigenstates LauParameter deltaM_; //! The width difference between the neutral mass eigenstates LauParameter deltaGamma_; //! The lifetime LauParameter tau_; //! The mixing phase LauParameter phiMix_; //! The sine of the mixing phase LauParameter sinPhiMix_; //! The cosine of the mixing phase LauParameter cosPhiMix_; //! Flag whether to use the sine and cosine of the mixing phase or the phase itself as the fit parameters Bool_t useSinCos_; //! e^{-i*phiMix} LauComplex phiMixComplex_; //! Signal Decay time PDFs (one per tagging category) LauDecayTimePdf* signalDecayTimePdf_; //! Background types std::vector BkgndTypes_; //! Background Decay time PDFs (one per tagging category) std::vector BkgndDecayTimePdfs_; //! Decay time for the current event Double_t curEvtDecayTime_; //! Decay time error for the current event Double_t curEvtDecayTimeErr_; //! PDFs for other variables LauPdfPList sigExtraPdf_; //! Production asymmetry between B0 and B0bar LauParameter AProd_; //! Production asymmetry between B0 and B0bar for bkgnds std::vector AProdBkgnd_; // Toy generation stuff //! The maximum allowed number of attempts when generating an event Int_t iterationsMax_; //! The number of unsucessful attempts to generate an event so far Int_t nGenLoop_; //! The value of A squared for the current event Double_t ASq_; //! The maximum value of A squared that has been seen so far while generating Double_t aSqMaxVar_; //! The maximum allowed value of A squared Double_t aSqMaxSet_; //! Flag for storage of amplitude info in generated ntuple Bool_t storeGenAmpInfo_; //! The signal event tree for embedding fully simulated events LauEmbeddedData* signalTree_; //! The background event tree for embedding fully simulated events std::vector bkgndTree_; //! Boolean to control reuse of embedded signal events Bool_t reuseSignal_; //! Boolean to use reweighting when embedding Bool_t useReweighting_; //! Vector of booleans to reuse background events LauBkgndReuseEventsList reuseBkgnd_; // Likelihood values //! Signal DP likelihood value Double_t sigDPLike_; //! Signal likelihood from extra PDFs Double_t sigExtraLike_; //! Total signal likelihood Double_t sigTotalLike_; //! Background DP likelihood value(s) std::vector bkgndDPLike_; //! Background likelihood value(s) from extra PDFs std::vector bkgndExtraLike_; //! Total background likelihood(s) std::vector bkgndTotalLike_; ClassDef(LauTimeDepFitModel,0) // Time-dependent neutral model }; #endif diff --git a/src/LauAbsFitModel.cc b/src/LauAbsFitModel.cc index 140f51f..6ef5431 100644 --- a/src/LauAbsFitModel.cc +++ b/src/LauAbsFitModel.cc @@ -1,1169 +1,1192 @@ /* Copyright 2004 University of Warwick Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Laura++ package authors: John Back Paul Harrison Thomas Latham */ /*! \file LauAbsFitModel.cc \brief File containing implementation of LauAbsFitModel class. */ #include #include #include #include "TMessage.h" #include "TMonitor.h" #include "TServerSocket.h" #include "TSocket.h" #include "TSystem.h" #include "TVirtualFitter.h" #include "LauAbsFitModel.hh" #include "LauAbsFitter.hh" #include "LauAbsPdf.hh" #include "LauComplex.hh" #include "LauFitter.hh" #include "LauFitDataTree.hh" #include "LauGenNtuple.hh" #include "LauParameter.hh" #include "LauParamFixed.hh" #include "LauPrint.hh" #include "LauSPlot.hh" ClassImp(LauAbsFitModel) LauAbsFitModel::LauAbsFitModel() : fixParams_(kFALSE), compareFitData_(kFALSE), savePDF_(kFALSE), writeLatexTable_(kFALSE), writeSPlotData_(kFALSE), storeDPEff_(kFALSE), randomFit_(kFALSE), emlFit_(kFALSE), poissonSmear_(kFALSE), enableEmbedding_(kFALSE), usingDP_(kTRUE), pdfsDependOnDP_(kFALSE), inputFitData_(0), genNtuple_(0), sPlotNtuple_(0), nullString_(""), doSFit_(kFALSE), sWeightBranchName_(""), sWeightScaleFactor_(1.0), outputTableName_(""), fitToyMCFileName_("fitToyMC.root"), fitToyMCTableName_("fitToyMCTable"), fitToyMCScale_(10), fitToyMCPoissonSmear_(kFALSE), sPlotFileName_(""), sPlotTreeName_(""), sPlotVerbosity_(LauOutputLevel::Quiet) { } LauAbsFitModel::~LauAbsFitModel() { delete inputFitData_; inputFitData_ = 0; delete genNtuple_; genNtuple_ = 0; delete sPlotNtuple_; sPlotNtuple_ = 0; // Remove the components created to apply constraints to fit parameters for ( auto par : conVars_ ) { if ( ! par->isLValue() ){ delete par; } } } void LauAbsFitModel::run(const TString& applicationCode, const TString& dataFileName, const TString& dataTreeName, const TString& histFileName, const TString& tableFileName) { // Chose whether you want to generate or fit events in the Dalitz plot. // To generate events choose applicationCode = "gen", to fit events choose // applicationCode = "fit". TString runCode(applicationCode); runCode.ToLower(); TString histFileNameCopy(histFileName); TString tableFileNameCopy(tableFileName); TString dataFileNameCopy(dataFileName); TString dataTreeNameCopy(dataTreeName); // Initialise the fit par vectors. Each class that inherits from this one // must implement this sensibly for all vectors specified in clearFitParVectors, // i.e. specify parameter names, initial, min, max and fixed values this->initialise(); // Add variables to Gaussian constrain to a list this->addConParameters(); if (dataFileNameCopy == "") {dataFileNameCopy = "data.root";} if (dataTreeNameCopy == "") {dataTreeNameCopy = "genResults";} if (runCode.Contains("gen")) { if (histFileNameCopy == "") {histFileNameCopy = "parInfo.root";} if (tableFileNameCopy == "") {tableFileNameCopy = "genResults";} this->setGenValues(); this->generate(dataFileNameCopy, dataTreeNameCopy, histFileNameCopy, tableFileNameCopy); } else if (runCode.Contains("fit")) { if (histFileNameCopy == "") {histFileNameCopy = "parInfo.root";} if (tableFileNameCopy == "") {tableFileNameCopy = "fitResults";} this->fit(dataFileNameCopy, dataTreeNameCopy, histFileNameCopy, tableFileNameCopy); } else if (runCode.Contains("plot")) { this->savePDFPlots("plot"); } else if (runCode.Contains("weight")) { this->weightEvents(dataFileNameCopy, dataTreeNameCopy); } } void LauAbsFitModel::doSFit( const TString& sWeightBranchName, Double_t scaleFactor ) { if ( sWeightBranchName == "" ) { std::cerr << "WARNING in LauAbsFitModel::doSFit : sWeight branch name is empty string, not setting-up sFit." << std::endl; return; } doSFit_ = kTRUE; sWeightBranchName_ = sWeightBranchName; sWeightScaleFactor_ = scaleFactor; } void LauAbsFitModel::setBkgndClassNames( const std::vector& names ) { if ( !bkgndClassNames_.empty() ) { std::cerr << "WARNING in LauAbsFitModel::setBkgndClassNames : Names already stored, not changing them." << std::endl; return; } UInt_t nBkgnds = names.size(); for ( UInt_t i(0); i < nBkgnds; ++i ) { bkgndClassNames_.insert( std::make_pair( i, names[i] ) ); } this->setupBkgndVectors(); } Bool_t LauAbsFitModel::validBkgndClass( const TString& className ) const { if ( bkgndClassNames_.empty() ) { return kFALSE; } Bool_t found(kFALSE); for ( LauBkgndClassMap::const_iterator iter = bkgndClassNames_.begin(); iter != bkgndClassNames_.end(); ++iter ) { if ( iter->second == className ) { found = kTRUE; break; } } return found; } UInt_t LauAbsFitModel::bkgndClassID( const TString& className ) const { if ( ! this->validBkgndClass( className ) ) { std::cerr << "ERROR in LauAbsFitModel::bkgndClassID : Request for ID for invalid background class \"" << className << "\"." << std::endl; return (bkgndClassNames_.size() + 1); } UInt_t bgID(0); for ( LauBkgndClassMap::const_iterator iter = bkgndClassNames_.begin(); iter != bkgndClassNames_.end(); ++iter ) { if ( iter->second == className ) { bgID = iter->first; break; } } return bgID; } const TString& LauAbsFitModel::bkgndClassName( UInt_t classID ) const { LauBkgndClassMap::const_iterator iter = bkgndClassNames_.find( classID ); if ( iter == bkgndClassNames_.end() ) { std::cerr << "ERROR in LauAbsFitModel::bkgndClassName : Request for name of invalid background class ID " << classID << "." << std::endl; return nullString_; } return iter->second; } void LauAbsFitModel::clearFitParVectors() { std::cout << "INFO in LauAbsFitModel::clearFitParVectors : Clearing fit variable vectors" << std::endl; // Remove the components created to apply constraints to fit parameters for ( auto par : conVars_ ) { if ( ! par->isLValue() ){ delete par; } } conVars_.clear(); resVars_.clear(); fitVars_.clear(); } void LauAbsFitModel::clearExtraVarVectors() { std::cout << "INFO in LauAbsFitModel::clearExtraVarVectors : Clearing extra ntuple variable vectors" << std::endl; extraVars_.clear(); } void LauAbsFitModel::setGenValues() { // makes sure each parameter holds its genValue as its current value for (LauParameterPList::iterator iter = fitVars_.begin(); iter != fitVars_.end(); ++iter) { (*iter)->value((*iter)->genValue()); } this->propagateParUpdates(); } void LauAbsFitModel::writeSPlotData(const TString& fileName, const TString& treeName, Bool_t storeDPEfficiency, const LauOutputLevel verbosity) { if (this->writeSPlotData()) { std::cerr << "ERROR in LauAbsFitModel::writeSPlotData : Already have an sPlot ntuple setup, not doing it again." << std::endl; return; } writeSPlotData_ = kTRUE; sPlotFileName_ = fileName; sPlotTreeName_ = treeName; sPlotVerbosity_ = verbosity; storeDPEff_ = storeDPEfficiency; } // TODO : histFileName isn't used here at the moment but could be used for // storing the values of the parameters used in the generation. // These could then be read and used for setting the "true" values // in a subsequent fit. void LauAbsFitModel::generate(const TString& dataFileName, const TString& dataTreeName, const TString& /*histFileName*/, const TString& tableFileNameBase) { // Create the ntuple for storing the results std::cout << "INFO in LauAbsFitModel::generate : Creating generation ntuple." << std::endl; if (genNtuple_ != 0) {delete genNtuple_; genNtuple_ = 0;} genNtuple_ = new LauGenNtuple(dataFileName,dataTreeName); // add branches for storing the experiment number and the number of // the event within the current experiment this->addGenNtupleIntegerBranch("iExpt"); this->addGenNtupleIntegerBranch("iEvtWithinExpt"); this->setupGenNtupleBranches(); // Start the cumulative timer cumulTimer_.Start(); const UInt_t firstExp = this->firstExpt(); const UInt_t nExp = this->nExpt(); Bool_t genOK(kTRUE); do { // Loop over the number of experiments for (UInt_t iExp = firstExp; iExp < (firstExp+nExp); ++iExp) { // Start the timer to see how long each experiment takes to generate timer_.Start(); // Store the experiment number in the ntuple this->setGenNtupleIntegerBranchValue("iExpt",iExp); // Do the generation for this experiment std::cout << "INFO in LauAbsFitModel::generate : Generating experiment number " << iExp << std::endl; genOK = this->genExpt(); // Stop the timer and see how long the program took so far timer_.Stop(); timer_.Print(); if (!genOK) { // delete and recreate an empty tree genNtuple_->deleteAndRecreateTree(); // then break out of the experiment loop std::cerr << "WARNING in LauAbsFitModel::generate : Problem in toy MC generation. Starting again with updated parameters..." << std::endl; break; } if (this->writeLatexTable()) { TString tableFileName(tableFileNameBase); tableFileName += "_"; tableFileName += iExp; tableFileName += ".tex"; this->writeOutTable(tableFileName); } } // Loop over number of experiments } while (!genOK); // Print out total timing info. cumulTimer_.Stop(); std::cout << "INFO in LauAbsFitModel::generate : Finished generating all experiments." << std::endl; std::cout << "INFO in LauAbsFitModel::generate : Cumulative timing:" << std::endl; cumulTimer_.Print(); // Build the event index std::cout << "INFO in LauAbsFitModel::generate : Building experiment:event index." << std::endl; // TODO - can test this return value? //Int_t nIndexEntries = genNtuple_->buildIndex("iExpt","iEvtWithinExpt"); // Write out toy MC ntuple std::cout << "INFO in LauAbsFitModel::generate : Writing data to file " << dataFileName << "." << std::endl; genNtuple_->writeOutGenResults(); } void LauAbsFitModel::addGenNtupleIntegerBranch(const TString& name) { genNtuple_->addIntegerBranch(name); } void LauAbsFitModel::addGenNtupleDoubleBranch(const TString& name) { genNtuple_->addDoubleBranch(name); } void LauAbsFitModel::setGenNtupleIntegerBranchValue(const TString& name, Int_t value) { genNtuple_->setIntegerBranchValue(name,value); } void LauAbsFitModel::setGenNtupleDoubleBranchValue(const TString& name, Double_t value) { genNtuple_->setDoubleBranchValue(name,value); } Int_t LauAbsFitModel::getGenNtupleIntegerBranchValue(const TString& name) const { return genNtuple_->getIntegerBranchValue(name); } Double_t LauAbsFitModel::getGenNtupleDoubleBranchValue(const TString& name) const { return genNtuple_->getDoubleBranchValue(name); } void LauAbsFitModel::fillGenNtupleBranches() { genNtuple_->fillBranches(); } void LauAbsFitModel::addSPlotNtupleIntegerBranch(const TString& name) { sPlotNtuple_->addIntegerBranch(name); } void LauAbsFitModel::addSPlotNtupleDoubleBranch(const TString& name) { sPlotNtuple_->addDoubleBranch(name); } void LauAbsFitModel::setSPlotNtupleIntegerBranchValue(const TString& name, Int_t value) { sPlotNtuple_->setIntegerBranchValue(name,value); } void LauAbsFitModel::setSPlotNtupleDoubleBranchValue(const TString& name, Double_t value) { sPlotNtuple_->setDoubleBranchValue(name,value); } void LauAbsFitModel::fillSPlotNtupleBranches() { sPlotNtuple_->fillBranches(); } void LauAbsFitModel::fit(const TString& dataFileName, const TString& dataTreeName, const TString& histFileName, const TString& tableFileNameBase) { // Routine to perform the total fit. const UInt_t firstExp = this->firstExpt(); const UInt_t nExp = this->nExpt(); std::cout << "INFO in LauAbsFitModel::fit : First experiment = " << firstExp << std::endl; std::cout << "INFO in LauAbsFitModel::fit : Number of experiments = " << nExp << std::endl; // Start the cumulative timer cumulTimer_.Start(); this->resetFitCounters(); // Create and setup the fit results ntuple this->setupResultsOutputs( histFileName, tableFileNameBase ); // Create and setup the sPlot ntuple if (this->writeSPlotData()) { std::cout << "INFO in LauAbsFitModel::fit : Creating sPlot ntuple." << std::endl; if (sPlotNtuple_ != 0) {delete sPlotNtuple_; sPlotNtuple_ = 0;} sPlotNtuple_ = new LauGenNtuple(sPlotFileName_,sPlotTreeName_); this->setupSPlotNtupleBranches(); } // This reads in the given dataFile and creates an input // fit data tree that stores them for all events and experiments. Bool_t dataOK = this->verifyFitData(dataFileName,dataTreeName); if (!dataOK) { std::cerr << "ERROR in LauAbsFitModel::fit : Problem caching the fit data." << std::endl; gSystem->Exit(EXIT_FAILURE); } // Loop over the number of experiments for (UInt_t iExp = firstExp; iExp < (firstExp+nExp); ++iExp) { // Start the timer to see how long each fit takes timer_.Start(); this->setCurrentExperiment( iExp ); UInt_t nEvents = this->readExperimentData(); if (nEvents < 1) { std::cerr << "WARNING in LauAbsFitModel::fit : Zero events in experiment " << iExp << ", skipping..." << std::endl; timer_.Stop(); continue; } // Now the sub-classes must implement whatever they need to do // to cache any more input fit data they need in order to // calculate the likelihoods during the fit. // They need to use the inputFitData_ tree as input. For example, // inputFitData_ contains m13Sq and m23Sq. The appropriate fit model // then caches the resonance dynamics for the signal model, as // well as the background likelihood values in the Dalitz plot this->cacheInputFitVars(); if ( this->doSFit() ) { this->cacheInputSWeights(); } // Do the fit for this experiment this->fitExpt(); // Write the results into the ntuple this->finaliseFitResults( outputTableName_ ); // Stop the timer and see how long the program took so far timer_.Stop(); timer_.Print(); // Store the per-event likelihood values if ( this->writeSPlotData() ) { this->storePerEvtLlhds(); } // Create a toy MC sample using the fitted parameters so that // the user can compare the fit to the data. if (compareFitData_ == kTRUE && this->statusCode() == 3) { this->createFitToyMC(fitToyMCFileName_, fitToyMCTableName_); } } // Loop over number of experiments // Print out total timing info. cumulTimer_.Stop(); std::cout << "INFO in LauAbsFitModel::fit : Cumulative timing:" << std::endl; cumulTimer_.Print(); // Print out stats on OK fits. const UInt_t nOKFits = this->numberOKFits(); const UInt_t nBadFits = this->numberBadFits(); std::cout << "INFO in LauAbsFitModel::fit : Number of OK Fits = " << nOKFits << std::endl; std::cout << "INFO in LauAbsFitModel::fit : Number of Failed Fits = " << nBadFits << std::endl; Double_t fitEff(0.0); if (nExp != 0) {fitEff = nOKFits/(1.0*nExp);} std::cout << "INFO in LauAbsFitModel::fit : Fit efficiency = " << fitEff*100.0 << "%." << std::endl; // Write out any fit results (ntuples etc...). this->writeOutAllFitResults(); if ( this->writeSPlotData() ) { this->calculateSPlotData(); } } void LauAbsFitModel::setupResultsOutputs( const TString& histFileName, const TString& tableFileName ) { this->LauSimFitTask::setupResultsOutputs( histFileName, tableFileName ); outputTableName_ = tableFileName; } Bool_t LauAbsFitModel::verifyFitData(const TString& dataFileName, const TString& dataTreeName) { // From the input data stream, store the variables into the // internal tree inputFitData_ that can be used by the sub-classes // in calculating their likelihood functions for the fit delete inputFitData_; inputFitData_ = new LauFitDataTree(dataFileName,dataTreeName); Bool_t dataOK = inputFitData_->findBranches(); if (!dataOK) { delete inputFitData_; inputFitData_ = 0; } return dataOK; } void LauAbsFitModel::cacheInputSWeights() { Bool_t hasBranch = inputFitData_->haveBranch( sWeightBranchName_ ); if ( ! hasBranch ) { std::cerr << "ERROR in LauAbsFitModel::cacheInputSWeights : Input data does not contain variable \"" << sWeightBranchName_ << "\".\n"; std::cerr << " : Turning off sFit!" << std::endl; doSFit_ = kFALSE; return; } UInt_t nEvents = this->eventsPerExpt(); sWeights_.clear(); sWeights_.reserve( nEvents ); for (UInt_t iEvt = 0; iEvt < nEvents; ++iEvt) { const LauFitData& dataValues = inputFitData_->getData(iEvt); LauFitData::const_iterator iter = dataValues.find( sWeightBranchName_ ); sWeights_.push_back( iter->second * sWeightScaleFactor_ ); } } void LauAbsFitModel::fitExpt() { // Routine to perform the actual fit for the given experiment // Update initial fit parameters if required (e.g. if using random numbers). this->checkInitFitParams(); // Initialise the fitter LauFitter::fitter()->useAsymmFitErrors( this->useAsymmFitErrors() ); LauFitter::fitter()->twoStageFit( this->twoStageFit() ); LauFitter::fitter()->initialise( this, fitVars_ ); this->startNewFit( LauFitter::fitter()->nParameters(), LauFitter::fitter()->nFreeParameters() ); // Now ready for minimisation step std::cout << "\nINFO in LauAbsFitModel::fitExpt : Start minimisation...\n"; LauAbsFitter::FitStatus fitResult = LauFitter::fitter()->minimise(); // If we're doing a two stage fit we can now release (i.e. float) // the 2nd stage parameters and re-fit if (this->twoStageFit()) { if ( fitResult.status != 3 ) { std::cerr << "WARNING in LauAbsFitModel:fitExpt : Not running second stage fit since first stage failed." << std::endl; LauFitter::fitter()->releaseSecondStageParameters(); } else { LauFitter::fitter()->releaseSecondStageParameters(); this->startNewFit( LauFitter::fitter()->nParameters(), LauFitter::fitter()->nFreeParameters() ); fitResult = LauFitter::fitter()->minimise(); } } const TMatrixD& covMat = LauFitter::fitter()->covarianceMatrix(); this->storeFitStatus( fitResult, covMat ); // Store the final fit results and errors into protected internal vectors that // all sub-classes can use within their own finalFitResults implementation // used below (e.g. putting them into an ntuple in a root file) LauFitter::fitter()->updateParameters(); } void LauAbsFitModel::calculateSPlotData() { if (sPlotNtuple_ != 0) { sPlotNtuple_->addFriendTree(inputFitData_->fileName(), inputFitData_->treeName()); sPlotNtuple_->writeOutGenResults(); LauSPlot splot(sPlotNtuple_->fileName(), sPlotNtuple_->treeName(), this->firstExpt(), this->nExpt(), this->variableNames(), this->freeSpeciesNames(), this->fixdSpeciesNames(), this->twodimPDFs(), this->splitSignal(), this->scfDPSmear()); splot.runCalculations(sPlotVerbosity_); splot.writeOutResults(); } } void LauAbsFitModel::compareFitData(UInt_t toyMCScale, const TString& mcFileName, const TString& tableFileName, Bool_t poissonSmearing) { compareFitData_ = kTRUE; fitToyMCScale_ = toyMCScale; fitToyMCFileName_ = mcFileName; fitToyMCTableName_ = tableFileName; fitToyMCPoissonSmear_ = poissonSmearing; } void LauAbsFitModel::createFitToyMC(const TString& mcFileName, const TString& tableFileName) { // Create a toy MC sample so that the user can compare the fitted // result with the data. // Generate more toy MC to reduce statistical fluctuations: // - use the rescaling value fitToyMCScale_ // Store the info on the number of experiments, first expt and current expt const UInt_t oldNExpt(this->nExpt()); const UInt_t oldFirstExpt(this->firstExpt()); const UInt_t oldIExpt(this->iExpt()); // Turn off Poisson smearing if required const Bool_t poissonSmearing(this->doPoissonSmearing()); this->doPoissonSmearing(fitToyMCPoissonSmear_); // Turn off embedding, since we need toy MC, not reco'ed events const Bool_t enableEmbeddingOrig(this->enableEmbedding()); this->enableEmbedding(kFALSE); // Need to make sure that the generation of the DP co-ordinates is // switched on if any of our PDFs depend on it const Bool_t origUseDP = this->useDP(); if ( !origUseDP && this->pdfsDependOnDP() ) { this->useDP( kTRUE ); this->initialiseDPModels(); } // Construct a unique filename for this experiment TString exptString("_expt"); exptString += oldIExpt; TString fileName( mcFileName ); fileName.Insert( fileName.Last('.'), exptString ); // Generate the toy MC std::cout << "INFO in LauAbsFitModel::createFitToyMC : Generating toy MC in " << fileName << " to compare fit with data...\n"; std::cout << " : Number of experiments to generate = " << fitToyMCScale_ << "\n"; std::cout << " : This is to allow the toy MC to be made with reduced statistical fluctuations\n"; std::cout << " : Number of events in each experiment will be " << (fitToyMCPoissonSmear_ ? "fluctuated according to a Poisson distribution" : "exactly the same") << std::endl; // Set the genValue of each parameter to its current (fitted) value // but first store the original genValues for restoring later std::vector origGenValues; origGenValues.reserve(this->nTotParams()); Bool_t blind(kFALSE); for (LauParameterPList::iterator iter = fitVars_.begin(); iter != fitVars_.end(); ++iter) { origGenValues.push_back((*iter)->genValue()); (*iter)->genValue((*iter)->unblindValue()); if ( (*iter)->blind() ) { blind = kTRUE; } } if ( blind ) { std::cerr << "WARNING in LauAbsFitModel::createFitToyMC : One or more parameters are blind but the toy will be created using the unblind values - use with caution!!" << std::endl; } // If we're asked to generate more than 100 experiments then split it // up into multiple files since otherwise can run into memory issues // when building the index // TODO - this obviously depends on the number of events per experiment as well, so should do this properly UInt_t totalExpts = fitToyMCScale_; if ( totalExpts > 100 ) { UInt_t nFiles = totalExpts/100; if ( totalExpts%100 ) { nFiles += 1; } TString fileNameBase {fileName}; for ( UInt_t iFile(0); iFile < nFiles; ++iFile ) { UInt_t firstExp( iFile*100 ); // Set number of experiments and first experiment to generate UInt_t nExp = ((firstExp + 100)>totalExpts) ? totalExpts-firstExp : 100; this->setNExpts(nExp, firstExp); // Create a unique filename and generate the events fileName = fileNameBase; TString extraname = "_file"; extraname += iFile; fileName.Insert( fileName.Last('.'), extraname ); this->generate(fileName, "genResults", "dummy.root", tableFileName); } } else { // Set number of experiments to new value this->setNExpts(fitToyMCScale_, 0); // Generate the toy this->generate(fileName, "genResults", "dummy.root", tableFileName); } // Reset number of experiments to original value this->setNExpts(oldNExpt, oldFirstExpt); this->setCurrentExperiment(oldIExpt); // Restore the Poisson smearing to its former value this->doPoissonSmearing(poissonSmearing); // Restore the embedding status this->enableEmbedding(enableEmbeddingOrig); // Restore "useDP" to its former status this->useDP( origUseDP ); // Restore the original genValue to each parameter for (UInt_t i(0); inTotParams(); ++i) { fitVars_[i]->genValue(origGenValues[i]); } std::cout << "INFO in LauAbsFitModel::createFitToyMC : Finished in createFitToyMC." << std::endl; } Double_t LauAbsFitModel::getTotNegLogLikelihood() { // Calculate the total negative log-likelihood over all events. // This function assumes that the fit parameters and data tree have // already been set-up correctly. // Loop over the data points to calculate the log likelihood Double_t logLike = this->getLogLikelihood( 0, this->eventsPerExpt() ); // Include the Poisson term in the extended likelihood if required if (this->doEMLFit()) { logLike -= this->getEventSum(); } // Calculate any penalty terms from Gaussian constrained variables if ( ! conVars_.empty() ){ logLike -= this->getLogLikelihoodPenalty(); } Double_t totNegLogLike = -logLike; return totNegLogLike; } Double_t LauAbsFitModel::getLogLikelihoodPenalty() { Double_t penalty(0.0); for ( LauAbsRValuePList::const_iterator iter = conVars_.begin(); iter != conVars_.end(); ++iter ) { Double_t val = (*iter)->unblindValue(); Double_t mean = (*iter)->constraintMean(); Double_t width = (*iter)->constraintWidth(); Double_t term = ( val - mean )*( val - mean ); penalty += term/( 2*width*width ); } return penalty; } Double_t LauAbsFitModel::getLogLikelihood( UInt_t iStart, UInt_t iEnd ) { // Calculate the total negative log-likelihood over all events. // This function assumes that the fit parameters and data tree have // already been set-up correctly. // Loop over the data points to calculate the log likelihood Double_t logLike(0.0); const Double_t worstLL = this->worstLogLike(); // Loop over the number of events in this experiment Bool_t ok(kTRUE); for (UInt_t iEvt = iStart; iEvt < iEnd; ++iEvt) { Double_t likelihood = this->getTotEvtLikelihood(iEvt); if (likelihood > std::numeric_limits::min()) { // Is the likelihood zero? Double_t evtLogLike = TMath::Log(likelihood); if ( doSFit_ ) { evtLogLike *= sWeights_[iEvt]; } logLike += evtLogLike; } else { ok = kFALSE; std::cerr << "WARNING in LauAbsFitModel::getLogLikelihood : Strange likelihood value for event " << iEvt << ": " << likelihood << "\n"; this->printEventInfo(iEvt); this->printVarsInfo(); //Write the values of the floated variables for which the likelihood is zero break; } } if (!ok) { std::cerr << " : Returning worst NLL found so far to force MINUIT out of this region." << std::endl; logLike = worstLL; } else if (logLike < worstLL) { this->worstLogLike( logLike ); } return logLike; } void LauAbsFitModel::setParsFromMinuit(Double_t* par, Int_t npar) { // This function sets the internal parameters based on the values // that Minuit is using when trying to minimise the total likelihood function. // MINOS reports different numbers of free parameters depending on the // situation, so disable this check if ( ! this->withinAsymErrorCalc() ) { const UInt_t nFreePars = this->nFreeParams(); if (static_cast(npar) != nFreePars) { std::cerr << "ERROR in LauAbsFitModel::setParsFromMinuit : Unexpected number of free parameters: " << npar << ".\n"; std::cerr << " Expected: " << nFreePars << ".\n" << std::endl; gSystem->Exit(EXIT_FAILURE); } } // Despite npar being the number of free parameters // the par array actually contains all the parameters, // free and floating... // Update all the floating ones with their new values // Also check if we have any parameters on which the DP integrals depend // and whether they have changed since the last iteration Bool_t recalcNorm(kFALSE); const LauParameterPSet::const_iterator resVarsEnd = resVars_.end(); for (UInt_t i(0); inTotParams(); ++i) { if (!fitVars_[i]->fixed()) { if ( resVars_.find( fitVars_[i] ) != resVarsEnd ) { if ( fitVars_[i]->value() != par[i] ) { recalcNorm = kTRUE; } } fitVars_[i]->value(par[i]); } } // If so, then recalculate the normalisation if (recalcNorm) { this->recalculateNormalisation(); } this->propagateParUpdates(); } UInt_t LauAbsFitModel::addFitParameters(LauParameter* param, const Bool_t addFixed) { UInt_t nParsAdded{0}; + // check the pointer is valid + if ( ! param ) { + return nParsAdded; + } + // if we're dealing with a clone, // we should instead deal with its parent if ( param->clone() ) { param = param->parent(); } // we need to include the parameter if it is either: // - floating // - currently fixed but will float in the second stage of a two-stage fit if ( addFixed || ! param->fixed() || ( this->twoStageFit() && param->secondStage() ) ) { // check whether we already have this parameter stored auto [ _, addedOK ] { fitVarsSet_.insert( param ) }; if ( addedOK ) { // if not, add it to the list fitVars_.push_back( param ); ++nParsAdded; } } return nParsAdded; } UInt_t LauAbsFitModel::addFitParameters(LauParameterPList& paramList, const Bool_t addFixed) { UInt_t nParsAdded{0}; for ( auto param : paramList ) { nParsAdded += this->addFitParameters( param, addFixed ); } return nParsAdded; } +UInt_t LauAbsFitModel::addFitParameters(std::vector>& paramList, const Bool_t addFixed) +{ + UInt_t nParsAdded{0}; + + for ( auto& paramArray : paramList ) { + nParsAdded += this->addFitParameters( paramArray[0], addFixed ); + nParsAdded += this->addFitParameters( paramArray[1], addFixed ); + nParsAdded += this->addFitParameters( paramArray[2], addFixed ); + } + + return nParsAdded; +} + UInt_t LauAbsFitModel::addFitParameters(LauAbsRValue* param, const Bool_t addFixed) { UInt_t nParsAdded{0}; + // check the pointer is valid + if ( ! param ) { + return nParsAdded; + } + LauParameterPList pars { param->getPars() }; for ( auto par : pars ) { nParsAdded += this->addFitParameters( par, addFixed ); } return nParsAdded; } UInt_t LauAbsFitModel::addFitParameters(LauAbsRValuePList& paramList, const Bool_t addFixed) { UInt_t nParsAdded{0}; for ( auto param : paramList ) { nParsAdded += this->addFitParameters( param, addFixed ); } return nParsAdded; } UInt_t LauAbsFitModel::addFitParameters(LauPdfPList& pdfList, const Bool_t addFixed) { UInt_t nParsAdded{0}; for ( auto pdf : pdfList ) { if ( pdf->isDPDependent() ) { this->pdfsDependOnDP( kTRUE ); } LauAbsRValuePList& pars = pdf->getParameters(); nParsAdded += this->addFitParameters( pars, addFixed ); } return nParsAdded; } UInt_t LauAbsFitModel::addResonanceParameters(LauParameter* param) { UInt_t nParsAdded{0}; // first check if we have this parameter in the set of resonance parameters auto [ _, addedOK ] { resVars_.insert( param ) }; if ( addedOK ) { nParsAdded += this->addFitParameters( param ); } return nParsAdded; } UInt_t LauAbsFitModel::addResonanceParameters(LauParameterPList& paramList) { UInt_t nParsAdded{0}; for ( auto param : paramList ) { nParsAdded += this->addResonanceParameters( param ); } return nParsAdded; } void LauAbsFitModel::addConParameters() { for ( LauParameterPList::const_iterator iter = fitVars_.begin(); iter != fitVars_.end(); ++iter ) { if ( (*iter)->gaussConstraint() ) { conVars_.push_back( *iter ); std::cout << "INFO in LauAbsFitModel::addConParameters : Added Gaussian constraint to parameter "<< (*iter)->name() << std::endl; } } // Add penalties from the constraints to fit parameters const std::vector& storeCon = this->constraintsStore(); for ( std::vector::const_iterator iter = storeCon.begin(); iter != storeCon.end(); ++iter ) { const std::vector& names = (*iter).conPars_; std::vector params; for ( std::vector::const_iterator iternames = names.begin(); iternames != names.end(); ++iternames ) { for ( LauParameterPList::const_iterator iterfit = fitVars_.begin(); iterfit != fitVars_.end(); ++iterfit ) { if ( (*iternames) == (*iterfit)->name() ){ params.push_back(*iterfit); } } } // If the parameters are not found, skip it if ( params.size() != (*iter).conPars_.size() ) { std::cerr << "WARNING in LauAbsFitModel::addConParameters: Could not find parameters to constrain in the formula... skipping" << std::endl; continue; } LauFormulaPar* formPar = new LauFormulaPar( (*iter).formula_, (*iter).formula_, params ); formPar->addGaussianConstraint( (*iter).mean_, (*iter).width_ ); conVars_.push_back(formPar); std::cout << "INFO in LauAbsFitModel::addConParameters : Added Gaussian constraint to formula\n"; std::cout << " : Formula: " << (*iter).formula_ << std::endl; for ( std::vector::iterator iterparam = params.begin(); iterparam != params.end(); ++iterparam ) { std::cout << " : Parameter: " << (*iterparam)->name() << std::endl; } } } void LauAbsFitModel::updateFitParameters(LauPdfPList& pdfList) { for (LauPdfPList::iterator pdf_iter = pdfList.begin(); pdf_iter != pdfList.end(); ++pdf_iter) { (*pdf_iter)->updatePulls(); } } void LauAbsFitModel::printFitParameters(const LauPdfPList& pdfList, std::ostream& fout) const { LauPrint print; for (LauPdfPList::const_iterator pdf_iter = pdfList.begin(); pdf_iter != pdfList.end(); ++pdf_iter) { const LauAbsRValuePList& pars = (*pdf_iter)->getParameters(); for (LauAbsRValuePList::const_iterator pars_iter = pars.begin(); pars_iter != pars.end(); ++pars_iter) { LauParameterPList params = (*pars_iter)->getPars(); for (LauParameterPList::iterator params_iter = params.begin(); params_iter != params.end(); ++params_iter) { if (!(*params_iter)->clone()) { fout << (*params_iter)->name() << " & $"; print.printFormat(fout, (*params_iter)->value()); if ((*params_iter)->fixed() == kTRUE) { fout << "$ (fixed) \\\\"; } else { fout << " \\pm "; print.printFormat(fout, (*params_iter)->error()); fout << "$ \\\\" << std::endl; } } } } } } void LauAbsFitModel::cacheInfo(LauPdfPList& pdfList, const LauFitDataTree& theData) { for (LauPdfPList::iterator pdf_iter = pdfList.begin(); pdf_iter != pdfList.end(); ++pdf_iter) { (*pdf_iter)->cacheInfo(theData); } } Double_t LauAbsFitModel::prodPdfValue(LauPdfPList& pdfList, UInt_t iEvt) { Double_t pdfVal = 1.0; for (LauPdfPList::iterator pdf_iter = pdfList.begin(); pdf_iter != pdfList.end(); ++pdf_iter) { (*pdf_iter)->calcLikelihoodInfo(iEvt); pdfVal *= (*pdf_iter)->getLikelihood(); } return pdfVal; } void LauAbsFitModel::printEventInfo(UInt_t iEvt) const { const LauFitData& data = inputFitData_->getData(iEvt); std::cerr << " : Input data values for this event:" << std::endl; for (LauFitData::const_iterator iter = data.begin(); iter != data.end(); ++iter) { std::cerr << " " << iter->first << " = " << iter->second << std::endl; } } void LauAbsFitModel::printVarsInfo() const { std::cerr << " : Current values of fit parameters:" << std::endl; for (UInt_t i(0); inTotParams(); ++i) { std::cerr << " " << (fitVars_[i]->name()).Data() << " = " << fitVars_[i]->value() << std::endl; } } void LauAbsFitModel::prepareInitialParArray( TObjArray& array ) { // Update initial fit parameters if required (e.g. if using random numbers). this->checkInitFitParams(); // Store the total number of parameters and the number of free parameters UInt_t nPars = fitVars_.size(); UInt_t nFreePars = 0; // Send the fit parameters for ( LauParameterPList::iterator iter = fitVars_.begin(); iter != fitVars_.end(); ++iter ) { if ( ! (*iter)->fixed() ) { ++nFreePars; } array.Add( *iter ); } this->startNewFit( nPars, nFreePars ); } void LauAbsFitModel::finaliseExperiment( const LauAbsFitter::FitStatus& fitStat, const TObjArray* parsFromCoordinator, const TMatrixD* covMat, TObjArray& parsToCoordinator ) { // Copy the fit status information this->storeFitStatus( fitStat, *covMat ); // Now process the parameters const UInt_t nPars = this->nTotParams(); UInt_t nParsFromCoordinator = parsFromCoordinator->GetEntries(); if ( nParsFromCoordinator != nPars ) { std::cerr << "ERROR in LauAbsFitModel::finaliseExperiment : Unexpected number of parameters received from coordinator" << std::endl; std::cerr << " : Received " << nParsFromCoordinator << " when expecting " << nPars << std::endl; gSystem->Exit( EXIT_FAILURE ); } for ( UInt_t iPar(0); iPar < nParsFromCoordinator; ++iPar ) { LauParameter* parameter = dynamic_cast( (*parsFromCoordinator)[iPar] ); if ( ! parameter ) { std::cerr << "ERROR in LauAbsFitModel::finaliseExperiment : Error reading parameter from coordinator" << std::endl; gSystem->Exit( EXIT_FAILURE ); } if ( parameter->name() != fitVars_[iPar]->name() ) { std::cerr << "ERROR in LauAbsFitModel::finaliseExperiment : Error reading parameter from coordinator" << std::endl; gSystem->Exit( EXIT_FAILURE ); } *(fitVars_[iPar]) = *parameter; } // Write the results into the ntuple this->finaliseFitResults( outputTableName_ ); // Store the per-event likelihood values if ( this->writeSPlotData() ) { this->storePerEvtLlhds(); } // Create a toy MC sample using the fitted parameters so that // the user can compare the fit to the data. if (compareFitData_ == kTRUE && fitStat.status == 3) { this->createFitToyMC(fitToyMCFileName_, fitToyMCTableName_); } // Send the finalised fit parameters for ( LauParameterPList::iterator iter = fitVars_.begin(); iter != fitVars_.end(); ++iter ) { parsToCoordinator.Add( *iter ); } } UInt_t LauAbsFitModel::readExperimentData() { // retrieve the data and find out how many events have been read const UInt_t exptIndex = this->iExpt(); inputFitData_->readExperimentData( exptIndex ); const UInt_t nEvent = inputFitData_->nEvents(); this->eventsPerExpt( nEvent ); return nEvent; } void LauAbsFitModel::setParametersFromFile(const TString& fileName, const TString& treeName, const Bool_t fix) { fixParamFileName_ = fileName; fixParamTreeName_ = treeName; fixParams_ = fix; } void LauAbsFitModel::setParametersFromMap(const std::map& parameters, const Bool_t fix) { fixParamMap_ = parameters; fixParams_ = fix; } void LauAbsFitModel::setNamedParameters(const TString& fileName, const TString& treeName, const std::set& parameters, const Bool_t fix) { fixParamFileName_ = fileName; fixParamTreeName_ = treeName; fixParamNames_ = parameters; fixParams_ = fix; } void LauAbsFitModel::setParametersFileFallback(const TString& fileName, const TString& treeName, const std::map& parameters, const Bool_t fix) { fixParamFileName_ = fileName; fixParamTreeName_ = treeName; fixParamMap_ = parameters; fixParams_ = fix; } diff --git a/src/LauFlavTag.cc b/src/LauFlavTag.cc index ed5c80c..234bc8b 100644 --- a/src/LauFlavTag.cc +++ b/src/LauFlavTag.cc @@ -1,1203 +1,1429 @@ /* Copyright 2017 University of Warwick Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Laura++ package authors: John Back Paul Harrison Thomas Latham */ /*! \file LauFlavTag.cc \brief File containing implementation of LauFlavTag class. */ #include #include #include #include "TMath.h" #include "TString.h" #include "TSystem.h" #include "Lau1DHistPdf.hh" #include "LauAbsPdf.hh" #include "LauFlavTag.hh" #include "LauRandom.hh" ClassImp(LauFlavTag) std::ostream& operator<<( std::ostream& stream, const LauFlavTag::BkgndType bkgndType ) { switch ( bkgndType ) { case LauFlavTag::BkgndType::Combinatorial : stream << "Combinatorial"; break; case LauFlavTag::BkgndType::FlavourSpecific : stream << "FlavourSpecific"; break; case LauFlavTag::BkgndType::SelfConjugate : stream << "SelfConjugate"; break; case LauFlavTag::BkgndType::NonSelfConjugate : stream << "NonSelfConjugate"; break; } return stream; } LauFlavTag::LauFlavTag(const Bool_t useAveDelta, const Bool_t useEtaPrime, const std::map bkgndInfo) : useAveDelta_(useAveDelta), useEtaPrime_(useEtaPrime) { // Put map values into vectors + bkgndTypes_.reserve( bkgndInfo.size() ); + bkgndDecayFlvDep_.reserve( bkgndInfo.size() ); for (const auto& [ bkgndName, bkgndType ] : bkgndInfo){ - bkgndNames_.push_back(bkgndName); + const std::size_t bkgndPos { bkgndIndex_.size() }; + bkgndIndex_.insert(std::make_pair(bkgndName, bkgndPos)); bkgndTypes_.push_back(bkgndType); + bkgndDecayFlvDep_.push_back(false); std::cout<< "INFO in LauFlavTag::LauFlavTag : adding background " << bkgndName << " of type " << bkgndType < 0){ + if ( not bkgndIndex_.empty() ){ + const std::size_t nBkgnds { bkgndIndex_.size() }; if (!useAveDelta_){ tagEffBkgnd_B0_.clear(); tagEffBkgnd_B0_.resize(nBkgnds); tagEffBkgnd_B0bar_.clear(); tagEffBkgnd_B0bar_.resize(nBkgnds); tagEffBkgnd_hist_B0_.clear(); tagEffBkgnd_hist_B0_.resize(nBkgnds); tagEffBkgnd_hist_B0bar_.clear(); tagEffBkgnd_hist_B0bar_.resize(nBkgnds); } else { tagEffBkgnd_ave_.clear(); tagEffBkgnd_ave_.resize(nBkgnds); tagEffBkgnd_delta_.clear(); tagEffBkgnd_delta_.resize(nBkgnds); tagEffBkgnd_hist_ave_.clear(); tagEffBkgnd_hist_ave_.resize(nBkgnds); tagEffBkgnd_hist_delta_.clear(); tagEffBkgnd_hist_delta_.resize(nBkgnds); } etaBkgndPdfs_.clear(); etaBkgndPdfs_.resize(nBkgnds); avgMistagBkgnd_.clear(); avgMistagBkgnd_.resize(nBkgnds); } } +std::vector LauFlavTag::getBkgndNames() +{ + std::vector names; + names.reserve( bkgndIndex_.size() ); + + for ( auto& [ name, _ ] : bkgndIndex_ ) { + names.push_back( name ); + } + + return names; +} + void LauFlavTag::addTagger(const TString& name, const TString& tagVarName, const TString& mistagVarName, LauAbsPdf* etapdf, const std::pair tagEff, const std::pair calib_p0, const std::pair calib_p1) { // Check that we don't already have a tagger with the same name - if ( taggerPosition_.find(name) != taggerPosition_.end() ) { + if ( taggerIndex_.find(name) != taggerIndex_.end() ) { std::cerr << "ERROR in LauFlavTag::addTagger : tagger called " << name << " already added" << std::endl; gSystem->Exit(EXIT_FAILURE); } // Check that the PDF pointer is valid if ( not etapdf ) { std::cerr << "ERROR in LauFlavTag::addTagger : Eta PDF pointer is NULL" << std::endl; gSystem->Exit(EXIT_FAILURE); } // Find how many taggers have already been added - const ULong_t position { tagVarNames_.size() }; + const std::size_t index { tagVarNames_.size() }; - // Update map to relate tagger name and position in the vectors - taggerPosition_[name] = position; + // Update map to relate tagger name and index in the vectors + taggerIndex_[name] = index; // Extend vectors this->extendVectors(tagVarName, mistagVarName); etaPdfs_.push_back(etapdf); Lau1DHistPdf* etahistpdf = dynamic_cast(etapdf); if (etahistpdf){ perEvtAvgMistag_.push_back(etahistpdf->getMean()); } else { std::cerr << "WARNING in LauFlavTag::addTagger : Couldn't determine average eta value from PDF. Setting it to 0.4." << std::endl; perEvtAvgMistag_.push_back(0.4); } //Calib parameters - this->setupCalibParams(name,position,calib_p0,calib_p1); + this->setupCalibParams(name,calib_p0,calib_p1); //Tagging efficiencies if (!useAveDelta_){ TString tagEff_b0Name("tagEff_b0_"+name); TString tagEff_b0barName("tagEff_b0bar_"+name); LauParameter* tageffb0 = new LauParameter(tagEff_b0Name,tagEff.first,0.0,1.0,kTRUE); tagEff_B0_.push_back(tageffb0); - tagEff_B0_[position]->initValue(tagEff.first); tagEff_B0_[position]->genValue(tagEff.first); - tagEff_B0_[position]->fixed(kTRUE); + tagEff_B0_[index]->initValue(tagEff.first); tagEff_B0_[index]->genValue(tagEff.first); + tagEff_B0_[index]->fixed(kTRUE); if (tagEff.second==-1.0){ - tagEff_B0bar_.push_back(tagEff_B0_[position]->createClone(tagEff_b0barName)); + tagEff_B0bar_.push_back(tagEff_B0_[index]->createClone(tagEff_b0barName)); } else { LauParameter* tageffb0bar = new LauParameter(tagEff_b0barName,tagEff.second,0.0,1.0,kTRUE); tagEff_B0bar_.push_back(tageffb0bar); - tagEff_B0bar_[position]->initValue(tagEff.second); tagEff_B0bar_[position]->genValue(tagEff.second); - tagEff_B0bar_[position]->fixed(kTRUE); + tagEff_B0bar_[index]->initValue(tagEff.second); tagEff_B0bar_[index]->genValue(tagEff.second); + tagEff_B0bar_[index]->fixed(kTRUE); } } else { //Use average and delta variables TString tagEff_aveName("tagEff_ave_"+name); TString tagEff_deltaName("tagEff_delta_"+name); LauParameter* tageffave = new LauParameter(tagEff_aveName,tagEff.first,0.0,1.0,kTRUE); tagEff_ave_.push_back(tageffave); - tagEff_ave_[position]->initValue(tagEff.first); tagEff_ave_[position]->genValue(tagEff.first); - tagEff_ave_[position]->fixed(kTRUE); + tagEff_ave_[index]->initValue(tagEff.first); tagEff_ave_[index]->genValue(tagEff.first); + tagEff_ave_[index]->fixed(kTRUE); LauParameter* tageffdelta = new LauParameter(tagEff_deltaName,tagEff.second,-1.0,1.0,kTRUE); tagEff_delta_.push_back(tageffdelta); - tagEff_delta_[position]->initValue(tagEff.second); tagEff_delta_[position]->genValue(tagEff.second); - tagEff_delta_[position]->fixed(kTRUE); + tagEff_delta_[index]->initValue(tagEff.second); tagEff_delta_[index]->genValue(tagEff.second); + tagEff_delta_[index]->fixed(kTRUE); } std::cout<<"INFO in LauFlavTag::addTagger : Added tagger with name "<< name << std::endl; } void LauFlavTag::addTagger(const TString& name, const TString& tagVarName, const TString& mistagVarName, LauAbsPdf* etapdf, const std::pair tagEff, const std::pair calib_p0, const std::pair calib_p1) { // Check that we don't already have a tagger with the same name - if ( taggerPosition_.find(name) != taggerPosition_.end() ) { + if ( taggerIndex_.find(name) != taggerIndex_.end() ) { std::cerr << "ERROR in LauFlavTag::addTagger : tagger called " << name << " already added" << std::endl; gSystem->Exit(EXIT_FAILURE); } // Check that the PDF pointer is valid if ( not etapdf ) { std::cerr << "ERROR in LauFlavTag::addTagger : Eta PDF pointer is NULL" << std::endl; gSystem->Exit(EXIT_FAILURE); } // Find how many taggers have already been added - const ULong_t position { tagVarNames_.size() }; + const std::size_t index { tagVarNames_.size() }; - // Update map to relate tagger name and position in the vectors - taggerPosition_[name] = position; + // Update map to relate tagger name and index in the vectors + taggerIndex_[name] = index; // Extend vectors this->extendVectors(tagVarName, mistagVarName); etaPdfs_.push_back(etapdf); Lau1DHistPdf* etahistpdf = dynamic_cast(etapdf); if (etahistpdf){ perEvtAvgMistag_.push_back(etahistpdf->getMean()); } else { std::cerr << "WARNING in LauFlavTag::addTagger : Couldn't determine average eta value from PDF. Setting it to 0.4." << std::endl; perEvtAvgMistag_.push_back(0.4); } //Calib parameters - this->setupCalibParams(name,position,calib_p0,calib_p1); + this->setupCalibParams(name,calib_p0,calib_p1); //Tagging efficiencies if (!useAveDelta_){ tagEff_hist_B0_.push_back(tagEff.first); tagEff_B0_.push_back(nullptr); if (tagEff.second==nullptr){ tagEff_hist_B0bar_.push_back(tagEff.first); tagEff_B0bar_.push_back(nullptr); } else { tagEff_hist_B0bar_.push_back(tagEff.second); tagEff_B0bar_.push_back(nullptr); } } else { //Use average and delta variables tagEff_hist_ave_.push_back(tagEff.first); tagEff_hist_delta_.push_back(tagEff.second); tagEff_ave_.push_back(nullptr); tagEff_delta_.push_back(nullptr); } std::cout<<"INFO in LauFlavTag::addTagger : Added tagger with name "<< name << std::endl; } -void LauFlavTag::extendVectors(const TString& tagVarName, const TString& mistagVarName){ +void LauFlavTag::extendVectors(const TString& tagVarName, const TString& mistagVarName) +{ tagVarNames_.push_back(tagVarName); mistagVarNames_.push_back(mistagVarName); curEvtTagFlv_.push_back(Flavour::Unknown); curEvtMistag_.push_back(Flavour::Unknown); - if (bkgndNames_.size()>0){ + if ( not bkgndIndex_.empty() ){ if (!useAveDelta_){ //Loop over the outer vector and extend the inner vectors for (auto& innerVec : tagEffBkgnd_B0_){ - innerVec.push_back(nullptr); + innerVec.push_back({nullptr,nullptr,nullptr}); } for (auto& innerVec : tagEffBkgnd_hist_B0_){ - innerVec.push_back(nullptr); + innerVec.push_back({nullptr,nullptr,nullptr}); } for (auto& innerVec : tagEffBkgnd_B0bar_){ - innerVec.push_back(nullptr); + innerVec.push_back({nullptr,nullptr,nullptr}); } for (auto& innerVec : tagEffBkgnd_hist_B0bar_){ - innerVec.push_back(nullptr); + innerVec.push_back({nullptr,nullptr,nullptr}); } } else { //Loop over the outer vector and extend the inner vectors for (auto& innerVec : tagEffBkgnd_ave_){ - innerVec.push_back(nullptr); + innerVec.push_back({nullptr,nullptr,nullptr}); } for (auto& innerVec : tagEffBkgnd_hist_ave_){ - innerVec.push_back(nullptr); + innerVec.push_back({nullptr,nullptr,nullptr}); } for (auto& innerVec : tagEffBkgnd_delta_){ - innerVec.push_back(nullptr); + innerVec.push_back({nullptr,nullptr,nullptr}); } for (auto& innerVec : tagEffBkgnd_hist_delta_){ - innerVec.push_back(nullptr); + innerVec.push_back({nullptr,nullptr,nullptr}); } } for (auto& innerVec : etaBkgndPdfs_){ - innerVec.push_back(nullptr); + innerVec.push_back({nullptr,nullptr,nullptr}); } for (auto& innerVec : avgMistagBkgnd_){ - innerVec.push_back(0); + innerVec.push_back({0.0,0.0,0.0}); } } } -void LauFlavTag::setupCalibParams(const TString& name, const ULong_t position, const std::pair calib_p0, const std::pair calib_p1) +void LauFlavTag::setupCalibParams(const TString& taggerName, const std::pair calib_p0, const std::pair calib_p1) { + const std::size_t taggerID { taggerIndex_.at( taggerName ) }; + if (!useAveDelta_){ - TString calib_p0_b0Name("calib_p0_b0_"+name); - TString calib_p0_b0barName("calib_p0_b0bar_"+name); - TString calib_p1_b0Name("calib_p1_b0_"+name); - TString calib_p1_b0barName("calib_p1_b0bar_"+name); + TString calib_p0_b0Name("calib_p0_b0_"+taggerName); + TString calib_p0_b0barName("calib_p0_b0bar_"+taggerName); + TString calib_p1_b0Name("calib_p1_b0_"+taggerName); + TString calib_p1_b0barName("calib_p1_b0bar_"+taggerName); LauParameter* calibp0b0 = new LauParameter(calib_p0_b0Name,calib_p0.first,-10.0,10.0,kTRUE); calib_p0_B0_.push_back(calibp0b0); - calib_p0_B0_[position]->initValue(calib_p0.first); calib_p0_B0_[position]->genValue(calib_p0.first); - calib_p0_B0_[position]->fixed(kTRUE); + calib_p0_B0_[taggerID]->initValue(calib_p0.first); calib_p0_B0_[taggerID]->genValue(calib_p0.first); + calib_p0_B0_[taggerID]->fixed(kTRUE); LauParameter* calibp1b0 = new LauParameter(calib_p1_b0Name,calib_p1.first,0.0,1.5,kTRUE); calib_p1_B0_.push_back(calibp1b0); - calib_p1_B0_[position]->initValue(calib_p1.first); calib_p1_B0_[position]->genValue(calib_p1.first); - calib_p1_B0_[position]->fixed(kTRUE); + calib_p1_B0_[taggerID]->initValue(calib_p1.first); calib_p1_B0_[taggerID]->genValue(calib_p1.first); + calib_p1_B0_[taggerID]->fixed(kTRUE); if (calib_p0.second==-1.0 && calib_p1.second==-1.0){ - calib_p0_B0bar_.push_back(calib_p0_B0_[position]->createClone(calib_p0_b0barName)); - calib_p1_B0bar_.push_back(calib_p1_B0_[position]->createClone(calib_p1_b0barName)); + calib_p0_B0bar_.push_back(calib_p0_B0_[taggerID]->createClone(calib_p0_b0barName)); + calib_p1_B0bar_.push_back(calib_p1_B0_[taggerID]->createClone(calib_p1_b0barName)); } else { LauParameter* calibp0b0bar = new LauParameter(calib_p0_b0barName,calib_p0.second,-10.0,10.0,kTRUE); calib_p0_B0bar_.push_back(calibp0b0bar); - calib_p0_B0bar_[position]->initValue(calib_p0.second); calib_p0_B0bar_[position]->genValue(calib_p0.second); - calib_p0_B0bar_[position]->fixed(kTRUE); + calib_p0_B0bar_[taggerID]->initValue(calib_p0.second); calib_p0_B0bar_[taggerID]->genValue(calib_p0.second); + calib_p0_B0bar_[taggerID]->fixed(kTRUE); LauParameter* calibp1b0bar = new LauParameter(calib_p1_b0barName,calib_p1.second,0.0,1.5,kTRUE); calib_p1_B0bar_.push_back(calibp1b0bar); - calib_p1_B0bar_[position]->initValue(calib_p1.second); calib_p1_B0bar_[position]->genValue(calib_p1.second); - calib_p1_B0bar_[position]->fixed(kTRUE); + calib_p1_B0bar_[taggerID]->initValue(calib_p1.second); calib_p1_B0bar_[taggerID]->genValue(calib_p1.second); + calib_p1_B0bar_[taggerID]->fixed(kTRUE); } } else { //Use average and delta variables - TString calib_p0_aveName("calib_p0_ave_"+name); - TString calib_p0_deltaName("calib_p0_delta_"+name); - TString calib_p1_aveName("calib_p1_ave_"+name); - TString calib_p1_deltaName("calib_p1_delta_"+name); + TString calib_p0_aveName("calib_p0_ave_"+taggerName); + TString calib_p0_deltaName("calib_p0_delta_"+taggerName); + TString calib_p1_aveName("calib_p1_ave_"+taggerName); + TString calib_p1_deltaName("calib_p1_delta_"+taggerName); LauParameter* calibp0ave = new LauParameter(calib_p0_aveName,calib_p0.first,-10.0,10.0,kTRUE); calib_p0_ave_.push_back(calibp0ave); - calib_p0_ave_[position]->initValue(calib_p0.first); calib_p0_ave_[position]->genValue(calib_p0.first); - calib_p0_ave_[position]->fixed(kTRUE); + calib_p0_ave_[taggerID]->initValue(calib_p0.first); calib_p0_ave_[taggerID]->genValue(calib_p0.first); + calib_p0_ave_[taggerID]->fixed(kTRUE); LauParameter* calibp1ave = new LauParameter(calib_p1_aveName,calib_p1.first,0.0,1.5,kTRUE); calib_p1_ave_.push_back(calibp1ave); - calib_p1_ave_[position]->initValue(calib_p1.first); calib_p1_ave_[position]->genValue(calib_p1.first); - calib_p1_ave_[position]->fixed(kTRUE); + calib_p1_ave_[taggerID]->initValue(calib_p1.first); calib_p1_ave_[taggerID]->genValue(calib_p1.first); + calib_p1_ave_[taggerID]->fixed(kTRUE); LauParameter* calibp0delta = new LauParameter(calib_p0_deltaName,calib_p0.second,-10.0,10.0,kTRUE); calib_p0_delta_.push_back(calibp0delta); - calib_p0_delta_[position]->initValue(calib_p0.second); calib_p0_delta_[position]->genValue(calib_p0.second); - calib_p0_delta_[position]->fixed(kTRUE); + calib_p0_delta_[taggerID]->initValue(calib_p0.second); calib_p0_delta_[taggerID]->genValue(calib_p0.second); + calib_p0_delta_[taggerID]->fixed(kTRUE); LauParameter* calibp1delta = new LauParameter(calib_p1_deltaName,calib_p1.second,-10.0,10.0,kTRUE); calib_p1_delta_.push_back(calibp1delta); - calib_p1_delta_[position]->initValue(calib_p1.second); calib_p1_delta_[position]->genValue(calib_p1.second); - calib_p1_delta_[position]->fixed(kTRUE); + calib_p1_delta_[taggerID]->initValue(calib_p1.second); calib_p1_delta_[taggerID]->genValue(calib_p1.second); + calib_p1_delta_[taggerID]->fixed(kTRUE); } } void LauFlavTag::cacheInputFitVars(LauFitDataTree* inputFitData, const TString& decayTimeVarName) { evtTagFlv_.clear(); evtMistag_.clear(); evtTrueTagFlv_.clear(); evtDecayFlv_.clear(); evtDecayTime_.clear(); // Loop over the taggers to check the branches - for (ULong_t i=0; i < tagVarNames_.size(); ++i){ + for (std::size_t i=0; i < tagVarNames_.size(); ++i){ if ( not inputFitData->haveBranch( tagVarNames_[i] ) ) { std::cerr << "ERROR in LauFlavTag::cacheInputFitVars : Input data does not contain branch \"" << tagVarNames_[i] << "\"." << std::endl; gSystem->Exit(EXIT_FAILURE); } if ( not inputFitData->haveBranch( mistagVarNames_[i] ) ) { std::cerr << "ERROR in LauFlavTag::cacheInputFitVars : Input data does not contain branch \"" << mistagVarNames_[i] << "\"." << std::endl; gSystem->Exit(EXIT_FAILURE); } } if ( trueTagVarName_ != "" and not inputFitData->haveBranch( trueTagVarName_ ) ) { std::cerr << "ERROR in LauFlavTag::cacheInputFitVars : Input data does not contain branch \"" << trueTagVarName_ << "\"." << std::endl; gSystem->Exit(EXIT_FAILURE); } if ( decayFlvVarName_ != "" and not inputFitData->haveBranch( decayFlvVarName_ ) ) { std::cerr << "ERROR in LauFlavTag::cacheInputFitVars : Input data does not contain branch \"" << decayFlvVarName_ << "\"." << std::endl; gSystem->Exit(EXIT_FAILURE); } if ( decayTimeVarName != "" and not inputFitData->haveBranch( decayTimeVarName ) ) { std::cerr << "ERROR in LauFlavTag::cacheInputFitVars : Input data does not contain branch \"" << decayTimeVarName << "\"." << std::endl; gSystem->Exit(EXIT_FAILURE); } - const ULong_t nEvents { inputFitData->nEvents() }; + const std::size_t nEvents { inputFitData->nEvents() }; evtTagFlv_.reserve( nEvents ); evtMistag_.reserve( nEvents ); evtTrueTagFlv_.reserve( nEvents ); evtDecayFlv_.reserve( nEvents ); evtDecayTime_.reserve( nEvents ); LauFitData::const_iterator fitdata_iter; - for (ULong_t iEvt = 0; iEvt < nEvents; iEvt++) { + for (std::size_t iEvt = 0; iEvt < nEvents; iEvt++) { const LauFitData& dataValues = inputFitData->getData(iEvt); // For untagged events see if we have a truth tag for normalisation modes Int_t curEvtTrueTagFlv { ( trueTagVarName_ != "" ) ? static_cast( dataValues.at( trueTagVarName_ ) ) : 0 }; if ( curEvtTrueTagFlv > 1 ) { std::cerr << "WARNING in LauFlavTag::cacheInputFitVars : Invalid true tag value " << curEvtTrueTagFlv << " for event " << iEvt << ", setting it to +1" << std::endl; curEvtTrueTagFlv = +1; } else if ( curEvtTrueTagFlv < -1 ){ std::cerr << "WARNING in LauFlavTag::cacheInputFitVars : Invalid true tag value " << curEvtTrueTagFlv << " for event " << iEvt << ", setting it to -1" << std::endl; curEvtTrueTagFlv = -1; } curEvtTrueTagFlv_ = static_cast(curEvtTrueTagFlv); evtTrueTagFlv_.push_back(curEvtTrueTagFlv_); // Flavour at decay // TODO put this in a try catch block current error message is unhelpful if this throws Int_t curEvtDecayFlv { ( decayFlvVarName_ != "" ) ? static_cast( dataValues.at( decayFlvVarName_ ) ) : 0 }; if ( curEvtDecayFlv > 1 ) { std::cerr << "WARNING in LauFlavTag::cacheInputFitVars : Invalid decay flavour value " << curEvtDecayFlv << " for event " << iEvt << ", setting it to +1" << std::endl; curEvtDecayFlv = +1; } else if ( curEvtDecayFlv < -1 ){ std::cerr << "WARNING in LauFlavTag::cacheInputFitVars : Invalid decay flavour value " << curEvtDecayFlv << " for event " << iEvt << ", setting it to -1" << std::endl; curEvtDecayFlv = -1; } curEvtDecayFlv_ = static_cast(curEvtDecayFlv); evtDecayFlv_.push_back(curEvtDecayFlv_); - for (ULong_t i=0; i < tagVarNames_.size(); ++i){ + for (std::size_t i=0; i < tagVarNames_.size(); ++i){ Int_t curEvtTagFlv { static_cast( dataValues.at( tagVarNames_[i] ) ) }; if ( curEvtTagFlv > 1 ) { std::cerr << "WARNING in LauFlavTag::cacheInputFitVars : Invalid tagging output " << curEvtTagFlv << " for event " << iEvt << ", setting it to +1" << std::endl; curEvtTagFlv = +1; } else if ( curEvtTagFlv < -1 ) { std::cerr << "WARNING in LauFlavTag::cacheInputFitVars : Invalid tagging output " << curEvtTagFlv << " for event " << iEvt << ", setting it to -1" << std::endl; curEvtTagFlv = -1; } curEvtTagFlv_[i] = static_cast( curEvtTagFlv ); curEvtMistag_[i] = static_cast( dataValues.at( mistagVarNames_[i] ) ); // Calibrated mistag > 0.5 is just a tag flip - handled automatically in getCapitalOmega function if (curEvtMistag_[i] > 0.5){ std::cerr<<"WARNING in LauFlavTag::cacheInputFitVars : Mistag value "<( dataValues.at( decayTimeVarName ) ); evtDecayTime_.push_back(curEvtDecayTime_); } } -void LauFlavTag::updateEventInfo(const ULong_t iEvt) +void LauFlavTag::updateEventInfo(const std::size_t iEvt) { //Assign current event variables curEvtTagFlv_ = evtTagFlv_[iEvt]; curEvtMistag_ = evtMistag_[iEvt]; curEvtTrueTagFlv_ = evtTrueTagFlv_[iEvt]; curEvtDecayFlv_ = evtDecayFlv_[iEvt]; curEvtDecayTime_ = evtDecayTime_[iEvt]; } void LauFlavTag::generateEventInfo(const Flavour trueTagFlv, const Double_t curEvtDecayTime) { curEvtTrueTagFlv_ = trueTagFlv; curEvtDecayFlv_ = Flavour::Unknown; curEvtDecayTime_ = curEvtDecayTime; Double_t randNo{0.0}; Double_t tagEffB0{0.0}; Double_t tagEffB0bar{0.0}; - const ULong_t nTaggers { this->getNTaggers() }; - for ( ULong_t position{0}; positiongetNTaggers() }; + for ( std::size_t taggerID{0}; taggerIDgetEtaGen(position); + this->getEtaGen(taggerID); if (this->getUseAveDelta()) { - if (tagEff_ave_[position]==nullptr){ - const Double_t ave = tagEff_hist_ave_[position]->GetBinContent(tagEff_hist_ave_[position]->FindFixBin(curEvtDecayTime_)); - const Double_t delta = tagEff_hist_delta_[position]->GetBinContent(tagEff_hist_delta_[position]->FindFixBin(curEvtDecayTime_)); + if (tagEff_ave_[taggerID]==nullptr){ + const Double_t ave = tagEff_hist_ave_[taggerID]->GetBinContent(tagEff_hist_ave_[taggerID]->FindFixBin(curEvtDecayTime_)); + const Double_t delta = tagEff_hist_delta_[taggerID]->GetBinContent(tagEff_hist_delta_[taggerID]->FindFixBin(curEvtDecayTime_)); tagEffB0 = ave + 0.5 * delta; tagEffB0bar = ave - 0.5 * delta; } else { - tagEffB0 = tagEff_ave_[position]->unblindValue() + 0.5 * tagEff_delta_[position]->unblindValue(); - tagEffB0bar = tagEff_ave_[position]->unblindValue() - 0.5 * tagEff_delta_[position]->unblindValue(); + tagEffB0 = tagEff_ave_[taggerID]->unblindValue() + 0.5 * tagEff_delta_[taggerID]->unblindValue(); + tagEffB0bar = tagEff_ave_[taggerID]->unblindValue() - 0.5 * tagEff_delta_[taggerID]->unblindValue(); } } else { - if (tagEff_B0_[position]==nullptr){ - tagEffB0 = tagEff_hist_B0_[position]->GetBinContent(tagEff_hist_B0_[position]->FindFixBin(curEvtDecayTime_)); - tagEffB0bar = tagEff_hist_B0bar_[position]->GetBinContent(tagEff_hist_B0bar_[position]->FindFixBin(curEvtDecayTime_)); + if (tagEff_B0_[taggerID]==nullptr){ + tagEffB0 = tagEff_hist_B0_[taggerID]->GetBinContent(tagEff_hist_B0_[taggerID]->FindFixBin(curEvtDecayTime_)); + tagEffB0bar = tagEff_hist_B0bar_[taggerID]->GetBinContent(tagEff_hist_B0bar_[taggerID]->FindFixBin(curEvtDecayTime_)); } else { - tagEffB0 = tagEff_B0_[position]->unblindValue(); - tagEffB0bar = tagEff_B0bar_[position]->unblindValue(); + tagEffB0 = tagEff_B0_[taggerID]->unblindValue(); + tagEffB0bar = tagEff_B0bar_[taggerID]->unblindValue(); } } if (curEvtTrueTagFlv_ == Flavour::B) { randNo = LauRandom::randomFun()->Rndm(); // Try to tag in tageff% of cases if (randNo <= tagEffB0) { randNo = LauRandom::randomFun()->Rndm(); // Account for (calibrated) mistag - if (randNo > this->getLittleOmega(position, Flavour::B)){ - curEvtTagFlv_[position] = Flavour::B; + if (randNo > this->getLittleOmega(taggerID, Flavour::B)){ + curEvtTagFlv_[taggerID] = Flavour::B; } else { - curEvtTagFlv_[position] = Flavour::Bbar; + curEvtTagFlv_[taggerID] = Flavour::Bbar; } } else { - curEvtTagFlv_[position] = Flavour::Unknown; + curEvtTagFlv_[taggerID] = Flavour::Unknown; } } else if (curEvtTrueTagFlv_ == Flavour::Bbar) { randNo = LauRandom::randomFun()->Rndm(); // Try to tag in tageff% of cases if (randNo <= tagEffB0bar) { randNo = LauRandom::randomFun()->Rndm(); // Account for (calibrated) mistag - if (randNo > this->getLittleOmega(position, Flavour::Bbar)){ - curEvtTagFlv_[position] = Flavour::Bbar; + if (randNo > this->getLittleOmega(taggerID, Flavour::Bbar)){ + curEvtTagFlv_[taggerID] = Flavour::Bbar; } else { - curEvtTagFlv_[position] = Flavour::B; + curEvtTagFlv_[taggerID] = Flavour::B; } } else { - curEvtTagFlv_[position] = Flavour::Unknown; + curEvtTagFlv_[taggerID] = Flavour::Unknown; } } else { std::cerr << "ERROR in LauFlavTag::generateEventInfo : Invalid true tag flavour, should be either B (+1) or Bbar (-1)" << std::endl; gSystem->Exit(EXIT_FAILURE); } } } -void LauFlavTag::generateBkgndEventInfo(const ULong_t bkgndID, const Flavour trueTagFlv, const Double_t curEvtDecayTime) +void LauFlavTag::generateBkgndEventInfo(const std::size_t bkgndID, const Flavour trueTagFlv, const Flavour trueDecayFlv, const Double_t curEvtDecayTime) { - if (bkgndID > bkgndNames_.size()){ + if (bkgndID > bkgndIndex_.size()){ std::cerr << "ERROR in LauFlavTag::generateBkgndEventInfo : Invalid backgrond class identifier" << std::endl; gSystem->Exit(EXIT_FAILURE); } curEvtTrueTagFlv_ = trueTagFlv; - curEvtDecayFlv_ = Flavour::Unknown; + curEvtDecayFlv_ = trueDecayFlv; curEvtDecayTime_ = curEvtDecayTime; Double_t randNo{0.0}; Double_t tagEffB0{0.0}; Double_t tagEffB0bar{0.0}; - const ULong_t nTaggers { this->getNTaggers() }; - for ( ULong_t position{0}; positiongetNTaggers() }; + for ( std::size_t taggerID{0}; taggerIDgetEtaGenBkgnd(position,bkgndID); + const std::size_t arrayIndex { static_cast( bkgndDecayFlvDep_[bkgndID] * curEvtDecayFlv_ + 1 ) }; - //TODO If bkgnd is signal like should these parameters be clones of signal TagEff etc? - //TODO Or call generateEventInfo() instead? + this->getEtaGenBkgnd(taggerID,bkgndID,curEvtDecayFlv_); + + // TODO - need to allow at least for combinatorial background, perhaps in general, for the tagging efficiency and/or calibration parameters to depend on the decay flavour + // - do we want this for signal too? if (this->getUseAveDelta()) { - if (tagEffBkgnd_ave_[bkgndID][position]==nullptr){ - const Double_t ave = tagEffBkgnd_hist_ave_[bkgndID][position]->GetBinContent(tagEffBkgnd_hist_ave_[bkgndID][position]->FindFixBin(curEvtDecayTime_)); - const Double_t delta = tagEffBkgnd_hist_delta_[bkgndID][position]->GetBinContent(tagEffBkgnd_hist_delta_[bkgndID][position]->FindFixBin(curEvtDecayTime_)); + if (tagEffBkgnd_ave_[bkgndID][taggerID][arrayIndex]==nullptr){ + const Double_t ave = tagEffBkgnd_hist_ave_[bkgndID][taggerID][arrayIndex]->GetBinContent(tagEffBkgnd_hist_ave_[bkgndID][taggerID][arrayIndex]->FindFixBin(curEvtDecayTime_)); + const Double_t delta = tagEffBkgnd_hist_delta_[bkgndID][taggerID][arrayIndex]->GetBinContent(tagEffBkgnd_hist_delta_[bkgndID][taggerID][arrayIndex]->FindFixBin(curEvtDecayTime_)); tagEffB0 = ave + 0.5 * delta; tagEffB0bar = ave - 0.5 * delta; } else { - tagEffB0 = tagEffBkgnd_ave_[bkgndID][position]->unblindValue() + 0.5 * tagEffBkgnd_delta_[bkgndID][position]->unblindValue(); - tagEffB0bar = tagEffBkgnd_ave_[bkgndID][position]->unblindValue() - 0.5 * tagEffBkgnd_delta_[bkgndID][position]->unblindValue(); + tagEffB0 = tagEffBkgnd_ave_[bkgndID][taggerID][arrayIndex]->unblindValue() + 0.5 * tagEffBkgnd_delta_[bkgndID][taggerID][arrayIndex]->unblindValue(); + tagEffB0bar = tagEffBkgnd_ave_[bkgndID][taggerID][arrayIndex]->unblindValue() - 0.5 * tagEffBkgnd_delta_[bkgndID][taggerID][arrayIndex]->unblindValue(); } } else { - if (tagEffBkgnd_B0_[bkgndID][position]==nullptr){ - tagEffB0 = tagEffBkgnd_hist_B0_[bkgndID][position]->GetBinContent(tagEffBkgnd_hist_B0_[bkgndID][position]->FindFixBin(curEvtDecayTime_)); - tagEffB0bar = tagEffBkgnd_hist_B0bar_[bkgndID][position]->GetBinContent(tagEffBkgnd_hist_B0bar_[bkgndID][position]->FindFixBin(curEvtDecayTime_)); + if (tagEffBkgnd_B0_[bkgndID][taggerID][arrayIndex]==nullptr){ + tagEffB0 = tagEffBkgnd_hist_B0_[bkgndID][taggerID][arrayIndex]->GetBinContent(tagEffBkgnd_hist_B0_[bkgndID][taggerID][arrayIndex]->FindFixBin(curEvtDecayTime_)); + tagEffB0bar = tagEffBkgnd_hist_B0bar_[bkgndID][taggerID][arrayIndex]->GetBinContent(tagEffBkgnd_hist_B0bar_[bkgndID][taggerID][arrayIndex]->FindFixBin(curEvtDecayTime_)); } else { - tagEffB0 = tagEffBkgnd_B0_[bkgndID][position]->unblindValue(); - tagEffB0bar = tagEffBkgnd_B0bar_[bkgndID][position]->unblindValue(); + tagEffB0 = tagEffBkgnd_B0_[bkgndID][taggerID][arrayIndex]->unblindValue(); + tagEffB0bar = tagEffBkgnd_B0bar_[bkgndID][taggerID][arrayIndex]->unblindValue(); } } if (bkgndTypes_[bkgndID] == BkgndType::Combinatorial){ randNo = LauRandom::randomFun()->Rndm(); if (randNo<=tagEffB0){ - curEvtTagFlv_[position] = Flavour::B; + curEvtTagFlv_[taggerID] = Flavour::B; } else if(randNo<=(tagEffB0+tagEffB0bar)){ - curEvtTagFlv_[position] = Flavour::Bbar; + curEvtTagFlv_[taggerID] = Flavour::Bbar; } else { - curEvtTagFlv_[position] = Flavour::Unknown; + curEvtTagFlv_[taggerID] = Flavour::Unknown; } }else{ if (curEvtTrueTagFlv_ == Flavour::B) { randNo = LauRandom::randomFun()->Rndm(); // Try to tag in tageff% of cases if (randNo <= tagEffB0) { randNo = LauRandom::randomFun()->Rndm(); // Account for (calibrated) mistag - if (randNo > this->getLittleOmegaBkgnd(position, Flavour::B, bkgndID)){ - curEvtTagFlv_[position] = Flavour::B; + if (randNo > this->getLittleOmegaBkgnd(bkgndID, taggerID, Flavour::B, curEvtDecayFlv_)){ + curEvtTagFlv_[taggerID] = Flavour::B; } else { - curEvtTagFlv_[position] = Flavour::Bbar; + curEvtTagFlv_[taggerID] = Flavour::Bbar; } } else { - curEvtTagFlv_[position] = Flavour::Unknown; + curEvtTagFlv_[taggerID] = Flavour::Unknown; } } else if (curEvtTrueTagFlv_ == Flavour::Bbar) { randNo = LauRandom::randomFun()->Rndm(); // Try to tag in tageff% of cases if (randNo <= tagEffB0bar) { randNo = LauRandom::randomFun()->Rndm(); // Account for (calibrated) mistag - if (randNo > this->getLittleOmegaBkgnd(position, Flavour::Bbar, bkgndID)){ - curEvtTagFlv_[position] = Flavour::Bbar; + if (randNo > this->getLittleOmegaBkgnd(bkgndID, taggerID, Flavour::Bbar, curEvtDecayFlv_)){ + curEvtTagFlv_[taggerID] = Flavour::Bbar; } else { - curEvtTagFlv_[position] = Flavour::B; + curEvtTagFlv_[taggerID] = Flavour::B; } } else { - curEvtTagFlv_[position] = Flavour::Unknown; + curEvtTagFlv_[taggerID] = Flavour::Unknown; } } else { std::cerr << "ERROR in LauFlavTag::generateBkgndEventInfo : Invalid true tag flavour, should be either B (+1) or Bbar (-1)" << std::endl; gSystem->Exit(EXIT_FAILURE); } } } } -Double_t LauFlavTag::getLittleOmega(const ULong_t position, const Flavour flag) const +Double_t LauFlavTag::getLittleOmega(const std::size_t taggerID, const Flavour flag) const { if ( flag == Flavour::Unknown ){ std::cerr << "ERROR in LauFlavTag::getLittleOmega : Invalid flag, you must request either omega (+1) or omega bar (-1) to be returned" << std::endl; return 0.0; } Double_t calibp0(0.), calibp1(0.), calibp0bar(0.), calibp1bar(0.); //If we are floating average omega and delta omega we need to use those parameters instead if (useAveDelta_){ - calibp0 = calib_p0_ave_[position]->unblindValue() + 0.5*calib_p0_delta_[position]->unblindValue(); - calibp0bar = calib_p0_ave_[position]->unblindValue() - 0.5*calib_p0_delta_[position]->unblindValue(); - calibp1 = calib_p1_ave_[position]->unblindValue() + 0.5*calib_p1_delta_[position]->unblindValue(); - calibp1bar = calib_p1_ave_[position]->unblindValue() - 0.5*calib_p1_delta_[position]->unblindValue(); + calibp0 = calib_p0_ave_[taggerID]->unblindValue() + 0.5*calib_p0_delta_[taggerID]->unblindValue(); + calibp0bar = calib_p0_ave_[taggerID]->unblindValue() - 0.5*calib_p0_delta_[taggerID]->unblindValue(); + calibp1 = calib_p1_ave_[taggerID]->unblindValue() + 0.5*calib_p1_delta_[taggerID]->unblindValue(); + calibp1bar = calib_p1_ave_[taggerID]->unblindValue() - 0.5*calib_p1_delta_[taggerID]->unblindValue(); } else { - calibp0 = calib_p0_B0_[position]->unblindValue(); - calibp0bar = calib_p0_B0bar_[position]->unblindValue(); - calibp1 = calib_p1_B0_[position]->unblindValue(); - calibp1bar = calib_p1_B0bar_[position]->unblindValue(); + calibp0 = calib_p0_B0_[taggerID]->unblindValue(); + calibp0bar = calib_p0_B0bar_[taggerID]->unblindValue(); + calibp1 = calib_p1_B0_[taggerID]->unblindValue(); + calibp1bar = calib_p1_B0bar_[taggerID]->unblindValue(); } if ( flag == Flavour::B ){ - return calibp0 + calibp1 * (curEvtMistag_[position] - perEvtAvgMistag_[position]); + return calibp0 + calibp1 * (curEvtMistag_[taggerID] - perEvtAvgMistag_[taggerID]); } else{ - return calibp0bar + calibp1bar * (curEvtMistag_[position] - perEvtAvgMistag_[position]); + return calibp0bar + calibp1bar * (curEvtMistag_[taggerID] - perEvtAvgMistag_[taggerID]); } return 0.0; } -Double_t LauFlavTag::getCapitalOmega(const ULong_t position, const Flavour flag) const +Double_t LauFlavTag::getCapitalOmega(const std::size_t taggerID, const Flavour flag) const { if ( flag == Flavour::Unknown ){ std::cerr << "ERROR in LauFlavTag::getCapitalOmega : Invalid flag, you must request either Omega (+1) or Omega bar (-1) to be returned" << std::endl; return 0.0; } //Delta functions to control which terms contribute Int_t deltap1(0), deltam1(0), delta0(0); - if (curEvtTagFlv_[position] == Flavour::Bbar){ + if (curEvtTagFlv_[taggerID] == Flavour::Bbar){ deltam1 = 1; - } else if(curEvtTagFlv_[position] == Flavour::B){ + } else if(curEvtTagFlv_[taggerID] == Flavour::B){ deltap1 = 1; } else{ delta0 = 1; } //Efficiency Double_t eff(0.0); if (useAveDelta_){ if(flag==Flavour::B){ - if (tagEff_ave_[position]==nullptr){ - eff = tagEff_hist_ave_[position]->GetBinContent(tagEff_hist_ave_[position]->FindFixBin(curEvtDecayTime_)) + 0.5*tagEff_hist_delta_[position]->GetBinContent(tagEff_hist_delta_[position]->FindFixBin(curEvtDecayTime_)); + if (tagEff_ave_[taggerID]==nullptr){ + eff = tagEff_hist_ave_[taggerID]->GetBinContent(tagEff_hist_ave_[taggerID]->FindFixBin(curEvtDecayTime_)) + 0.5*tagEff_hist_delta_[taggerID]->GetBinContent(tagEff_hist_delta_[taggerID]->FindFixBin(curEvtDecayTime_)); } else { - eff = tagEff_ave_[position]->unblindValue() + 0.5*tagEff_delta_[position]->unblindValue(); + eff = tagEff_ave_[taggerID]->unblindValue() + 0.5*tagEff_delta_[taggerID]->unblindValue(); } } else { - if (tagEff_ave_[position]==nullptr){ - eff = tagEff_hist_ave_[position]->GetBinContent(tagEff_hist_ave_[position]->FindFixBin(curEvtDecayTime_)) - 0.5*tagEff_hist_delta_[position]->GetBinContent(tagEff_hist_delta_[position]->FindFixBin(curEvtDecayTime_)); + if (tagEff_ave_[taggerID]==nullptr){ + eff = tagEff_hist_ave_[taggerID]->GetBinContent(tagEff_hist_ave_[taggerID]->FindFixBin(curEvtDecayTime_)) - 0.5*tagEff_hist_delta_[taggerID]->GetBinContent(tagEff_hist_delta_[taggerID]->FindFixBin(curEvtDecayTime_)); } else { - eff = tagEff_ave_[position]->unblindValue() - 0.5*tagEff_delta_[position]->unblindValue(); + eff = tagEff_ave_[taggerID]->unblindValue() - 0.5*tagEff_delta_[taggerID]->unblindValue(); } } }else{ if(flag==Flavour::B){ - if (tagEff_B0_[position]==nullptr){ - eff = tagEff_hist_B0_[position]->GetBinContent(tagEff_hist_B0_[position]->FindFixBin(curEvtDecayTime_)); + if (tagEff_B0_[taggerID]==nullptr){ + eff = tagEff_hist_B0_[taggerID]->GetBinContent(tagEff_hist_B0_[taggerID]->FindFixBin(curEvtDecayTime_)); } else { - eff = tagEff_B0_[position]->unblindValue(); + eff = tagEff_B0_[taggerID]->unblindValue(); } }else{ - if (tagEff_B0bar_[position]==nullptr){ - eff = tagEff_hist_B0bar_[position]->GetBinContent(tagEff_hist_B0bar_[position]->FindFixBin(curEvtDecayTime_)); + if (tagEff_B0bar_[taggerID]==nullptr){ + eff = tagEff_hist_B0bar_[taggerID]->GetBinContent(tagEff_hist_B0bar_[taggerID]->FindFixBin(curEvtDecayTime_)); } else { - eff = tagEff_B0bar_[position]->unblindValue(); + eff = tagEff_B0bar_[taggerID]->unblindValue(); } } } //Little omega - Double_t omega = this->getLittleOmega(position, flag); + Double_t omega = this->getLittleOmega(taggerID, flag); Double_t omegaPrime(0.); //Transform to omega prime - TODO isn't this the inverse, getLittleOmega is actually giving us omegaPrime and on the next line we convert back to omega? if (useEtaPrime_){ omegaPrime = (1/(1+TMath::Exp(-1.0*omega))); }else{ omegaPrime = omega; } //little omega must be between 0 and 1. Force this for now, if the fits keep getting stuck can look more closely at it. static Bool_t tooSmallWarningIssued {kFALSE}; static Bool_t tooLargeWarningIssued {kFALSE}; if (omegaPrime < 0.0){ if ( not tooSmallWarningIssued ) { std::cerr << "WARNING in LauFlavTag::getCapitalOmega : The value of little omega is less than 0, shifting to 0\n"; std::cerr << " : Further WARNINGs of this type will be suppressed" << std::endl; tooSmallWarningIssued = kTRUE; } omegaPrime = 0.0; } if (omegaPrime > 1.0){ if ( not tooLargeWarningIssued ) { std::cerr << "WARNING in LauFlavTag::getCapitalOmega : The value of little omega is greater than 1, shifting to 1\n"; std::cerr << " : Further WARNINGs of this type will be suppressed" << std::endl; tooLargeWarningIssued = kTRUE; } omegaPrime = 1.0; } //eta PDF value std::vector abs; - abs.push_back(curEvtMistag_[position]); - etaPdfs_[position]->calcLikelihoodInfo(abs); - Double_t h { etaPdfs_[position]->getLikelihood() }; + abs.push_back(curEvtMistag_[taggerID]); + etaPdfs_[taggerID]->calcLikelihoodInfo(abs); + Double_t h { etaPdfs_[taggerID]->getLikelihood() }; const Double_t u { 2.0 }; // the PDF value for a uniform PDF between 0.0 and 0.5 //If h returns 0 for a tagged event, the event likelihood will be zero if (h==0 && delta0==0){ - std::cerr << "WARNING in LauFlavTag::getCapitalOmega : The value of the eta PDF is zero at eta = " << curEvtMistag_[position] << ", shifting to 0.1" << std::endl; + std::cerr << "WARNING in LauFlavTag::getCapitalOmega : The value of the eta PDF is zero at eta = " << curEvtMistag_[taggerID] << ", shifting to 0.1" << std::endl; h=0.1; } //Put it together if (flag == Flavour::B){ return (deltap1*eff*(1-omegaPrime) + deltam1*eff*omegaPrime)*h + delta0*(1-eff)*u; } else { return (deltam1*eff*(1-omegaPrime) + deltap1*eff*omegaPrime)*h + delta0*(1-eff)*u; } } -Double_t LauFlavTag::getLittleOmegaBkgnd(const ULong_t position, const Flavour flag, const UInt_t classID) const +Double_t LauFlavTag::getLittleOmegaBkgnd(const std::size_t bkgndID, const std::size_t taggerID, const Flavour flag, const Flavour decayFlv) const { if ( flag == Flavour::Unknown ){ std::cerr << "ERROR in LauFlavTag::getLittleOmegaBkgnd : Invalid flag, you must request either omega (+1) or omega bar (-1) to be returned" << std::endl; return 0.0; } Double_t calibp0(0.), calibp1(0.), calibp0bar(0.), calibp1bar(0.); //If we are floating average omega and delta omega we need to use those parameters instead if (useAveDelta_){ - calibp0 = calib_p0_ave_[position]->unblindValue() + 0.5*calib_p0_delta_[position]->unblindValue(); - calibp0bar = calib_p0_ave_[position]->unblindValue() - 0.5*calib_p0_delta_[position]->unblindValue(); - calibp1 = calib_p1_ave_[position]->unblindValue() + 0.5*calib_p1_delta_[position]->unblindValue(); - calibp1bar = calib_p1_ave_[position]->unblindValue() - 0.5*calib_p1_delta_[position]->unblindValue(); + calibp0 = calib_p0_ave_[taggerID]->unblindValue() + 0.5*calib_p0_delta_[taggerID]->unblindValue(); + calibp0bar = calib_p0_ave_[taggerID]->unblindValue() - 0.5*calib_p0_delta_[taggerID]->unblindValue(); + calibp1 = calib_p1_ave_[taggerID]->unblindValue() + 0.5*calib_p1_delta_[taggerID]->unblindValue(); + calibp1bar = calib_p1_ave_[taggerID]->unblindValue() - 0.5*calib_p1_delta_[taggerID]->unblindValue(); } else { - calibp0 = calib_p0_B0_[position]->unblindValue(); - calibp0bar = calib_p0_B0bar_[position]->unblindValue(); - calibp1 = calib_p1_B0_[position]->unblindValue(); - calibp1bar = calib_p1_B0bar_[position]->unblindValue(); + calibp0 = calib_p0_B0_[taggerID]->unblindValue(); + calibp0bar = calib_p0_B0bar_[taggerID]->unblindValue(); + calibp1 = calib_p1_B0_[taggerID]->unblindValue(); + calibp1bar = calib_p1_B0bar_[taggerID]->unblindValue(); } + const std::size_t arrayIndex { static_cast( bkgndDecayFlvDep_[bkgndID] * decayFlv + 1 ) }; if ( flag == Flavour::B ){ - return calibp0 + calibp1 * (curEvtMistag_[position] - avgMistagBkgnd_[classID][position]); + return calibp0 + calibp1 * (curEvtMistag_[taggerID] - avgMistagBkgnd_[bkgndID][taggerID][arrayIndex]); } else{ - return calibp0bar + calibp1bar * (curEvtMistag_[position] - avgMistagBkgnd_[classID][position]); + return calibp0bar + calibp1bar * (curEvtMistag_[taggerID] - avgMistagBkgnd_[bkgndID][taggerID][arrayIndex]); } return 0.0; } -Double_t LauFlavTag::getCapitalOmegaBkgnd(const ULong_t position, const Flavour flag, const UInt_t classID) const +Double_t LauFlavTag::getCapitalOmegaBkgnd(const std::size_t bkgndID, const std::size_t taggerID, const Flavour flag, const Flavour decayFlv) const { //Fill in with the various options of flag = +-1, type = signal-like, combinatorial etc if ( flag == Flavour::Unknown ){ std::cerr << "ERROR in LauFlavTag::getCapitalOmegaBkgnd : Invalid flag, you must request either Omega (+1) or Omega bar (-1) to be returned" << std::endl; return 0.0; } - //Delta functions to control which terms contribute - Int_t deltap1(0), deltam1(0), delta0(0); + const std::size_t arrayIndex { static_cast( bkgndDecayFlvDep_[bkgndID] * decayFlv + 1 ) }; - if (curEvtTagFlv_[position] == Flavour::Bbar){ - deltam1 = 1; - } else if(curEvtTagFlv_[position] == Flavour::B){ - deltap1 = 1; - } else{ - delta0 = 1; - } + //Delta functions to control which terms contribute + bool deltap1 { curEvtTagFlv_[taggerID] == Flavour::B }; + bool deltam1 { curEvtTagFlv_[taggerID] == Flavour::Bbar }; + bool delta0 { curEvtTagFlv_[taggerID] == Flavour::Unknown }; //Efficiency Double_t effB0(0.0), effB0bar(0.0); if (useAveDelta_){ - if (tagEffBkgnd_ave_[classID][position]==nullptr){ - effB0 = tagEffBkgnd_hist_ave_[classID][position]->GetBinContent(tagEffBkgnd_hist_ave_[classID][position]->FindFixBin(curEvtDecayTime_)) + 0.5*tagEffBkgnd_hist_delta_[classID][position]->GetBinContent(tagEffBkgnd_hist_delta_[classID][position]->FindFixBin(curEvtDecayTime_)); - effB0bar = tagEffBkgnd_hist_ave_[classID][position]->GetBinContent(tagEffBkgnd_hist_ave_[classID][position]->FindFixBin(curEvtDecayTime_)) - 0.5*tagEffBkgnd_hist_delta_[classID][position]->GetBinContent(tagEffBkgnd_hist_delta_[classID][position]->FindFixBin(curEvtDecayTime_)); + if (tagEffBkgnd_ave_[bkgndID][taggerID][arrayIndex]==nullptr){ + effB0 = tagEffBkgnd_hist_ave_[bkgndID][taggerID][arrayIndex]->GetBinContent(tagEffBkgnd_hist_ave_[bkgndID][taggerID][arrayIndex]->FindFixBin(curEvtDecayTime_)) + 0.5*tagEffBkgnd_hist_delta_[bkgndID][taggerID][arrayIndex]->GetBinContent(tagEffBkgnd_hist_delta_[bkgndID][taggerID][arrayIndex]->FindFixBin(curEvtDecayTime_)); + effB0bar = tagEffBkgnd_hist_ave_[bkgndID][taggerID][arrayIndex]->GetBinContent(tagEffBkgnd_hist_ave_[bkgndID][taggerID][arrayIndex]->FindFixBin(curEvtDecayTime_)) - 0.5*tagEffBkgnd_hist_delta_[bkgndID][taggerID][arrayIndex]->GetBinContent(tagEffBkgnd_hist_delta_[bkgndID][taggerID][arrayIndex]->FindFixBin(curEvtDecayTime_)); } else { - effB0 = tagEffBkgnd_ave_[classID][position]->unblindValue() + 0.5*tagEffBkgnd_delta_[classID][position]->unblindValue(); - effB0bar = tagEffBkgnd_ave_[classID][position]->unblindValue() - 0.5*tagEffBkgnd_delta_[classID][position]->unblindValue(); + effB0 = tagEffBkgnd_ave_[bkgndID][taggerID][arrayIndex]->unblindValue() + 0.5*tagEffBkgnd_delta_[bkgndID][taggerID][arrayIndex]->unblindValue(); + effB0bar = tagEffBkgnd_ave_[bkgndID][taggerID][arrayIndex]->unblindValue() - 0.5*tagEffBkgnd_delta_[bkgndID][taggerID][arrayIndex]->unblindValue(); } }else{ - if (tagEffBkgnd_B0_[classID][position]==nullptr){ - effB0 = tagEffBkgnd_hist_B0_[classID][position]->GetBinContent(tagEffBkgnd_hist_B0_[classID][position]->FindFixBin(curEvtDecayTime_)); - effB0bar = tagEffBkgnd_hist_B0bar_[classID][position]->GetBinContent(tagEffBkgnd_hist_B0bar_[classID][position]->FindFixBin(curEvtDecayTime_)); + if (tagEffBkgnd_B0_[bkgndID][taggerID][arrayIndex]==nullptr){ + effB0 = tagEffBkgnd_hist_B0_[bkgndID][taggerID][arrayIndex]->GetBinContent(tagEffBkgnd_hist_B0_[bkgndID][taggerID][arrayIndex]->FindFixBin(curEvtDecayTime_)); + effB0bar = tagEffBkgnd_hist_B0bar_[bkgndID][taggerID][arrayIndex]->GetBinContent(tagEffBkgnd_hist_B0bar_[bkgndID][taggerID][arrayIndex]->FindFixBin(curEvtDecayTime_)); } else { - effB0 = tagEffBkgnd_B0_[classID][position]->unblindValue(); - effB0bar = tagEffBkgnd_B0bar_[classID][position]->unblindValue(); + effB0 = tagEffBkgnd_B0_[bkgndID][taggerID][arrayIndex]->unblindValue(); + effB0bar = tagEffBkgnd_B0bar_[bkgndID][taggerID][arrayIndex]->unblindValue(); } } - //Need to know which background eta PDF to use - classID + //Need to know which background eta PDF to use - bkgndID std::vector abs; - abs.push_back(curEvtMistag_[position]); - etaBkgndPdfs_[classID][position]->calcLikelihoodInfo(abs); - Double_t h { etaBkgndPdfs_[classID][position]->getLikelihood() }; + abs.push_back(curEvtMistag_[taggerID]); + etaBkgndPdfs_[bkgndID][taggerID][arrayIndex]->calcLikelihoodInfo(abs); + const Double_t h { etaBkgndPdfs_[bkgndID][taggerID][arrayIndex]->getLikelihood() }; const Double_t u { 2.0 }; // the PDF value for a uniform PDF between 0.0 and 0.5 - if (bkgndTypes_[classID] == BkgndType::Combinatorial){ - // Combinatorial efficiences are defined differently - // effB0 - chance to tag any combinatorial event as a B0 - // effB0bar - chance to tag any combinatorial event as a B0bar - return (deltap1*effB0 + deltam1*effB0bar)*h + delta0*(1.0 - effB0 - effB0bar)*u; - } else if (bkgndTypes_[classID] == BkgndType::FlavourSpecific){ - Double_t omega = this->getLittleOmegaBkgnd(position, flag, classID); - if (flag == Flavour::B){ - return (deltap1*effB0*(1-omega) + deltam1*effB0*omega)*h + delta0*(1-effB0)*u; - } else { - return (deltam1*effB0bar*(1-omega) + deltap1*effB0bar*omega)*h + delta0*(1-effB0bar)*u; - } - } else if (bkgndTypes_[classID] == BkgndType::SelfConjugate){ - Double_t omega = this->getLittleOmegaBkgnd(position, flag, classID); - if (flag == Flavour::B){ - return (deltap1*effB0*(1-omega) + deltam1*effB0*omega)*h + delta0*(1-effB0)*u; - } else { - return (deltam1*effB0bar*(1-omega) + deltap1*effB0bar*omega)*h + delta0*(1-effB0bar)*u; - } - } else if (bkgndTypes_[classID] == BkgndType::NonSelfConjugate){ - return 1.0; + switch ( bkgndTypes_[bkgndID] ) { + case BkgndType::Combinatorial : + // Combinatorial efficiences are defined differently + // effB0 - chance to tag any combinatorial event as a B0 + // effB0bar - chance to tag any combinatorial event as a B0bar + return (deltap1*effB0 + deltam1*effB0bar)*h + delta0*(1.0 - effB0 - effB0bar)*u; + + case BkgndType::FlavourSpecific : + case BkgndType::SelfConjugate : + case BkgndType::NonSelfConjugate : // TODO - double check what to do for NonSelfConjugate (same as FlavourSpecific and SelfConjugate?) + { + const Double_t omega { this->getLittleOmegaBkgnd(bkgndID, taggerID, flag, decayFlv) }; + if (flag == Flavour::B){ + return (deltap1*effB0*(1-omega) + deltam1*effB0*omega)*h + delta0*(1-effB0)*u; + } else { + return (deltam1*effB0bar*(1-omega) + deltap1*effB0bar*omega)*h + delta0*(1-effB0bar)*u; + } + } + } +} + +void LauFlavTag::setBkgndParams(const TString& bkgndName, const TString& taggerName, LauAbsPdf* etaPdf, const std::pair tagEff) +{ + if ( bkgndIndex_.count(bkgndName) == 0 ) { + std::cerr << "ERROR in LauFlavTag::setBkgndParams : Background name \"" << bkgndName << "\" not recognised please check your options" << std::endl; + return; + } + + if ( taggerIndex_.count(taggerName) == 0 ){ + std::cerr << "ERROR in LauFlavTag::setBkgndParams : Tagger name \"" << taggerName << "\" not recognised please check your options" << std::endl; + return; + } + + const std::size_t bkgndID { bkgndIndex_.at(bkgndName) }; + const std::size_t taggerID { taggerIndex_.at(taggerName) }; + + bkgndDecayFlvDep_[bkgndID] = false; + + etaBkgndPdfs_[bkgndID][taggerID][0] = nullptr; + etaBkgndPdfs_[bkgndID][taggerID][1] = etaPdf; + etaBkgndPdfs_[bkgndID][taggerID][2] = nullptr; + Lau1DHistPdf* etahistpdf = dynamic_cast(etaPdf); + if (etahistpdf){ + avgMistagBkgnd_[bkgndID][taggerID][0] = 0.0; + avgMistagBkgnd_[bkgndID][taggerID][1] = etahistpdf->getMean(); + avgMistagBkgnd_[bkgndID][taggerID][2] = 0.0; + } else { + std::cerr << "WARNING in LauFlavTag::setBkgndParams : Couldn't determine average eta value from PDF. Setting it to 0.4." << std::endl; + avgMistagBkgnd_[bkgndID][taggerID][0] = 0.0; + avgMistagBkgnd_[bkgndID][taggerID][1] = 0.4; + avgMistagBkgnd_[bkgndID][taggerID][2] = 0.0; + } + + if (useAveDelta_){ + const TString tagEff_aveName{"tagEff_ave_"+taggerName+"_bkgnd_"+bkgndName}; + const TString tagEff_deltaName{"tagEff_delta_"+taggerName+"_bkgnd_"+bkgndName}; + tagEffBkgnd_ave_[bkgndID][taggerID][0] = nullptr; + tagEffBkgnd_delta_[bkgndID][taggerID][0] = nullptr; + tagEffBkgnd_ave_[bkgndID][taggerID][1] = new LauParameter{tagEff_aveName, tagEff.first, 0.0, 1.0, kTRUE}; + tagEffBkgnd_delta_[bkgndID][taggerID][1] = new LauParameter{tagEff_deltaName, tagEff.second, -1.0, 1.0, kTRUE}; + tagEffBkgnd_ave_[bkgndID][taggerID][2] = nullptr; + tagEffBkgnd_delta_[bkgndID][taggerID][2] = nullptr; } else { - return 1.0; + const TString tagEff_b0Name{"tagEff_b0_"+taggerName+"_bkgnd_"+bkgndName}; + const TString tagEff_b0barName{"tagEff_b0bar_"+taggerName+"_bkgnd_"+bkgndName}; + tagEffBkgnd_B0_[bkgndID][taggerID][0] = nullptr; + tagEffBkgnd_B0bar_[bkgndID][taggerID][0] = nullptr; + tagEffBkgnd_B0_[bkgndID][taggerID][1] = new LauParameter{tagEff_b0Name, tagEff.first, 0.0, 1.0, kTRUE}; + tagEffBkgnd_B0bar_[bkgndID][taggerID][1] = new LauParameter{tagEff_b0barName, tagEff.second, 0.0, 1.0, kTRUE}; + tagEffBkgnd_B0_[bkgndID][taggerID][2] = nullptr; + tagEffBkgnd_B0bar_[bkgndID][taggerID][2] = nullptr; } + + std::cout << "INFO in LauFlavTag::setBkgndParams : Added efficiency parameters and eta PDF for background " << bkgndName << " for tagger " << taggerName << std::endl; } -void LauFlavTag::setBkgndParams(const TString& bkgndName, const TString& taggerName, LauAbsPdf* etaPdf, std::pair tagEff) +void LauFlavTag::setBkgndParams(const TString& bkgndName, const TString& taggerName, LauAbsPdf* etaPdfB, std::pair tagEffB, LauAbsPdf* etaPdfBbar, std::pair tagEffBbar) { - if (taggerPosition_.count(taggerName)==0){ - std::cerr << "ERROR in LauFlavTag::setBkgndParams : Tagger name not recognised please check your options" << std::endl; + if ( bkgndIndex_.count(bkgndName) == 0 ) { + std::cerr << "ERROR in LauFlavTag::setBkgndParams : Background name \"" << bkgndName << "\" not recognised please check your options" << std::endl; return; } - Int_t bkgndID(-1); - for (ULong_t i=0; i(etaPdf); + bkgndDecayFlvDep_[bkgndID] = true; + + etaBkgndPdfs_[bkgndID][taggerID][0] = etaPdfBbar; + Lau1DHistPdf* etahistpdf = dynamic_cast(etaPdfBbar); if (etahistpdf){ - avgMistagBkgnd_[bkgndID][position] = etahistpdf->getMean(); + avgMistagBkgnd_[bkgndID][taggerID][0] = etahistpdf->getMean(); } else { std::cerr << "WARNING in LauFlavTag::setBkgndParams : Couldn't determine average eta value from PDF. Setting it to 0.4." << std::endl; - avgMistagBkgnd_[bkgndID][position] = 0.4; + avgMistagBkgnd_[bkgndID][taggerID][0] = 0.4; } - TString tagEff_b0Name("tagEff_b0_"+taggerName+"_bkgnd_"+bkgndName); - TString tagEff_b0barName("tagEff_b0bar_"+taggerName+"_bkgnd_"+bkgndName); - LauParameter* tagEffB0 = new LauParameter(tagEff_b0Name,tagEff.first,0.0,1.0,kTRUE); - LauParameter* tagEffB0bar = new LauParameter(tagEff_b0barName,tagEff.second,-1.0,1.0,kTRUE); + etaBkgndPdfs_[bkgndID][taggerID][1] = nullptr; + avgMistagBkgnd_[bkgndID][taggerID][1] = 0.0; + + etaBkgndPdfs_[bkgndID][taggerID][2] = etaPdfB; + etahistpdf = dynamic_cast(etaPdfB); + if (etahistpdf){ + avgMistagBkgnd_[bkgndID][taggerID][2] = etahistpdf->getMean(); + } else { + std::cerr << "WARNING in LauFlavTag::setBkgndParams : Couldn't determine average eta value from PDF. Setting it to 0.4." << std::endl; + avgMistagBkgnd_[bkgndID][taggerID][2] = 0.4; + } if (useAveDelta_){ - tagEffB0->name("tagEff_ave_"+taggerName+"_bkgnd_"+bkgndName); - tagEffBkgnd_ave_[bkgndID][position] = tagEffB0; - tagEffB0bar->name("tagEff_delta_"+taggerName+"_bkgnd_"+bkgndName); - tagEffBkgnd_delta_[bkgndID][position] = tagEffB0bar; + TString tagEff_aveName { "tagEff_ave_decayFlvB0bar_"+taggerName+"_bkgnd_"+bkgndName }; + TString tagEff_deltaName { "tagEff_delta_decayFlvB0bar_"+taggerName+"_bkgnd_"+bkgndName }; + tagEffBkgnd_ave_[bkgndID][taggerID][0] = new LauParameter{tagEff_aveName, tagEffBbar.first, 0.0, 1.0, kTRUE}; + tagEffBkgnd_delta_[bkgndID][taggerID][0] = new LauParameter{tagEff_deltaName, tagEffBbar.second, -1.0, 1.0, kTRUE}; + + tagEffBkgnd_ave_[bkgndID][taggerID][1] = nullptr; + tagEffBkgnd_delta_[bkgndID][taggerID][1] = nullptr; + + tagEff_aveName = "tagEff_ave_decayFlvB0_"+taggerName+"_bkgnd_"+bkgndName; + tagEff_deltaName = "tagEff_delta_decayFlvB0_"+taggerName+"_bkgnd_"+bkgndName; + tagEffBkgnd_ave_[bkgndID][taggerID][2] = new LauParameter{tagEff_aveName, tagEffBbar.first, 0.0, 1.0, kTRUE}; + tagEffBkgnd_delta_[bkgndID][taggerID][2] = new LauParameter{tagEff_deltaName, tagEffBbar.second, -1.0, 1.0, kTRUE}; } else { - tagEffBkgnd_B0_[bkgndID][position] = tagEffB0; - tagEffB0bar->range(0.0,1.0); - tagEffBkgnd_B0bar_[bkgndID][position] = tagEffB0bar; + TString tagEff_b0Name { "tagEff_b0_decayFlvB0bar_"+taggerName+"_bkgnd_"+bkgndName }; + TString tagEff_b0barName { "tagEff_b0bar_decayFlvB0bar_"+taggerName+"_bkgnd_"+bkgndName }; + tagEffBkgnd_B0_[bkgndID][taggerID][0] = new LauParameter{tagEff_b0Name, tagEffB.first, 0.0, 1.0, kTRUE}; + tagEffBkgnd_B0bar_[bkgndID][taggerID][0] = new LauParameter{tagEff_b0barName, tagEffB.second, 0.0, 1.0, kTRUE}; + + tagEffBkgnd_B0_[bkgndID][taggerID][1] = nullptr; + tagEffBkgnd_B0bar_[bkgndID][taggerID][1] = nullptr; + + tagEff_b0Name = "tagEff_b0_decayFlvB0_"+taggerName+"_bkgnd_"+bkgndName; + tagEff_b0barName = "tagEff_b0bar_decayFlvB0_"+taggerName+"_bkgnd_"+bkgndName; + tagEffBkgnd_B0_[bkgndID][taggerID][2] = new LauParameter{tagEff_b0Name, tagEffB.first, 0.0, 1.0, kTRUE}; + tagEffBkgnd_B0bar_[bkgndID][taggerID][2] = new LauParameter{tagEff_b0barName, tagEffB.second, 0.0, 1.0, kTRUE}; } std::cout << "INFO in LauFlavTag::setBkgndParams : Added efficiency parameters and eta PDF for background " << bkgndName << " for tagger " << taggerName << std::endl; } -void LauFlavTag::setBkgndParams(const TString& bkgndName, const TString& taggerName, LauAbsPdf* etaPdf, std::pair tagEff) +void LauFlavTag::setBkgndParams(const TString& bkgndName, const TString& taggerName, LauAbsPdf* etaPdf, std::pair tagEff) { - if (taggerPosition_.count(taggerName)==0){ - std::cerr << "ERROR in LauFlavTag::setBkgndParams : Tagger name not recognised please check your options" << std::endl; + if ( bkgndIndex_.count(bkgndName) == 0 ) { + std::cerr << "ERROR in LauFlavTag::setBkgndParams : Background name \"" << bkgndName << "\" not recognised please check your options" << std::endl; + return; + } + + if (taggerIndex_.count(taggerName)==0){ + std::cerr << "ERROR in LauFlavTag::setBkgndParams : Tagger name \"" << taggerName << "\" not recognised please check your options" << std::endl; return; } + if (tagEff.first==nullptr || tagEff.second==nullptr){ std::cerr << "ERROR in LauFlavTag::setBkgndParams : Efficiency histogram(s) do not exist please check your options" << std::endl; return; } - Int_t bkgndID(-1); - for (ULong_t i=0; i(etaPdf); + if (etahistpdf){ + avgMistagBkgnd_[bkgndID][taggerID][0] = 0.0; + avgMistagBkgnd_[bkgndID][taggerID][1] = etahistpdf->getMean(); + avgMistagBkgnd_[bkgndID][taggerID][2] = 0.0; + } else { + std::cerr << "WARNING in LauFlavTag::setBkgndParams : Couldn't determine average eta value from PDF. Setting it to 0.4." << std::endl; + avgMistagBkgnd_[bkgndID][taggerID][0] = 0.0; + avgMistagBkgnd_[bkgndID][taggerID][1] = 0.4; + avgMistagBkgnd_[bkgndID][taggerID][2] = 0.0; + } + + if (useAveDelta_){ + tagEffBkgnd_hist_ave_[bkgndID][taggerID][0] = nullptr; + tagEffBkgnd_hist_delta_[bkgndID][taggerID][0] = nullptr; + tagEffBkgnd_hist_ave_[bkgndID][taggerID][1] = tagEff.first; + tagEffBkgnd_hist_delta_[bkgndID][taggerID][1] = tagEff.second; + tagEffBkgnd_hist_ave_[bkgndID][taggerID][2] = nullptr; + tagEffBkgnd_hist_delta_[bkgndID][taggerID][2] = nullptr; + } else { + tagEffBkgnd_hist_B0_[bkgndID][taggerID][0] = nullptr; + tagEffBkgnd_hist_B0bar_[bkgndID][taggerID][0] = nullptr; + tagEffBkgnd_hist_B0_[bkgndID][taggerID][1] = tagEff.first; + tagEffBkgnd_hist_B0bar_[bkgndID][taggerID][1] = tagEff.second; + tagEffBkgnd_hist_B0_[bkgndID][taggerID][2] = nullptr; + tagEffBkgnd_hist_B0bar_[bkgndID][taggerID][2] = nullptr; } - if (bkgndID==-1){ - std::cerr << "ERROR in LauFlavTag::setBkgndParams : Background name not recognised please check your options" << std::endl; + + std::cout << "INFO in LauFlavTag::setBkgndParams : Added efficiency histograms and eta PDF for background " << bkgndName << " for tagger " << taggerName << std::endl; +} + +void LauFlavTag::setBkgndParams(const TString& bkgndName, const TString& taggerName, LauAbsPdf* etaPdfB, std::pair tagEffB, LauAbsPdf* etaPdfBbar, std::pair tagEffBbar) +{ + if ( bkgndIndex_.count(bkgndName) == 0 ) { + std::cerr << "ERROR in LauFlavTag::setBkgndParams : Background name \"" << bkgndName << "\" not recognised please check your options" << std::endl; return; } - Int_t position = taggerPosition_.at(taggerName); - etaBkgndPdfs_[bkgndID][position] = etaPdf; - Lau1DHistPdf* etahistpdf = dynamic_cast(etaPdf); + if (taggerIndex_.count(taggerName)==0){ + std::cerr << "ERROR in LauFlavTag::setBkgndParams : Tagger name \"" << taggerName << "\" not recognised please check your options" << std::endl; + return; + } + + if (tagEffB.first==nullptr || tagEffB.second==nullptr || tagEffBbar.first==nullptr || tagEffBbar.second==nullptr){ + std::cerr << "ERROR in LauFlavTag::setBkgndParams : Efficiency histogram(s) do not exist please check your options" << std::endl; + return; + } + + const std::size_t bkgndID { bkgndIndex_.at(bkgndName) }; + const std::size_t taggerID { taggerIndex_.at(taggerName) }; + + if ( bkgndTypes_[bkgndID] != BkgndType::Combinatorial ) { + std::cerr << "ERROR in LauFlavTag::setBkgndParams : Background \"" << bkgndName << "\" is not of type Combinatorial" << std::endl; + std::cerr << " : As such, it does not make sense to call this version of the function that separates the tagging efficiency by decay flavour" << std::endl; + return; + } + + bkgndDecayFlvDep_[bkgndID] = true; + + etaBkgndPdfs_[bkgndID][taggerID][0] = etaPdfBbar; + Lau1DHistPdf* etahistpdf = dynamic_cast(etaPdfBbar); if (etahistpdf){ - avgMistagBkgnd_[bkgndID][position] = etahistpdf->getMean(); + avgMistagBkgnd_[bkgndID][taggerID][0] = etahistpdf->getMean(); } else { std::cerr << "WARNING in LauFlavTag::setBkgndParams : Couldn't determine average eta value from PDF. Setting it to 0.4." << std::endl; - avgMistagBkgnd_[bkgndID][position] = 0.4; + avgMistagBkgnd_[bkgndID][taggerID][0] = 0.4; + } + + etaBkgndPdfs_[bkgndID][taggerID][1] = nullptr; + avgMistagBkgnd_[bkgndID][taggerID][1] = 0.0; + + etaBkgndPdfs_[bkgndID][taggerID][2] = etaPdfB; + etahistpdf = dynamic_cast(etaPdfB); + if (etahistpdf){ + avgMistagBkgnd_[bkgndID][taggerID][2] = etahistpdf->getMean(); + } else { + std::cerr << "WARNING in LauFlavTag::setBkgndParams : Couldn't determine average eta value from PDF. Setting it to 0.4." << std::endl; + avgMistagBkgnd_[bkgndID][taggerID][2] = 0.4; } if (useAveDelta_){ - tagEffBkgnd_hist_ave_[bkgndID][position] = tagEff.first; - tagEffBkgnd_hist_delta_[bkgndID][position] = tagEff.second; + tagEffBkgnd_hist_ave_[bkgndID][taggerID][0] = tagEffBbar.first; + tagEffBkgnd_hist_delta_[bkgndID][taggerID][0] = tagEffBbar.second; + tagEffBkgnd_hist_ave_[bkgndID][taggerID][1] = nullptr; + tagEffBkgnd_hist_delta_[bkgndID][taggerID][1] = nullptr; + tagEffBkgnd_hist_ave_[bkgndID][taggerID][2] = tagEffB.first; + tagEffBkgnd_hist_delta_[bkgndID][taggerID][2] = tagEffB.second; } else { - tagEffBkgnd_hist_B0_[bkgndID][position] = tagEff.first; - tagEffBkgnd_hist_B0bar_[bkgndID][position] = tagEff.second; + tagEffBkgnd_hist_B0_[bkgndID][taggerID][0] = tagEffBbar.first; + tagEffBkgnd_hist_B0bar_[bkgndID][taggerID][0] = tagEffBbar.second; + tagEffBkgnd_hist_B0_[bkgndID][taggerID][1] = nullptr; + tagEffBkgnd_hist_B0bar_[bkgndID][taggerID][1] = nullptr; + tagEffBkgnd_hist_B0_[bkgndID][taggerID][2] = tagEffB.first; + tagEffBkgnd_hist_B0bar_[bkgndID][taggerID][2] = tagEffB.second; } std::cout << "INFO in LauFlavTag::setBkgndParams : Added efficiency histograms and eta PDF for background " << bkgndName << " for tagger " << taggerName << std::endl; } - -Double_t LauFlavTag::getEtaGen(const ULong_t position) +Double_t LauFlavTag::getEtaGen(const std::size_t taggerID) { - LauFitData data { etaPdfs_[position]->generate(nullptr) }; - Double_t etagen { data.at(etaPdfs_[position]->varName()) }; + LauFitData data { etaPdfs_[taggerID]->generate(nullptr) }; + Double_t etagen { data.at(etaPdfs_[taggerID]->varName()) }; if (etagen > 0.5){etagen = 0.5;} if (etagen < 0.0){etagen = 0.0;} - curEvtMistag_[position] = etagen; + curEvtMistag_[taggerID] = etagen; return etagen; } -Double_t LauFlavTag::getEtaGenBkgnd(const ULong_t position, const ULong_t bkgndID) +Double_t LauFlavTag::getEtaGenBkgnd(const std::size_t taggerID, const std::size_t bkgndID, const Flavour decayFlv) { - LauFitData data { etaBkgndPdfs_[bkgndID][position]->generate(nullptr) }; - Double_t etagen { data.at(etaBkgndPdfs_[bkgndID][position]->varName()) }; + const std::size_t arrayIndex { static_cast( bkgndDecayFlvDep_[bkgndID] * decayFlv + 1 ) }; + LauFitData data { etaBkgndPdfs_[bkgndID][taggerID][arrayIndex]->generate(nullptr) }; + Double_t etagen { data.at(etaBkgndPdfs_[bkgndID][taggerID][arrayIndex]->varName()) }; if (etagen > 0.5){etagen = 0.5;} if (etagen < 0.0){etagen = 0.0;} - curEvtMistag_[position] = etagen; + curEvtMistag_[taggerID] = etagen; return etagen; } -void LauFlavTag::setTrueTagVarName(TString trueTagVarName){ +void LauFlavTag::setTrueTagVarName(TString trueTagVarName) +{ trueTagVarName_ = std::move(trueTagVarName); } -void LauFlavTag::setDecayFlvVarName(TString decayFlvVarName){ +void LauFlavTag::setDecayFlvVarName(TString decayFlvVarName) +{ decayFlvVarName_ = std::move(decayFlvVarName); } -void LauFlavTag::addP0GaussianConstraints(TString name, std::pair constraint1, std::pair constraint2){ - //Does key exist? - if (taggerPosition_.count(name)==0){ +void LauFlavTag::addP0GaussianConstraints(const TString& taggerName, const std::pair constraint1, const std::pair constraint2) +{ + // Does key exist? + if (taggerIndex_.count(taggerName)==0){ std::cerr << "ERROR in LauFlavTag::addP0GaussianConstraints : Tagger name not recognised please check your options" << std::endl; std::cerr << "ERROR in LauFlavTag::addP0GaussianConstraints : Constraints have not been applied" << std::endl; return; } - //Find position in the vector from the tagger name - Double_t pos = taggerPosition_.at(name); + + // Find index in the vectors from the tagger name + const std::size_t pos { taggerIndex_.at(taggerName) }; if (!useAveDelta_){ calib_p0_B0_[pos]->addGaussianConstraint(constraint1.first,constraint1.second); calib_p0_B0bar_[pos]->addGaussianConstraint(constraint2.first,constraint2.second); }else{ calib_p0_ave_[pos]->addGaussianConstraint(constraint1.first,constraint1.second); calib_p0_delta_[pos]->addGaussianConstraint(constraint2.first,constraint2.second); } - std::cout << "INFO in LauFlavTag::addP0GaussianConstraints : Added Gaussian constraints for the P0 calibration parameters of tagger " << name << std::endl; + std::cout << "INFO in LauFlavTag::addP0GaussianConstraints : Added Gaussian constraints for the P0 calibration parameters of tagger " << taggerName << std::endl; } -void LauFlavTag::addP1GaussianConstraints(TString name, std::pair constraint1, std::pair constraint2){ - //Does key exist? - if (taggerPosition_.count(name)==0){ +void LauFlavTag::addP1GaussianConstraints(const TString& taggerName, const std::pair constraint1, const std::pair constraint2) +{ + // Does key exist? + if (taggerIndex_.count(taggerName)==0){ std::cerr << "ERROR in LauFlavTag::addP1GaussianConstraints : Tagger name not recognised please check your options" << std::endl; std::cerr << "ERROR in LauFlavTag::addP1GaussianConstraints : Constraints have not been applied" << std::endl; return; } - //Find position in the vector from the tagger name - Double_t pos = taggerPosition_.at(name); + + // Find index in the vector from the tagger name + const std::size_t pos { taggerIndex_.at(taggerName) }; if (!useAveDelta_){ calib_p1_B0_[pos]->addGaussianConstraint(constraint1.first,constraint1.second); calib_p1_B0bar_[pos]->addGaussianConstraint(constraint2.first,constraint2.second); }else{ calib_p1_ave_[pos]->addGaussianConstraint(constraint1.first,constraint1.second); calib_p1_delta_[pos]->addGaussianConstraint(constraint2.first,constraint2.second); } - std::cout << "INFO in LauFlavTag::addP1GaussianConstraints : Added Gaussian constraints for the P1 calibration parameters of tagger " << name << std::endl; + std::cout << "INFO in LauFlavTag::addP1GaussianConstraints : Added Gaussian constraints for the P1 calibration parameters of tagger " << taggerName << std::endl; } -void LauFlavTag::addTagEffGaussianConstraints(TString name, std::pair constraint1, std::pair constraint2){ - //Does key exist? - if (taggerPosition_.count(name)==0){ +void LauFlavTag::addTagEffGaussianConstraints(const TString& taggerName, const std::pair constraint1, const std::pair constraint2) +{ + // Does key exist? + if (taggerIndex_.count(taggerName)==0){ std::cerr << "ERROR in LauFlavTag::addTagEffGaussianConstraints : Tagger name not recognised please check your options" << std::endl; std::cerr << "ERROR in LauFlavTag::addTagEffGaussianConstraints : Constraints have not been applied" << std::endl; return; } - //Find position in the vector from the tagger name - Double_t pos = taggerPosition_.at(name); + + // Find index in the vector from the tagger name + const std::size_t pos { taggerIndex_.at(taggerName) }; if (tagEff_B0_[pos] == nullptr){ std::cerr << "ERROR in LauFlavTag::addTagEffGaussianConstraints : Cannot add Gaussian constraints to a histogram!" << std::endl; return; } if (!useAveDelta_){ tagEff_B0_[pos]->addGaussianConstraint(constraint1.first,constraint1.second); tagEff_B0bar_[pos]->addGaussianConstraint(constraint2.first,constraint2.second); }else{ tagEff_ave_[pos]->addGaussianConstraint(constraint1.first,constraint1.second); tagEff_delta_[pos]->addGaussianConstraint(constraint2.first,constraint2.second); } - std::cout << "INFO in LauFlavTag::addTagEffGaussianConstraints : Added Gaussian constraints for the tagging efficiency parameters of tagger " << name << std::endl; + std::cout << "INFO in LauFlavTag::addTagEffGaussianConstraints : Added Gaussian constraints for the tagging efficiency parameters of tagger " << taggerName << std::endl; +} + +LauParameter* LauFlavTag::findParameter( const TString& taggerName, std::vector& parameters ) +{ + // Check the tagger name is valid + auto iter = taggerIndex_.find(taggerName); + if ( iter == taggerIndex_.end() ){ + return nullptr; + } + + // If so, find the appropriate parameter + const std::size_t index { iter->second }; + return parameters[index]; } -void LauFlavTag::floatCalibParP0B0(const TString name){ +void LauFlavTag::floatCalibParP0B0(const TString& taggerName) +{ if (useAveDelta_){ std::cerr << "ERROR in LauFlavTag::floatCalibParP0B0 : Trying to set calibration parameters for B0/B0bar not average/delta" << std::endl; return; } - if (name==""){ + + if (taggerName==""){ + // Float parameters for all taggers for (auto& param : calib_p0_B0_){ if (param==nullptr){continue;} param->fixed(kFALSE); } - } else { - //Does key exist? - if (taggerPosition_.count(name)==0){ - std::cerr << "ERROR in LauFlavTag::floatCalibParP0B0 : Tagger name not recognised please check your options" << std::endl; - return; - } - //Find position in the vector from the tagger name - Double_t position = taggerPosition_.at(name); - calib_p0_B0_[position]->fixed(kFALSE); + return; } + + // Float parameter for requested tagger + LauParameter* par { this->findParameter( taggerName, calib_p0_B0_ ) }; + if ( not par ){ + std::cerr << "ERROR in LauFlavTag::floatCalibParP0B0 : Tagger name not recognised please check your options" << std::endl; + return; + } + par->fixed(kFALSE); } -void LauFlavTag::floatCalibParP1B0(const TString name){ +void LauFlavTag::floatCalibParP1B0(const TString& taggerName) +{ if (useAveDelta_){ std::cerr << "ERROR in LauFlavTag::floatCalibParP1B0 : Trying to set calibration parameters for B0/B0bar not average/delta" << std::endl; return; } - if (name==""){ + + if (taggerName==""){ + // Float parameters for all taggers for (auto& param : calib_p1_B0_){ if (param==nullptr){continue;} param->fixed(kFALSE); } - } else { - //Does key exist? - if (taggerPosition_.count(name)==0){ - std::cerr << "ERROR in LauFlavTag::floatCalibParP1B0 : Tagger name not recognised please check your options" << std::endl; - return; - } - //Find position in the vector from the tagger name - Double_t position = taggerPosition_.at(name); - calib_p1_B0_[position]->fixed(kFALSE); + return; + } + + // Float parameter for requested tagger + LauParameter* par { this->findParameter( taggerName, calib_p1_B0_ ) }; + if ( not par ){ + std::cerr << "ERROR in LauFlavTag::floatCalibParP1B0 : Tagger name not recognised please check your options" << std::endl; + return; } + par->fixed(kFALSE); } -void LauFlavTag::floatCalibParP0B0bar(const TString name){ +void LauFlavTag::floatCalibParP0B0bar(const TString& taggerName) +{ if (useAveDelta_){ std::cerr << "ERROR in LauFlavTag::floatCalibParP0B0bar : Trying to set calibration parameters for B0/B0bar not average/delta" << std::endl; return; } - if (name==""){ + + if (taggerName==""){ + // Float parameters for all taggers for (auto& param : calib_p0_B0bar_){ if (param==nullptr){continue;} param->fixed(kFALSE); } - } else { - //Does key exist? - if (taggerPosition_.count(name)==0){ - std::cerr << "ERROR in LauFlavTag::floatCalibParP0B0bar : Tagger name not recognised please check your options" << std::endl; - return; - } - //Find position in the vector from the tagger name - Double_t position = taggerPosition_.at(name); - calib_p0_B0bar_[position]->fixed(kFALSE); + return; } + + // Float parameter for requested tagger + LauParameter* par { this->findParameter( taggerName, calib_p0_B0bar_ ) }; + if ( not par ) { + std::cerr << "ERROR in LauFlavTag::floatCalibParP0B0bar : Tagger name not recognised please check your options" << std::endl; + return; + } + par->fixed(kFALSE); } -void LauFlavTag::floatCalibParP1B0bar(const TString name){ +void LauFlavTag::floatCalibParP1B0bar(const TString& taggerName) +{ if (useAveDelta_){ std::cerr << "ERROR in LauFlavTag::floatCalibParP1B0bar : Trying to set calibration parameters for B0/B0bar not average/delta" << std::endl; return; } - if (name==""){ + + if (taggerName==""){ + // Float parameters for all taggers for (auto& param : calib_p1_B0bar_){ if (param==nullptr){continue;} param->fixed(kFALSE); } - } else { - //Does key exist? - if (taggerPosition_.count(name)==0){ - std::cerr << "ERROR in LauFlavTag::floatCalibParP1B0bar : Tagger name not recognised please check your options" << std::endl; - return; - } - //Find position in the vector from the tagger name - Double_t position = taggerPosition_.at(name); - calib_p1_B0bar_[position]->fixed(kFALSE); + return; + } + + // Float parameter for requested tagger + LauParameter* par { this->findParameter( taggerName, calib_p1_B0bar_ ) }; + if ( not par ) { + std::cerr << "ERROR in LauFlavTag::floatCalibParP1B0bar : Tagger name not recognised please check your options" << std::endl; + return; } + par->fixed(kFALSE); } -void LauFlavTag::floatCalibParP0Ave(const TString name){ +void LauFlavTag::floatCalibParP0Ave(const TString& taggerName) +{ if (!useAveDelta_){ std::cerr << "ERROR in LauFlavTag::floatCalibParP0Ave : Trying to set calibration parameters for average/delta not B0/B0bar" << std::endl; return; } - if (name==""){ + + if (taggerName==""){ + // Float parameters for all taggers for (auto& param : calib_p0_ave_){ if (param==nullptr){continue;} param->fixed(kFALSE); } - } else { - //Does key exist? - if (taggerPosition_.count(name)==0){ - std::cerr << "ERROR in LauFlavTag::floatCalibParP0Ave : Tagger name not recognised please check your options" << std::endl; - return; - } - //Find position in the vector from the tagger name - Double_t position = taggerPosition_.at(name); - calib_p0_ave_[position]->fixed(kFALSE); + return; } + + // Float parameter for requested tagger + LauParameter* par { this->findParameter( taggerName, calib_p0_ave_ ) }; + if ( not par ) { + std::cerr << "ERROR in LauFlavTag::floatCalibParP0Ave : Tagger name not recognised please check your options" << std::endl; + return; + } + par->fixed(kFALSE); } -void LauFlavTag::floatCalibParP0Delta(const TString name){ +void LauFlavTag::floatCalibParP0Delta(const TString& taggerName) +{ if (!useAveDelta_){ std::cerr << "ERROR in LauFlavTag::floatCalibParP0Delta : Trying to set calibration parameters for average/delta not B0/B0bar" << std::endl; return; } - if (name==""){ + + if (taggerName==""){ + // Float parameters for all taggers for (auto& param : calib_p0_delta_){ if (param==nullptr){continue;} param->fixed(kFALSE); } - } else { - //Does key exist? - if (taggerPosition_.count(name)==0){ - std::cerr << "ERROR in LauFlavTag::floatCalibParP0Delta : Tagger name not recognised please check your options" << std::endl; - return; - } - //Find position in the vector from the tagger name - Double_t position = taggerPosition_.at(name); - calib_p0_delta_[position]->fixed(kFALSE); + return; + } + + // Float parameter for requested tagger + LauParameter* par { this->findParameter( taggerName, calib_p0_delta_ ) }; + if ( not par ) { + std::cerr << "ERROR in LauFlavTag::floatCalibParP0Delta : Tagger name not recognised please check your options" << std::endl; + return; } + par->fixed(kFALSE); } -void LauFlavTag::floatCalibParP1Ave(const TString name){ +void LauFlavTag::floatCalibParP1Ave(const TString& taggerName) +{ if (!useAveDelta_){ std::cerr << "ERROR in LauFlavTag::floatCalibParP1Ave : Trying to set calibration parameters for average/delta not B0/B0bar" << std::endl; return; } - if (name==""){ + + if (taggerName==""){ + // Float parameters for all taggers for (auto& param : calib_p1_ave_){ if (param==nullptr){continue;} param->fixed(kFALSE); } - } else { - //Does key exist? - if (taggerPosition_.count(name)==0){ - std::cerr << "ERROR in LauFlavTag::floatCalibParP1Ave : Tagger name not recognised please check your options" << std::endl; - return; - } - //Find position in the vector from the tagger name - Double_t position = taggerPosition_.at(name); - calib_p1_ave_[position]->fixed(kFALSE); + return; } + + // Float parameter for requested tagger + LauParameter* par { this->findParameter( taggerName, calib_p1_ave_ ) }; + if ( not par ) { + std::cerr << "ERROR in LauFlavTag::floatCalibParP1Ave : Tagger name not recognised please check your options" << std::endl; + return; + } + par->fixed(kFALSE); } -void LauFlavTag::floatCalibParP1Delta(const TString name){ +void LauFlavTag::floatCalibParP1Delta(const TString& taggerName) +{ if (!useAveDelta_){ std::cerr << "ERROR in LauFlavTag::floatCalibParP1Delta : Trying to set calibration parameters for average/delta not B0/B0bar" << std::endl; return; } - if (name==""){ + + if (taggerName==""){ + // Float parameters for all taggers for (auto& param : calib_p1_delta_){ if (param==nullptr){continue;} param->fixed(kFALSE); } - } else { - //Does key exist? - if (taggerPosition_.count(name)==0){ - std::cerr << "ERROR in LauFlavTag::floatCalibParP1Delta : Tagger name not recognised please check your options" << std::endl; - return; - } - //Find position in the vector from the tagger name - Double_t position = taggerPosition_.at(name); - calib_p1_delta_[position]->fixed(kFALSE); + return; + } + + // Float parameter for requested tagger + LauParameter* par { this->findParameter( taggerName, calib_p1_delta_ ) }; + if ( not par ) { + std::cerr << "ERROR in LauFlavTag::floatCalibParP1Delta : Tagger name not recognised please check your options" << std::endl; + return; } + par->fixed(kFALSE); } void LauFlavTag::floatAllCalibPars(){ if (useAveDelta_){ this->floatCalibParP0Ave(); this->floatCalibParP0Delta(); this->floatCalibParP1Ave(); this->floatCalibParP1Delta(); } else { this->floatCalibParP0B0(); this->floatCalibParP1B0(); this->floatCalibParP0B0bar(); this->floatCalibParP1B0bar(); } } diff --git a/src/LauTimeDepFitModel.cc b/src/LauTimeDepFitModel.cc index b6e4068..e5662fe 100644 --- a/src/LauTimeDepFitModel.cc +++ b/src/LauTimeDepFitModel.cc @@ -1,3161 +1,3231 @@ /* Copyright 2006 University of Warwick Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Laura++ package authors: John Back Paul Harrison Thomas Latham */ /*! \file LauTimeDepFitModel.cc \brief File containing implementation of LauTimeDepFitModel class. */ #include #include #include #include #include #include #include "TFile.h" #include "TMinuit.h" #include "TRandom.h" #include "TSystem.h" #include "TVirtualFitter.h" #include "LauAbsBkgndDPModel.hh" #include "LauAbsCoeffSet.hh" #include "LauAbsPdf.hh" #include "LauAsymmCalc.hh" #include "LauComplex.hh" #include "LauConstants.hh" #include "LauDPPartialIntegralInfo.hh" #include "LauDaughters.hh" #include "LauDecayTimePdf.hh" #include "LauFitNtuple.hh" #include "LauGenNtuple.hh" #include "LauIsobarDynamics.hh" #include "LauKinematics.hh" #include "LauParamFixed.hh" #include "LauPrint.hh" #include "LauRandom.hh" #include "LauScfMap.hh" #include "LauTimeDepFitModel.hh" #include "LauFlavTag.hh" ClassImp(LauTimeDepFitModel) LauTimeDepFitModel::LauTimeDepFitModel(LauIsobarDynamics* modelB0bar, LauIsobarDynamics* modelB0, LauFlavTag* flavTag) : LauAbsFitModel(), sigModelB0bar_(modelB0bar), sigModelB0_(modelB0), kinematicsB0bar_(modelB0bar ? modelB0bar->getKinematics() : 0), kinematicsB0_(modelB0 ? modelB0->getKinematics() : 0), usingBkgnd_(kFALSE), flavTag_(flavTag), curEvtTrueTagFlv_(LauFlavTag::Unknown), curEvtDecayFlv_(LauFlavTag::Unknown), nSigComp_(0), nSigDPPar_(0), nDecayTimePar_(0), nExtraPdfPar_(0), nNormPar_(0), nCalibPar_(0), nTagEffPar_(0), nEffiPar_(0), nAsymPar_(0), coeffsB0bar_(0), coeffsB0_(0), coeffPars_(0), fitFracB0bar_(0), fitFracB0_(0), fitFracAsymm_(0), acp_(0), meanEffB0bar_("meanEffB0bar",0.0,0.0,1.0), meanEffB0_("meanEffB0",0.0,0.0,1.0), DPRateB0bar_("DPRateB0bar",0.0,0.0,100.0), DPRateB0_("DPRateB0",0.0,0.0,100.0), signalEvents_(0), signalAsym_(0), cpevVarName_(""), cpEigenValue_(CPEven), evtCPEigenVals_(0), deltaM_("deltaM",0.0), deltaGamma_("deltaGamma",0.0), tau_("tau",LauConstants::tauB0), phiMix_("phiMix", 2.0*LauConstants::beta, -LauConstants::threePi, LauConstants::threePi, kFALSE), sinPhiMix_("sinPhiMix", TMath::Sin(2.0*LauConstants::beta), -1.0, 1.0, kFALSE), cosPhiMix_("cosPhiMix", TMath::Cos(2.0*LauConstants::beta), -1.0, 1.0, kFALSE), useSinCos_(kFALSE), phiMixComplex_(TMath::Cos(-2.0*LauConstants::beta),TMath::Sin(-2.0*LauConstants::beta)), signalDecayTimePdf_(), BkgndTypes_(flavTag_->getBkgndTypes()), BkgndDecayTimePdfs_(), curEvtDecayTime_(0.0), curEvtDecayTimeErr_(0.0), sigExtraPdf_(), AProd_("AProd",0.0,-1.0,1.0,kTRUE), iterationsMax_(100000000), nGenLoop_(0), ASq_(0.0), aSqMaxVar_(0.0), aSqMaxSet_(1.25), storeGenAmpInfo_(kFALSE), signalTree_(), reuseSignal_(kFALSE), sigDPLike_(0.0), sigExtraLike_(0.0), sigTotalLike_(0.0) { // Set up ftag here? this->setBkgndClassNames(flavTag_->getBkgndNames()); - const ULong_t nBkgnds { this->nBkgndClasses() }; + const std::size_t nBkgnds { this->nBkgndClasses() }; if ( nBkgnds > 0 ){ usingBkgnd_ = kTRUE; - for ( ULong_t iBkgnd{0}; iBkgnd < nBkgnds; ++iBkgnd ) { + for ( std::size_t iBkgnd{0}; iBkgnd < nBkgnds; ++iBkgnd ) { const TString& bkgndClass { this->bkgndClassName( iBkgnd ) }; AProdBkgnd_[iBkgnd] = new LauParameter("AProd_"+bkgndClass,0.0,-1.0,1.0,kTRUE); } } // Make sure that the integration scheme will be symmetrised sigModelB0bar_->forceSymmetriseIntegration(kTRUE); sigModelB0_->forceSymmetriseIntegration(kTRUE); } LauTimeDepFitModel::~LauTimeDepFitModel() { for ( LauAbsPdf* pdf : sigExtraPdf_ ) { delete pdf; } for(auto& data : bkgndTree_){ delete data; } } void LauTimeDepFitModel::setupBkgndVectors() { UInt_t nBkgnds { this->nBkgndClasses() }; AProdBkgnd_.resize( nBkgnds ); BkgndDPModelsB_.resize( nBkgnds ); BkgndDPModelsBbar_.resize( nBkgnds ); BkgndDecayTimePdfs_.resize( nBkgnds ); BkgndPdfs_.resize( nBkgnds ); bkgndEvents_.resize( nBkgnds ); bkgndAsym_.resize( nBkgnds ); bkgndTree_.resize( nBkgnds ); reuseBkgnd_.resize( nBkgnds ); bkgndDPLike_.resize( nBkgnds ); bkgndExtraLike_.resize( nBkgnds ); bkgndTotalLike_.resize( nBkgnds ); } void LauTimeDepFitModel::setNSigEvents(LauParameter* nSigEvents) { if ( nSigEvents == 0 ) { std::cerr << "ERROR in LauTimeDepFitModel::setNSigEvents : The LauParameter pointer is null." << std::endl; gSystem->Exit(EXIT_FAILURE); } if ( signalEvents_ != 0 ) { std::cerr << "ERROR in LauTimeDepFitModel::setNSigEvents : You are trying to overwrite the signal yield." << std::endl; return; } if ( signalAsym_ != 0 ) { std::cerr << "ERROR in LauTimeDepFitModel::setNSigEvents : You are trying to overwrite the signal asymmetry." << std::endl; return; } signalEvents_ = nSigEvents; signalEvents_->name("signalEvents"); Double_t value = nSigEvents->value(); signalEvents_->range(-2.0*(TMath::Abs(value)+1.0),2.0*(TMath::Abs(value)+1.0)); signalAsym_ = new LauParameter("signalAsym",0.0,-1.0,1.0,kTRUE); } void LauTimeDepFitModel::setNSigEvents(LauParameter* nSigEvents, LauParameter* sigAsym) { if ( nSigEvents == 0 ) { std::cerr << "ERROR in LauTimeDepFitModel::setNSigEvents : The event LauParameter pointer is null." << std::endl; gSystem->Exit(EXIT_FAILURE); } if ( sigAsym == 0 ) { std::cerr << "ERROR in LauTimeDepFitModel::setNSigEvents : The asym LauParameter pointer is null." << std::endl; gSystem->Exit(EXIT_FAILURE); } if ( signalEvents_ != 0 ) { std::cerr << "ERROR in LauTimeDepFitModel::setNSigEvents : You are trying to overwrite the signal yield." << std::endl; return; } if ( signalAsym_ != 0 ) { std::cerr << "ERROR in LauTimeDepFitModel::setNSigEvents : You are trying to overwrite the signal asymmetry." << std::endl; return; } signalEvents_ = nSigEvents; signalEvents_->name("signalEvents"); Double_t value = nSigEvents->value(); signalEvents_->range(-2.0*(TMath::Abs(value)+1.0), 2.0*(TMath::Abs(value)+1.0)); signalAsym_ = sigAsym; signalAsym_->name("signalAsym"); signalAsym_->range(-1.0,1.0); } void LauTimeDepFitModel::setNBkgndEvents(LauAbsRValue* nBkgndEvents) { if ( nBkgndEvents == 0 ) { std::cerr << "ERROR in LauTimeDepFitModel::setNBgkndEvents : The background yield LauParameter pointer is null." << std::endl; gSystem->Exit(EXIT_FAILURE); } if ( ! this->validBkgndClass( nBkgndEvents->name() ) ) { std::cerr << "ERROR in LauTimeDepFitModel::setNBkgndEvents : Invalid background class \"" << nBkgndEvents->name() << "\"." << std::endl; std::cerr << " : Background class names must be provided in \"setBkgndClassNames\" before any other background-related actions can be performed." << std::endl; gSystem->Exit(EXIT_FAILURE); } UInt_t bkgndID = this->bkgndClassID( nBkgndEvents->name() ); if ( bkgndEvents_[bkgndID] != 0 ) { std::cerr << "ERROR in LauTimeDepFitModel::setNBkgndEvents : You are trying to overwrite the background yield." << std::endl; return; } if ( bkgndAsym_[bkgndID] != 0 ) { std::cerr << "ERROR in LauTimeDepFitModel::setNBkgndEvents : You are trying to overwrite the background asymmetry." << std::endl; return; } nBkgndEvents->name( nBkgndEvents->name()+"Events" ); if ( nBkgndEvents->isLValue() ) { Double_t value = nBkgndEvents->value(); LauParameter* yield = dynamic_cast( nBkgndEvents ); yield->range(-2.0*(TMath::Abs(value)+1.0), 2.0*(TMath::Abs(value)+1.0)); } bkgndEvents_[bkgndID] = nBkgndEvents; bkgndAsym_[bkgndID] = new LauParameter(nBkgndEvents->name()+"Asym",0.0,-1.0,1.0,kTRUE); } void LauTimeDepFitModel::setNBkgndEvents(LauAbsRValue* nBkgndEvents, LauAbsRValue* bkgndAsym) { if ( nBkgndEvents == 0 ) { std::cerr << "ERROR in LauTimeDepFitModel::setNBkgndEvents : The background yield LauParameter pointer is null." << std::endl; gSystem->Exit(EXIT_FAILURE); } if ( bkgndAsym == 0 ) { std::cerr << "ERROR in LauTimeDepFitModel::setNBkgndEvents : The background asym LauParameter pointer is null." << std::endl; gSystem->Exit(EXIT_FAILURE); } if ( ! this->validBkgndClass( nBkgndEvents->name() ) ) { std::cerr << "ERROR in LauTimeDepFitModel::setNBkgndEvents : Invalid background class \"" << nBkgndEvents->name() << "\"." << std::endl; std::cerr << " : Background class names must be provided in \"setBkgndClassNames\" before any other background-related actions can be performed." << std::endl; gSystem->Exit(EXIT_FAILURE); } UInt_t bkgndID = this->bkgndClassID( nBkgndEvents->name() ); if ( bkgndEvents_[bkgndID] != 0 ) { std::cerr << "ERROR in LauTimeDepFitModel::setNBkgndEvents : You are trying to overwrite the background yield." << std::endl; return; } if ( bkgndAsym_[bkgndID] != 0 ) { std::cerr << "ERROR in LauTimeDepFitModel::setNBkgndEvents : You are trying to overwrite the background asymmetry." << std::endl; return; } nBkgndEvents->name( nBkgndEvents->name()+"Events" ); if ( nBkgndEvents->isLValue() ) { Double_t value = nBkgndEvents->value(); LauParameter* yield = dynamic_cast( nBkgndEvents ); yield->range(-2.0*(TMath::Abs(value)+1.0), 2.0*(TMath::Abs(value)+1.0)); } bkgndEvents_[bkgndID] = nBkgndEvents; bkgndAsym->name( nBkgndEvents->name()+"Asym" ); if ( bkgndAsym->isLValue() ) { LauParameter* asym = dynamic_cast( bkgndAsym ); asym->range(-1.0, 1.0); } bkgndAsym_[bkgndID] = bkgndAsym; } void LauTimeDepFitModel::setSignalDtPdf(LauDecayTimePdf* pdf) { if (pdf==0) { std::cerr<<"ERROR in LauTimeDepFitModel::setSignalDtPdf : The PDF pointer is null, not adding it."<validBkgndClass( bkgndClass) ) { std::cerr << "ERROR in LauTimeDepFitModel::setBkgndDtPdf : Invalid background class \"" << bkgndClass << "\"." << std::endl; std::cerr << " : Background class names must be provided in \"setBkgndClassNames\" before any other background-related actions can be performed." << std::endl; return; } UInt_t bkgndID = this->bkgndClassID( bkgndClass ); BkgndDecayTimePdfs_[bkgndID] = pdf; usingBkgnd_ = kTRUE; } void LauTimeDepFitModel::setBkgndDPModels(const TString& bkgndClass, LauAbsBkgndDPModel* BModel, LauAbsBkgndDPModel* BbarModel) { if (BModel==nullptr) { std::cerr << "ERROR in LauTimeDepFitModel::setBkgndDPModels : the model pointer is null for the particle model." << std::endl; return; } // check that this background name is valid if ( ! this->validBkgndClass( bkgndClass) ) { std::cerr << "ERROR in LauTimeDepFitModel::setBkgndDPModels : Invalid background class \"" << bkgndClass << "\"." << std::endl; std::cerr << " : Background class names must be provided in \"setBkgndClassNames\" before any other background-related actions can be performed." << std::endl; return; } UInt_t bkgndID = this->bkgndClassID( bkgndClass ); BkgndDPModelsB_[bkgndID] = BModel; if (BbarModel==nullptr) { std::cout << "INFO in LauTimeDepFitModel::setBkgndDPModels : the model pointer is null for the anti-particle model. Using only the particle model." << std::endl; BkgndDPModelsBbar_[bkgndID] = nullptr; } else { BkgndDPModelsBbar_[bkgndID] = BbarModel; } usingBkgnd_ = kTRUE; } void LauTimeDepFitModel::setSignalPdfs(LauAbsPdf* pdf) { // These "extra variables" are assumed to be purely kinematical, like mES and DeltaE //or making use of Rest of Event information, and therefore independent of whether //the parent is a B0 or a B0bar. If this assupmtion doesn't hold, do modify this part! if (pdf==0) { std::cerr<<"ERROR in LauTimeDepFitModel::setSignalPdfs : The PDF pointer is null."<validBkgndClass( bkgndClass ) ) { std::cerr << "ERROR in LauTimeDepFitModel::setBkgndPdf : Invalid background class \"" << bkgndClass << "\"." << std::endl; std::cerr << " : Background class names must be provided in \"setBkgndClassNames\" before any other background-related actions can be performed." << std::endl; return; } UInt_t bkgndID = this->bkgndClassID( bkgndClass ); BkgndPdfs_[bkgndID].push_back(pdf); usingBkgnd_ = kTRUE; } void LauTimeDepFitModel::setPhiMix(const Double_t phiMix, const Bool_t fixPhiMix, const Bool_t useSinCos) { phiMix_.value(phiMix); phiMix_.initValue(phiMix); phiMix_.genValue(phiMix); phiMix_.fixed(fixPhiMix); const Double_t sinPhiMix = TMath::Sin(phiMix); sinPhiMix_.value(sinPhiMix); sinPhiMix_.initValue(sinPhiMix); sinPhiMix_.genValue(sinPhiMix); sinPhiMix_.fixed(fixPhiMix); const Double_t cosPhiMix = TMath::Cos(phiMix); cosPhiMix_.value(cosPhiMix); cosPhiMix_.initValue(cosPhiMix); cosPhiMix_.genValue(cosPhiMix); cosPhiMix_.fixed(fixPhiMix); useSinCos_ = useSinCos; phiMixComplex_.setRealPart(cosPhiMix); phiMixComplex_.setImagPart(-1.0*sinPhiMix); } void LauTimeDepFitModel::initialise() { // From the initial parameter values calculate the coefficients // so they can be passed to the signal model this->updateCoeffs(); // Initialisation if (this->useDP() == kTRUE) { this->initialiseDPModels(); } // Flavour tagging //flavTag_->initialise(); // Decay-time PDFs signalDecayTimePdf_->initialise(); //Initialise for backgrounds if necessary for (auto& pdf : BkgndDecayTimePdfs_){ pdf->initialise(); } if (!this->useDP() && sigExtraPdf_.empty()) { std::cerr<<"ERROR in LauTimeDepFitModel::initialise : Signal model doesn't exist for any variable."<Exit(EXIT_FAILURE); } if (this->useDP() == kTRUE) { // Check that we have all the Dalitz-plot models if ((sigModelB0bar_ == 0) || (sigModelB0_ == 0)) { std::cerr<<"ERROR in LauTimeDepFitModel::initialise : the pointer to one (particle or anti-particle) of the signal DP models is null."<Exit(EXIT_FAILURE); } } // Next check that, if a given component is being used we've got the // right number of PDFs for all the variables involved // TODO - should probably check variable names and so on as well //UInt_t nsigpdfvars(0); //for ( LauPdfPList::const_iterator pdf_iter = sigExtraPdf_.begin(); pdf_iter != sigExtraPdf_.end(); ++pdf_iter ) { // std::vector varNames = (*pdf_iter)->varNames(); // for ( std::vector::const_iterator var_iter = varNames.begin(); var_iter != varNames.end(); ++var_iter ) { // if ( (*var_iter) != "m13Sq" && (*var_iter) != "m23Sq" ) { // ++nsigpdfvars; // } // } //} //if (usingBkgnd_) { // for (LauBkgndPdfsList::const_iterator bgclass_iter = BkgndPdfsB0_.begin(); bgclass_iter != BkgndPdfsB0_.end(); ++bgclass_iter) { // UInt_t nbkgndpdfvars(0); // const LauPdfPList& pdfList = (*bgclass_iter); // for ( LauPdfPList::const_iterator pdf_iter = pdfList.begin(); pdf_iter != pdfList.end(); ++pdf_iter ) { // std::vector varNames = (*pdf_iter)->varNames(); // for ( std::vector::const_iterator var_iter = varNames.begin(); var_iter != varNames.end(); ++var_iter ) { // if ( (*var_iter) != "m13Sq" && (*var_iter) != "m23Sq" ) { // ++nbkgndpdfvars; // } // } // } // if (nbkgndpdfvars != nsigpdfvars) { // std::cerr << "ERROR in LauTimeDepFitModel::initialise : There are " << nsigpdfvars << " signal PDF variables but " << nbkgndpdfvars << " bkgnd PDF variables." << std::endl; // gSystem->Exit(EXIT_FAILURE); // } // } //} // Clear the vectors of parameter information so we can start from scratch this->clearFitParVectors(); // Set the fit parameters for signal and background models this->setSignalDPParameters(); // Set the fit parameters for the decay time models this->setDecayTimeParameters(); // Set the fit parameters for the extra PDFs this->setExtraPdfParameters(); // Set the initial bg and signal events this->setFitNEvents(); // Handle flavour-tagging calibration parameters this->setCalibParams(); // Add tagging efficiency parameters this->setTagEffParams(); //Asymmetry terms AProd and in setAsymmetries()? this->setAsymParams(); // Check that we have the expected number of fit variables const LauParameterPList& fitVars = this->fitPars(); if (fitVars.size() != (nSigDPPar_ + nDecayTimePar_ + nExtraPdfPar_ + nNormPar_ + nCalibPar_ + nTagEffPar_ + nEffiPar_ + nAsymPar_)) { std::cerr<<"ERROR in LauTimeDepFitModel::initialise : Number of fit parameters not of expected size."<Exit(EXIT_FAILURE); } if (sigModelB0_ == 0) { std::cerr<<"ERROR in LauTimeDepFitModel::initialiseDPModels : B0 signal DP model doesn't exist"<Exit(EXIT_FAILURE); } // Need to check that the number of components we have and that the dynamics has matches up const UInt_t nAmpB0bar = sigModelB0bar_->getnTotAmp(); const UInt_t nAmpB0 = sigModelB0_->getnTotAmp(); if ( nAmpB0bar != nAmpB0 ) { std::cerr << "ERROR in LauTimeDepFitModel::initialiseDPModels : Unequal number of signal DP components in the particle and anti-particle models: " << nAmpB0bar << " != " << nAmpB0 << std::endl; gSystem->Exit(EXIT_FAILURE); } if ( nAmpB0bar != nSigComp_ ) { std::cerr << "ERROR in LauTimeDepFitModel::initialiseDPModels : Number of signal DP components in the model (" << nAmpB0bar << ") not equal to number of coefficients supplied (" << nSigComp_ << ")." << std::endl; gSystem->Exit(EXIT_FAILURE); } std::cout<<"INFO in LauTimeDepFitModel::initialiseDPModels : Initialising signal DP model"<initialise(coeffsB0bar_); sigModelB0_->initialise(coeffsB0_); fifjEffSum_.clear(); fifjEffSum_.resize(nSigComp_); for (UInt_t iAmp = 0; iAmp < nSigComp_; ++iAmp) { fifjEffSum_[iAmp].resize(nSigComp_); } // calculate the integrals of the A*Abar terms this->calcInterferenceTermIntegrals(); this->calcInterferenceTermNorm(); // Add backgrounds if (usingBkgnd_ == kTRUE) { for (auto& model : BkgndDPModelsB_){ model->initialise(); } for (auto& model : BkgndDPModelsBbar_){ if (model != nullptr) { model->initialise(); } } } } void LauTimeDepFitModel::calcInterferenceTermIntegrals() { const std::vector& integralInfoListB0bar = sigModelB0bar_->getIntegralInfos(); const std::vector& integralInfoListB0 = sigModelB0_->getIntegralInfos(); // TODO should check (first time) that they match in terms of number of entries in the vectors and that each entry has the same number of points, ranges, weights etc. LauComplex A, Abar, fifjEffSumTerm; for (UInt_t iAmp = 0; iAmp < nSigComp_; ++iAmp) { for (UInt_t jAmp = 0; jAmp < nSigComp_; ++jAmp) { fifjEffSum_[iAmp][jAmp].zero(); } } const UInt_t nIntegralRegions = integralInfoListB0bar.size(); for ( UInt_t iRegion(0); iRegion < nIntegralRegions; ++iRegion ) { const LauDPPartialIntegralInfo* integralInfoB0bar = integralInfoListB0bar[iRegion]; const LauDPPartialIntegralInfo* integralInfoB0 = integralInfoListB0[iRegion]; const UInt_t nm13Points = integralInfoB0bar->getnm13Points(); const UInt_t nm23Points = integralInfoB0bar->getnm23Points(); for (UInt_t m13 = 0; m13 < nm13Points; ++m13) { for (UInt_t m23 = 0; m23 < nm23Points; ++m23) { const Double_t weight = integralInfoB0bar->getWeight(m13,m23); const Double_t eff = integralInfoB0bar->getEfficiency(m13,m23); const Double_t effWeight = eff*weight; for (UInt_t iAmp = 0; iAmp < nSigComp_; ++iAmp) { A = integralInfoB0->getAmplitude(m13, m23, iAmp); for (UInt_t jAmp = 0; jAmp < nSigComp_; ++jAmp) { Abar = integralInfoB0bar->getAmplitude(m13, m23, jAmp); fifjEffSumTerm = Abar*A.conj(); fifjEffSumTerm.rescale(effWeight); fifjEffSum_[iAmp][jAmp] += fifjEffSumTerm; } } } } } } void LauTimeDepFitModel::calcInterferenceTermNorm() { const std::vector& fNormB0bar = sigModelB0bar_->getFNorm(); const std::vector& fNormB0 = sigModelB0_->getFNorm(); LauComplex norm; for (UInt_t iAmp = 0; iAmp < nSigComp_; ++iAmp) { for (UInt_t jAmp = 0; jAmp < nSigComp_; ++jAmp) { LauComplex coeffTerm = coeffsB0bar_[jAmp]*coeffsB0_[iAmp].conj(); coeffTerm *= fifjEffSum_[iAmp][jAmp]; coeffTerm.rescale(fNormB0bar[jAmp] * fNormB0[iAmp]); norm += coeffTerm; } } norm *= phiMixComplex_; interTermReNorm_ = 2.0*norm.re(); interTermImNorm_ = 2.0*norm.im(); } void LauTimeDepFitModel::setAmpCoeffSet(LauAbsCoeffSet* coeffSet) { // Is there a component called compName in the signal models? TString compName = coeffSet->name(); TString conjName = sigModelB0bar_->getConjResName(compName); const LauDaughters* daughtersB0bar = sigModelB0bar_->getDaughters(); const LauDaughters* daughtersB0 = sigModelB0_->getDaughters(); const Bool_t conjugate = daughtersB0bar->isConjugate( daughtersB0 ); if ( ! sigModelB0bar_->hasResonance(compName) ) { if ( ! sigModelB0bar_->hasResonance(conjName) ) { std::cerr<<"ERROR in LauTimeDepFitModel::setAmpCoeffSet : B0bar signal DP model doesn't contain component \""<name( compName ); } if ( conjugate ) { if ( ! sigModelB0_->hasResonance(conjName) ) { std::cerr<<"ERROR in LauTimeDepFitModel::setAmpCoeffSet : B0 signal DP model doesn't contain component \""<hasResonance(compName) ) { std::cerr<<"ERROR in LauTimeDepFitModel::setAmpCoeffSet : B0 signal DP model doesn't contain component \""<name() == compName) { std::cerr<<"ERROR in LauTimeDepFitModel::setAmpCoeffSet : Have already set coefficients for \""<index(nSigComp_); coeffPars_.push_back(coeffSet); TString parName = coeffSet->baseName(); parName += "FitFracAsym"; fitFracAsymm_.push_back(LauParameter(parName, 0.0, -1.0, 1.0)); acp_.push_back(coeffSet->acp()); ++nSigComp_; std::cout<<"INFO in LauTimeDepFitModel::setAmpCoeffSet : Added coefficients for component \""<acp(); LauAsymmCalc asymmCalc(fitFracB0bar_[i][i].value(), fitFracB0_[i][i].value()); Double_t asym = asymmCalc.getAsymmetry(); fitFracAsymm_[i].value(asym); if (initValues) { fitFracAsymm_[i].genValue(asym); fitFracAsymm_[i].initValue(asym); } } } void LauTimeDepFitModel::setSignalDPParameters() { // Set the fit parameters for the signal model. nSigDPPar_ = 0; if ( ! this->useDP() ) { return; } std::cout << "INFO in LauTimeDepFitModel::setSignalDPParameters : Setting the initial fit parameters for the signal DP model." << std::endl; // Place isobar coefficient parameters in vector of fit variables for (UInt_t i = 0; i < nSigComp_; ++i) { LauParameterPList pars = coeffPars_[i]->getParameters(); nSigDPPar_ += this->addFitParameters( pars, kTRUE ); } // Obtain the resonance parameters and place them in the vector of fit variables and in a separate vector // Need to make sure that they are unique because some might appear in both DP models LauParameterPList& sigDPParsB0bar = sigModelB0bar_->getFloatingParameters(); LauParameterPList& sigDPParsB0 = sigModelB0_->getFloatingParameters(); nSigDPPar_ += this->addResonanceParameters( sigDPParsB0bar ); nSigDPPar_ += this->addResonanceParameters( sigDPParsB0 ); } UInt_t LauTimeDepFitModel::addFitParameters(LauDecayTimePdf* decayTimePdf) { return this->addFitParameters( decayTimePdf->getParameters(), kTRUE ); } UInt_t LauTimeDepFitModel::addFitParameters(std::vector& decayTimePdfList) { UInt_t nParsAdded{0}; for ( auto decayTimePdf : decayTimePdfList ) { nParsAdded += this->addFitParameters( decayTimePdf ); } return nParsAdded; } void LauTimeDepFitModel::setDecayTimeParameters() { nDecayTimePar_ = 0; std::cout << "INFO in LauTimeDepFitModel::setDecayTimeParameters : Setting the initial fit parameters of the DecayTime Pdfs." << std::endl; // Loop over the Dt PDFs nDecayTimePar_ += this->addFitParameters( signalDecayTimePdf_ ); if (usingBkgnd_){ nDecayTimePar_ += this->addFitParameters(BkgndDecayTimePdfs_); } if (useSinCos_) { nDecayTimePar_ += this->addFitParameters( &sinPhiMix_ ); nDecayTimePar_ += this->addFitParameters( &cosPhiMix_ ); } else { nDecayTimePar_ += this->addFitParameters( &phiMix_ ); } } void LauTimeDepFitModel::setExtraPdfParameters() { // Include the parameters of the PDF for each tagging category in the fit // NB all of them are passed to the fit, even though some have been fixed through parameter.fixed(kTRUE) // With the new "cloned parameter" scheme only "original" parameters are passed to the fit. // Their clones are updated automatically when the originals are updated. nExtraPdfPar_ = 0; std::cout << "INFO in LauTimeDepFitModel::setExtraPdfParameters : Setting the initial fit parameters of the extra Pdfs." << std::endl; nExtraPdfPar_ += this->addFitParameters(sigExtraPdf_); if (usingBkgnd_ == kTRUE) { for (auto& pdf : BkgndPdfs_){ nExtraPdfPar_ += this->addFitParameters(pdf); } } } void LauTimeDepFitModel::setFitNEvents() { nNormPar_ = 0; std::cout << "INFO in LauTimeDepFitModel::setFitNEvents : Setting the initial fit parameters of the signal and background yields." << std::endl; // Initialise the total number of events to be the sum of all the hypotheses Double_t nTotEvts = signalEvents_->value(); this->eventsPerExpt(TMath::FloorNint(nTotEvts)); // if doing an extended ML fit add the signal fraction into the fit parameters if (this->doEMLFit()) { std::cout<<"INFO in LauTimeDepFitModel::setFitNEvents : Initialising number of events for signal and background components..."<addFitParameters( signalEvents_ ); } else { std::cout<<"INFO in LauTimeDepFitModel::setFitNEvents : Initialising number of events for background components (and hence signal)..."<useDP() == kFALSE) { nNormPar_ += this->addFitParameters( signalAsym_ ); } // TODO arguably should delegate this //LauTagCatParamMap& signalTagCatFrac = flavTag_->getSignalTagCatFrac(); // tagging-category fractions for signal events //for (LauTagCatParamMap::iterator iter = signalTagCatFrac.begin(); iter != signalTagCatFrac.end(); ++iter) { // if (iter == signalTagCatFrac.begin()) { // continue; // } // LauParameter* par = &((*iter).second); // fitVars.push_back(par); // ++nNormPar_; //} // Backgrounds if (usingBkgnd_ == kTRUE) { nNormPar_ += this->addFitParameters( bkgndEvents_ ); nNormPar_ += this->addFitParameters( bkgndAsym_ ); } } void LauTimeDepFitModel::setAsymParams() { nAsymPar_ = 0; //Signal nAsymPar_ += this->addFitParameters( &AProd_ ); //Background(s) nAsymPar_ += this->addFitParameters( AProdBkgnd_ ); } void LauTimeDepFitModel::setTagEffParams() { nTagEffPar_ = 0; Bool_t useAltPars = flavTag_->getUseAveDelta(); std::cout << "INFO in LauTimeDepFitModel::setTagEffParams : Setting the initial fit parameters for flavour tagging efficiencies." << std::endl; if (useAltPars){ std::vector tageff_ave = flavTag_->getTagEffAve(); std::vector tageff_delta = flavTag_->getTagEffDelta(); nTagEffPar_ += this->addFitParameters( tageff_ave ); nTagEffPar_ += this->addFitParameters( tageff_delta ); } else { std::vector tageff_b0 = flavTag_->getTagEffB0(); std::vector tageff_b0bar = flavTag_->getTagEffB0bar(); nTagEffPar_ += this->addFitParameters( tageff_b0 ); nTagEffPar_ += this->addFitParameters( tageff_b0bar ); } if (usingBkgnd_){ if (useAltPars){ - std::vector> tageff_ave = flavTag_->getTagEffBkgndAve(); - std::vector> tageff_delta = flavTag_->getTagEffBkgndDelta(); + auto tageff_ave = flavTag_->getTagEffBkgndAve(); + auto tageff_delta = flavTag_->getTagEffBkgndDelta(); for(auto& innerVec : tageff_ave){ nTagEffPar_ += this->addFitParameters( innerVec ); } for(auto& innerVec : tageff_delta){ nTagEffPar_ += this->addFitParameters( innerVec ); } } else { - std::vector> tageff_b0 = flavTag_->getTagEffBkgndB0(); - std::vector> tageff_b0bar = flavTag_->getTagEffBkgndB0bar(); + auto tageff_b0 = flavTag_->getTagEffBkgndB0(); + auto tageff_b0bar = flavTag_->getTagEffBkgndB0bar(); for(auto& innerVec : tageff_b0){ nTagEffPar_ += this->addFitParameters( innerVec ); } for(auto& innerVec : tageff_b0bar){ nTagEffPar_ += this->addFitParameters( innerVec ); } } } } void LauTimeDepFitModel::setCalibParams() { nCalibPar_ = 0; Bool_t useAltPars = flavTag_->getUseAveDelta(); std::cout << "INFO in LauTimeDepFitModel::setCalibParams : Setting the initial fit parameters of the flavour tagging calibration parameters." << std::endl; if (useAltPars){ std::vector p0pars_ave = flavTag_->getCalibP0Ave(); std::vector p0pars_delta = flavTag_->getCalibP0Delta(); std::vector p1pars_ave = flavTag_->getCalibP1Ave(); std::vector p1pars_delta = flavTag_->getCalibP1Delta(); nCalibPar_ += this->addFitParameters( p0pars_ave ); nCalibPar_ += this->addFitParameters( p0pars_delta ); nCalibPar_ += this->addFitParameters( p1pars_ave ); nCalibPar_ += this->addFitParameters( p1pars_delta ); } else { std::vector p0pars_b0 = flavTag_->getCalibP0B0(); std::vector p0pars_b0bar = flavTag_->getCalibP0B0bar(); std::vector p1pars_b0 = flavTag_->getCalibP1B0(); std::vector p1pars_b0bar = flavTag_->getCalibP1B0bar(); nCalibPar_ += this->addFitParameters( p0pars_b0 ); nCalibPar_ += this->addFitParameters( p0pars_b0bar ); nCalibPar_ += this->addFitParameters( p1pars_b0 ); nCalibPar_ += this->addFitParameters( p1pars_b0bar ); } } void LauTimeDepFitModel::setExtraNtupleVars() { // Set-up other parameters derived from the fit results, e.g. fit fractions. if (this->useDP() != kTRUE) { return; } // First clear the vectors so we start from scratch this->clearExtraVarVectors(); LauParameterList& extraVars = this->extraPars(); // Add the B0 and B0bar fit fractions for each signal component fitFracB0bar_ = sigModelB0bar_->getFitFractions(); if (fitFracB0bar_.size() != nSigComp_) { std::cerr<<"ERROR in LauTimeDepFitModel::setExtraNtupleVars : Initial Fit Fraction array of unexpected dimension: "<Exit(EXIT_FAILURE); } for (UInt_t i(0); iExit(EXIT_FAILURE); } } for (UInt_t i(0); igetFitFractions(); if (fitFracB0_.size() != nSigComp_) { std::cerr<<"ERROR in LauTimeDepFitModel::setExtraNtupleVars : Initial Fit Fraction array of unexpected dimension: "<Exit(EXIT_FAILURE); } for (UInt_t i(0); iExit(EXIT_FAILURE); } } for (UInt_t i(0); icalcAsymmetries(kTRUE); // Add the Fit Fraction asymmetry for each signal component for (UInt_t i = 0; i < nSigComp_; i++) { extraVars.push_back(fitFracAsymm_[i]); } // Add the calculated CP asymmetry for each signal component for (UInt_t i = 0; i < nSigComp_; i++) { extraVars.push_back(acp_[i]); } // Now add in the DP efficiency values Double_t initMeanEffB0bar = sigModelB0bar_->getMeanEff().initValue(); meanEffB0bar_.value(initMeanEffB0bar); meanEffB0bar_.initValue(initMeanEffB0bar); meanEffB0bar_.genValue(initMeanEffB0bar); extraVars.push_back(meanEffB0bar_); Double_t initMeanEffB0 = sigModelB0_->getMeanEff().initValue(); meanEffB0_.value(initMeanEffB0); meanEffB0_.initValue(initMeanEffB0); meanEffB0_.genValue(initMeanEffB0); extraVars.push_back(meanEffB0_); // Also add in the DP rates Double_t initDPRateB0bar = sigModelB0bar_->getDPRate().initValue(); DPRateB0bar_.value(initDPRateB0bar); DPRateB0bar_.initValue(initDPRateB0bar); DPRateB0bar_.genValue(initDPRateB0bar); extraVars.push_back(DPRateB0bar_); Double_t initDPRateB0 = sigModelB0_->getDPRate().initValue(); DPRateB0_.value(initDPRateB0); DPRateB0_.initValue(initDPRateB0); DPRateB0_.genValue(initDPRateB0); extraVars.push_back(DPRateB0_); } void LauTimeDepFitModel::setAsymmetries(const Double_t AProd, const Bool_t AProdFix){ AProd_.value(AProd); AProd_.fixed(AProdFix); } void LauTimeDepFitModel::setBkgndAsymmetries(const TString& bkgndClass, const Double_t AProd, const Bool_t AProdFix){ // check that this background name is valid if ( ! this->validBkgndClass( bkgndClass) ) { std::cerr << "ERROR in LauTimeDepFitModel::setBkgndAsymmetries : Invalid background class \"" << bkgndClass << "\"." << std::endl; std::cerr << " : Background class names must be provided in \"setBkgndClassNames\" before any other background-related actions can be performed." << std::endl; return; } UInt_t bkgndID = this->bkgndClassID( bkgndClass ); AProdBkgnd_[bkgndID]->value( AProd ); AProdBkgnd_[bkgndID]->genValue( AProd ); AProdBkgnd_[bkgndID]->initValue( AProd ); AProdBkgnd_[bkgndID]->fixed( AProdFix ); } void LauTimeDepFitModel::finaliseFitResults(const TString& tablePrefixName) { // Retrieve parameters from the fit results for calculations and toy generation // and eventually store these in output root ntuples/text files // Now take the fit parameters and update them as necessary // i.e. to make mag > 0.0, phase in the right range. // This function will also calculate any other values, such as the // fit fractions, using any errors provided by fitParErrors as appropriate. // Also obtain the pull values: (measured - generated)/(average error) if (this->useDP() == kTRUE) { for (UInt_t i = 0; i < nSigComp_; ++i) { // Check whether we have "a > 0.0", and phases in the right range coeffPars_[i]->finaliseValues(); } } // update the pulls on the event fractions and asymmetries if (this->doEMLFit()) { signalEvents_->updatePull(); } if (this->useDP() == kFALSE) { signalAsym_->updatePull(); } // Finalise the pulls on the decay time parameters signalDecayTimePdf_->updatePulls(); // and for backgrounds if required if (usingBkgnd_){ for (auto& pdf : BkgndDecayTimePdfs_){ pdf->updatePulls(); } } if (useSinCos_) { if ( not sinPhiMix_.fixed() ) { sinPhiMix_.updatePull(); cosPhiMix_.updatePull(); } } else { this->checkMixingPhase(); } if (usingBkgnd_ == kTRUE) { for (auto& params : bkgndEvents_){ std::vector parameters = params->getPars(); for ( LauParameter* parameter : parameters ) { parameter->updatePull(); } } for (auto& params : bkgndAsym_){ std::vector parameters = params->getPars(); for ( LauParameter* parameter : parameters ) { parameter->updatePull(); } } } // Update the pulls on all the extra PDFs' parameters this->updateFitParameters(sigExtraPdf_); if (usingBkgnd_ == kTRUE) { for (auto& pdf : BkgndPdfs_){ this->updateFitParameters(pdf); } } // Fill the fit results to the ntuple // update the coefficients and then calculate the fit fractions and ACP's if (this->useDP() == kTRUE) { this->updateCoeffs(); sigModelB0bar_->updateCoeffs(coeffsB0bar_); sigModelB0bar_->calcExtraInfo(); sigModelB0_->updateCoeffs(coeffsB0_); sigModelB0_->calcExtraInfo(); LauParArray fitFracB0bar = sigModelB0bar_->getFitFractions(); if (fitFracB0bar.size() != nSigComp_) { std::cerr<<"ERROR in LauTimeDepFitModel::finaliseFitResults : Fit Fraction array of unexpected dimension: "<Exit(EXIT_FAILURE); } for (UInt_t i(0); iExit(EXIT_FAILURE); } } LauParArray fitFracB0 = sigModelB0_->getFitFractions(); if (fitFracB0.size() != nSigComp_) { std::cerr<<"ERROR in LauTimeDepFitModel::finaliseFitResults : Fit Fraction array of unexpected dimension: "<Exit(EXIT_FAILURE); } for (UInt_t i(0); iExit(EXIT_FAILURE); } } for (UInt_t i(0); igetMeanEff().value()); meanEffB0_.value(sigModelB0_->getMeanEff().value()); DPRateB0bar_.value(sigModelB0bar_->getDPRate().value()); DPRateB0_.value(sigModelB0_->getDPRate().value()); this->calcAsymmetries(); // Then store the final fit parameters, and any extra parameters for // the signal model (e.g. fit fractions, FF asymmetries, ACPs, mean efficiency and DP rate) this->clearExtraVarVectors(); LauParameterList& extraVars = this->extraPars(); for (UInt_t i(0); iprintFitFractions(std::cout); this->printAsymmetries(std::cout); } const LauParameterPList& fitVars = this->fitPars(); const LauParameterList& extraVars = this->extraPars(); LauFitNtuple* ntuple = this->fitNtuple(); ntuple->storeParsAndErrors(fitVars, extraVars); // find out the correlation matrix for the parameters ntuple->storeCorrMatrix(this->iExpt(), this->fitStatus(), this->covarianceMatrix()); // Fill the data into ntuple ntuple->updateFitNtuple(); // Print out the partial fit fractions, phases and the // averaged efficiency, reweighted by the dynamics (and anything else) if (this->writeLatexTable()) { TString sigOutFileName(tablePrefixName); sigOutFileName += "_"; sigOutFileName += this->iExpt(); sigOutFileName += "Expt.tex"; this->writeOutTable(sigOutFileName); } } void LauTimeDepFitModel::printFitFractions(std::ostream& output) { // Print out Fit Fractions, total DP rate and mean efficiency // First for the B0bar events for (UInt_t i = 0; i < nSigComp_; i++) { const TString compName(coeffPars_[i]->name()); output<<"B0bar FitFraction for component "<useDP() == kTRUE) { // print the fit coefficients in one table coeffPars_.front()->printTableHeading(fout); for (UInt_t i = 0; i < nSigComp_; i++) { coeffPars_[i]->printTableRow(fout); } fout<<"\\hline"<name(); resName = resName.ReplaceAll("_", "\\_"); fout< =$ & $"; print.printFormat(fout, meanEffB0bar_.value()); fout << "$ & $"; print.printFormat(fout, meanEffB0_.value()); fout << "$ & & \\\\" << std::endl; if (useSinCos_) { fout << "$\\sinPhiMix =$ & $"; print.printFormat(fout, sinPhiMix_.value()); fout << " \\pm "; print.printFormat(fout, sinPhiMix_.error()); fout << "$ & & & & & & & \\\\" << std::endl; fout << "$\\cosPhiMix =$ & $"; print.printFormat(fout, cosPhiMix_.value()); fout << " \\pm "; print.printFormat(fout, cosPhiMix_.error()); fout << "$ & & & & & & & \\\\" << std::endl; } else { fout << "$\\phiMix =$ & $"; print.printFormat(fout, phiMix_.value()); fout << " \\pm "; print.printFormat(fout, phiMix_.error()); fout << "$ & & & & & & & \\\\" << std::endl; } fout << "\\hline \n\\end{tabular}" << std::endl; } if (!sigExtraPdf_.empty()) { fout<<"\\begin{tabular}{|l|c|}"<printFitParameters(sigExtraPdf_, fout); if (usingBkgnd_ == kTRUE && !BkgndPdfs_.empty()) { fout << "\\hline" << std::endl; fout << "\\Extra Background PDFs' Parameters: & \\\\" << std::endl; for (auto& pdf : BkgndPdfs_){ this->printFitParameters(pdf, fout); } } fout<<"\\hline \n\\end{tabular}"<updateSigEvents(); // Check whether we want to have randomised initial fit parameters for the signal model if (this->useRandomInitFitPars() == kTRUE) { this->randomiseInitFitPars(); } } void LauTimeDepFitModel::randomiseInitFitPars() { // Only randomise those parameters that are not fixed! std::cout<<"INFO in LauTimeDepFitModel::randomiseInitFitPars : Randomising the initial values of the coefficients of the DP components (and phiMix)..."<randomiseInitValues(); } phiMix_.randomiseValue(-LauConstants::pi, LauConstants::pi); if (useSinCos_) { sinPhiMix_.initValue(TMath::Sin(phiMix_.initValue())); cosPhiMix_.initValue(TMath::Cos(phiMix_.initValue())); } } LauTimeDepFitModel::LauGenInfo LauTimeDepFitModel::eventsToGenerate() { // Determine the number of events to generate for each hypothesis // If we're smearing then smear each one individually // NB this individual smearing has to be done individually per tagging category as well LauGenInfo nEvtsGen; // Signal // If we're including the DP and decay time we can't decide on the tag // yet, since it depends on the whole DP+dt PDF, however, if // we're not then we need to decide. Double_t evtWeight(1.0); Double_t nEvts = signalEvents_->genValue(); if ( nEvts < 0.0 ) { evtWeight = -1.0; nEvts = TMath::Abs( nEvts ); } //TOD sigAysm doesn't do anything here? Double_t sigAsym(0.0); if (this->useDP() == kFALSE) { sigAsym = signalAsym_->genValue(); //TODO fill in here if we care } else { Double_t rateB0bar = sigModelB0bar_->getDPRate().value(); Double_t rateB0 = sigModelB0_->getDPRate().value(); if ( rateB0bar+rateB0 > 1e-30) { sigAsym = (rateB0bar-rateB0)/(rateB0bar+rateB0); } //for (LauTagCatParamMap::const_iterator iter = signalTagCatFrac.begin(); iter != signalTagCatFrac.end(); ++iter) { // const LauParameter& par = iter->second; // Double_t eventsbyTagCat = par.value() * nEvts; // if (this->doPoissonSmearing()) { // eventsbyTagCat = LauRandom::randomFun()->Poisson(eventsbyTagCat); // } // eventsB0[iter->first] = std::make_pair( TMath::Nint(eventsbyTagCat), evtWeight ); //} //nEvtsGen[std::make_pair("signal",0)] = eventsB0; // generate signal event, decide tag later. if (this->doPoissonSmearing()) { nEvts = LauRandom::randomFun()->Poisson(signalEvents_->genValue()); } nEvtsGen["signal"] = std::make_pair( nEvts, evtWeight ); } std::cout<<"INFO in LauTimeDepFitModel::eventsToGenerate : Generating toy MC with:"<bkgndClassName(bkgndID)<<" background events = "<genValue()<eventsToGenerate(); Bool_t genOK(kTRUE); Int_t evtNum(0); const UInt_t nBkgnds = this->nBkgndClasses(); std::vector bkgndClassNames(nBkgnds); std::vector bkgndClassNamesGen(nBkgnds); for ( UInt_t iBkgnd(0); iBkgnd < nBkgnds; ++iBkgnd ) { TString name( this->bkgndClassName(iBkgnd) ); bkgndClassNames[iBkgnd] = name; bkgndClassNamesGen[iBkgnd] = "gen"+name; } // Loop over the hypotheses and generate the appropriate number of // events for each one for (auto& hypo : nEvts){ // find the category of events (e.g. signal) const TString& evtCategory(hypo.first); // Type const TString& type(hypo.first); // Number of events Int_t nEvtsGen( hypo.second.first ); // get the event weight for this category const Double_t evtWeight( hypo.second.second ); for (Int_t iEvt(0); iEvtsetGenNtupleDoubleBranchValue( "evtWeight", evtWeight ); if (evtCategory == "signal") { this->setGenNtupleIntegerBranchValue("genSig",1); for ( UInt_t iBkgnd(0); iBkgnd < nBkgnds; ++iBkgnd ) { this->setGenNtupleIntegerBranchValue( bkgndClassNamesGen[iBkgnd], 0 ); } // All the generate*Event() methods have to fill in curEvtDecayTime_ and curEvtDecayTimeErr_ // In addition, generateSignalEvent has to decide on the tag and fill in curEvtTagFlv_ genOK = this->generateSignalEvent(); } else { this->setGenNtupleIntegerBranchValue("genSig",0); UInt_t bkgndID(0); for ( UInt_t iBkgnd(0); iBkgnd < nBkgnds; ++iBkgnd ) { Int_t gen(0); if ( bkgndClassNames[iBkgnd] == type ) { gen = 1; bkgndID = iBkgnd; } this->setGenNtupleIntegerBranchValue( bkgndClassNamesGen[iBkgnd], gen ); } genOK = this->generateBkgndEvent(bkgndID); } if (!genOK) { // If there was a problem with the generation then break out and return. // The problem model will have adjusted itself so that all should be OK next time. break; } if (this->useDP() == kTRUE) { this->setDPDtBranchValues(); // store DP, decay time and tagging variables in the ntuple } // Store the event's tag and tagging category this->setGenNtupleIntegerBranchValue("cpEigenvalue", cpEigenValue_); const TString& trueTagVarName { flavTag_->getTrueTagVarName() }; if ( trueTagVarName != "" ) { this->setGenNtupleIntegerBranchValue(trueTagVarName, curEvtTrueTagFlv_); } if ( cpEigenValue_ == QFS ) { const TString& decayFlvVarName { flavTag_->getDecayFlvVarName() }; if ( decayFlvVarName == "" ) { std::cerr<<"ERROR in LauTimeDepFitModel::genExpt : Decay flavour variable not set for QFS decay, see LauFlavTag::setDecayFlvVarName()."<Exit(EXIT_FAILURE); } else { this->setGenNtupleIntegerBranchValue(decayFlvVarName, curEvtDecayFlv_); } } const std::vector& tagVarNames { flavTag_->getTagVarNames() }; const std::vector& mistagVarNames { flavTag_->getMistagVarNames() }; // Loop over the taggers - values set via generateSignalEvent - const ULong_t nTaggers {flavTag_->getNTaggers()}; - for (ULong_t i=0; igetNTaggers()}; + for (std::size_t i=0; isetGenNtupleIntegerBranchValue(tagVarNames[i], curEvtTagFlv_[i]); this->setGenNtupleDoubleBranchValue(mistagVarNames[i], curEvtMistag_[i]); } // Store the event number (within this experiment) // and then increment it this->setGenNtupleIntegerBranchValue("iEvtWithinExpt",evtNum); ++evtNum; // Write the values into the tree this->fillGenNtupleBranches(); // Print an occasional progress message if (iEvt%1000 == 0) {std::cout<<"INFO in LauTimeDepFitModel::genExpt : Generated event number "<useDP() && genOK) { sigModelB0bar_->checkToyMC(kTRUE); sigModelB0_->checkToyMC(kTRUE); std::cout<<"aSqMaxSet = "<Exit(EXIT_FAILURE); } for (UInt_t i(0); iExit(EXIT_FAILURE); } } LauParArray fitFracB0 = sigModelB0_->getFitFractions(); if (fitFracB0.size() != nSigComp_) { std::cerr<<"ERROR in LauTimeDepFitModel::generate : Fit Fraction array of unexpected dimension: "<Exit(EXIT_FAILURE); } for (UInt_t i(0); iExit(EXIT_FAILURE); } } for (UInt_t i(0); igetMeanEff().value()); meanEffB0_.value(sigModelB0_->getMeanEff().value()); DPRateB0bar_.value(sigModelB0bar_->getDPRate().value()); DPRateB0_.value(sigModelB0_->getDPRate().value()); } } // If we're reusing embedded events or if the generation is being // reset then clear the lists of used events if (reuseSignal_ || !genOK) { if (signalTree_) { signalTree_->clearUsedList(); } } for ( UInt_t bkgndID(0); bkgndID < nBkgnds; ++bkgndID ) { LauEmbeddedData* data = bkgndTree_[bkgndID]; if (reuseBkgnd_[bkgndID] || !genOK) { if (data) { data->clearUsedList(); } } } return genOK; } Bool_t LauTimeDepFitModel::generateSignalEvent() { // Generate signal event, including SCF if necessary. // DP:DecayTime generation follows. // If it's ok, we then generate mES, DeltaE, Fisher/NN... Bool_t genOK(kTRUE); Bool_t generatedEvent(kFALSE); Bool_t doSquareDP = kinematicsB0bar_->squareDP(); doSquareDP &= kinematicsB0_->squareDP(); LauKinematics* kinematics(kinematicsB0bar_); if (this->useDP()) { if (signalTree_) { signalTree_->getEmbeddedEvent(kinematics); //curEvtTagFlv_ = TMath::Nint(signalTree_->getValue("tagFlv")); curEvtDecayTimeErr_ = signalTree_->getValue(signalDecayTimePdf_->varErrName()); curEvtDecayTime_ = signalTree_->getValue(signalDecayTimePdf_->varName()); if (signalTree_->haveBranch("mcMatch")) { Int_t match = TMath::Nint(signalTree_->getValue("mcMatch")); if (match) { this->setGenNtupleIntegerBranchValue("genTMSig",1); this->setGenNtupleIntegerBranchValue("genSCFSig",0); } else { this->setGenNtupleIntegerBranchValue("genTMSig",0); this->setGenNtupleIntegerBranchValue("genSCFSig",1); } } } else { nGenLoop_ = 0; // Now generate from the combined DP / decay-time PDF while (generatedEvent == kFALSE && nGenLoop_ < iterationsMax_) { curEvtTrueTagFlv_ = LauFlavTag::Flavour::Unknown; curEvtDecayFlv_ = LauFlavTag::Flavour::Unknown; // First choose the true tag, accounting for the production asymmetry // CONVENTION WARNING regarding meaning of sign of AProd Double_t random = LauRandom::randomFun()->Rndm(); if (random <= 0.5 * ( 1.0 - AProd_.unblindValue() ) ) { curEvtTrueTagFlv_ = LauFlavTag::Flavour::B; } else { curEvtTrueTagFlv_ = LauFlavTag::Flavour::Bbar; } // Generate the DP position Double_t m13Sq{0.0}, m23Sq{0.0}; kinematicsB0bar_->genFlatPhaseSpace(m13Sq, m23Sq); // Next, calculate the total A and Abar for the given DP position sigModelB0_->calcLikelihoodInfo(m13Sq, m23Sq); sigModelB0bar_->calcLikelihoodInfo(m13Sq, m23Sq); // Generate decay time const Double_t tMin = signalDecayTimePdf_->minAbscissa(); const Double_t tMax = signalDecayTimePdf_->maxAbscissa(); curEvtDecayTime_ = LauRandom::randomFun()->Uniform(tMin,tMax); // Generate the decay time error (NB the kTRUE forces the generation of a new value) curEvtDecayTimeErr_ = signalDecayTimePdf_->generateError(kTRUE); // Calculate all the decay time info signalDecayTimePdf_->calcLikelihoodInfo(curEvtDecayTime_,curEvtDecayTimeErr_); // Retrieve the amplitudes and efficiency from the dynamics const LauComplex& Abar { sigModelB0bar_->getEvtDPAmp() }; const LauComplex& A { sigModelB0_->getEvtDPAmp() }; const Double_t ASq { A.abs2() }; const Double_t AbarSq { Abar.abs2() }; const Double_t dpEff { sigModelB0bar_->getEvtEff() }; // Also retrieve all the decay time terms const Double_t dtCos { signalDecayTimePdf_->getCosTerm() }; const Double_t dtSin { signalDecayTimePdf_->getSinTerm() }; const Double_t dtCosh { signalDecayTimePdf_->getCoshTerm() }; const Double_t dtSinh { signalDecayTimePdf_->getSinhTerm() }; // and the decay time acceptance const Double_t dtEff { signalDecayTimePdf_->getEffiTerm() }; if ( cpEigenValue_ == QFS) { // Calculate the total intensities for each flavour-specific final state const Double_t ATotSq { ( ASq * dtCosh + curEvtTrueTagFlv_ * ASq * dtCos ) * dpEff * dtEff }; const Double_t AbarTotSq { ( AbarSq * dtCosh - curEvtTrueTagFlv_ * AbarSq * dtCos ) * dpEff * dtEff }; const Double_t ASumSq { ATotSq + AbarTotSq }; // Finally we throw the dice to see whether this event should be generated (and, if so, which final state) const Double_t randNum = LauRandom::randomFun()->Rndm(); if (randNum <= ASumSq / aSqMaxSet_ ) { generatedEvent = kTRUE; nGenLoop_ = 0; if (ASumSq > aSqMaxVar_) {aSqMaxVar_ = ASumSq;} if ( randNum <= ATotSq / aSqMaxSet_ ) { curEvtDecayFlv_ = LauFlavTag::Flavour::B; } else { curEvtDecayFlv_ = LauFlavTag::Flavour::Bbar; } // Generate the flavour tagging information from the true tag // (we do this after accepting the event to save time) flavTag_->generateEventInfo( curEvtTrueTagFlv_, curEvtDecayTime_ ); curEvtTagFlv_ = flavTag_->getCurEvtTagFlv(); curEvtMistag_ = flavTag_->getCurEvtMistag(); } else { nGenLoop_++; } } else { // Calculate the DP terms const Double_t aSqSum { ASq + AbarSq }; const Double_t aSqDif { ASq - AbarSq }; const LauComplex inter { Abar * A.conj() * phiMixComplex_ }; const Double_t interTermIm { ( cpEigenValue_ == CPEven ) ? 2.0 * inter.im() : -2.0 * inter.im() }; const Double_t interTermRe { ( cpEigenValue_ == CPEven ) ? 2.0 * inter.re() : -2.0 * inter.re() }; // Combine DP and decay-time info for all terms const Double_t coshTerm { aSqSum * dtCosh }; const Double_t sinhTerm { interTermRe * dtSinh }; const Double_t cosTerm { aSqDif * dtCos }; const Double_t sinTerm { interTermIm * dtSin }; // Sum to obtain the total and multiply by the efficiency // Multiplying the cos and sin terms by the true flavour at production const Double_t ATotSq { ( coshTerm + sinhTerm + curEvtTrueTagFlv_ * ( cosTerm - sinTerm ) ) * dpEff * dtEff }; //Finally we throw the dice to see whether this event should be generated const Double_t randNum = LauRandom::randomFun()->Rndm(); if (randNum <= ATotSq/aSqMaxSet_ ) { generatedEvent = kTRUE; nGenLoop_ = 0; if (ATotSq > aSqMaxVar_) {aSqMaxVar_ = ATotSq;} // Generate the flavour tagging information from the true tag // (we do this after accepting the event to save time) flavTag_->generateEventInfo( curEvtTrueTagFlv_, curEvtDecayTime_ ); curEvtTagFlv_ = flavTag_->getCurEvtTagFlv(); curEvtMistag_ = flavTag_->getCurEvtMistag(); } else { nGenLoop_++; } } } // end of while !generatedEvent loop } // end of if (signalTree_) else control } else { if ( signalTree_ ) { signalTree_->getEmbeddedEvent(0); //curEvtTagFlv_ = TMath::Nint(signalTree_->getValue("tagFlv")); curEvtDecayTimeErr_ = signalTree_->getValue(signalDecayTimePdf_->varErrName()); curEvtDecayTime_ = signalTree_->getValue(signalDecayTimePdf_->varName()); } } // Check whether we have generated the toy MC OK. if (nGenLoop_ >= iterationsMax_) { aSqMaxSet_ = 1.01 * aSqMaxVar_; genOK = kFALSE; std::cerr<<"WARNING in LauTimeDepFitModel::generateSignalEvent : Hit max iterations: setting aSqMaxSet_ to "< aSqMaxSet_) { aSqMaxSet_ = 1.01 * aSqMaxVar_; genOK = kFALSE; std::cerr<<"WARNING in LauTimeDepFitModel::generateSignalEvent : Found a larger ASq value: setting aSqMaxSet_ to "<updateKinematics(kinematicsB0bar_->getm13Sq(), kinematicsB0bar_->getm23Sq() ); this->generateExtraPdfValues(sigExtraPdf_, signalTree_); } // Check for problems with the embedding if (signalTree_ && (signalTree_->nEvents() == signalTree_->nUsedEvents())) { std::cerr<<"WARNING in LauTimeDepFitModel::generateSignalEvent : Source of embedded signal events used up, clearing the list of used events."<clearUsedList(); } return genOK; } Bool_t LauTimeDepFitModel::generateBkgndEvent(UInt_t bkgndID) { // Generate Bkgnd event Bool_t genOK{kTRUE}; //Check necessary ingredients are in place //TODO these checks should be part of a general sanity check during the initialisation phase if (BkgndDPModelsB_[bkgndID] == nullptr){ std::cerr << "ERROR in LauTimeDepFitModel::generateBkgndEvent : Dalitz plot model is missing" << std::endl; gSystem->Exit(EXIT_FAILURE); } if (BkgndDecayTimePdfs_[bkgndID] == nullptr){ std::cerr << "ERROR in LauTimeDepFitModel::generateBkgndEvent : Decay time model is missing" << std::endl; gSystem->Exit(EXIT_FAILURE); } //TODO restore the ability to embed events from an external source //LauAbsBkgndDPModel* model(0); //LauEmbeddedData* embeddedData(0); //LauPdfPList* extraPdfs(0); //LauKinematics* kinematics(0); //model = BkgndDPModels_[bkgndID]; //if (this->enableEmbedding()) { // // find the right embedded data for the current tagging category // LauTagCatEmbDataMap::const_iterator emb_iter = bkgndTree_[bkgndID].find(curEvtTagCat_); // embeddedData = (emb_iter != bkgndTree_[bkgndID].end()) ? emb_iter->second : 0; //} //extraPdfs = &BkgndPdfs_[bkgndID]; //kinematics = kinematicsB0bar_; //if (this->useDP()) { // if (embeddedData) { // embeddedData->getEmbeddedEvent(kinematics); // } else { // if (model == 0) { // const TString& bkgndClass = this->bkgndClassName(bkgndID); // std::cerr << "ERROR in LauCPFitModel::generateBkgndEvent : Can't find the DP model for background class \"" << bkgndClass << "\"." << std::endl; // gSystem->Exit(EXIT_FAILURE); // } // genOK = model->generate(); // } //} else { // if (embeddedData) { // embeddedData->getEmbeddedEvent(0); // } //} //if (genOK) { // this->generateExtraPdfValues(extraPdfs, embeddedData); //} //// Check for problems with the embedding //if (embeddedData && (embeddedData->nEvents() == embeddedData->nUsedEvents())) { // const TString& bkgndClass = this->bkgndClassName(bkgndID); // std::cerr << "WARNING in LauCPFitModel::generateBkgndEvent : Source of embedded " << bkgndClass << " events used up, clearing the list of used events." << std::endl; // embeddedData->clearUsedList(); //} // switch ( BkgndTypes_[bkgndID] ) { case LauFlavTag::BkgndType::Combinatorial: { - - // This doesn't really mean anything for combinatorial background - // TODO But maybe we need some sort of asymmetry parameter here? + // First choose the true tag, accounting for the production asymmetry + // CONVENTION WARNING regarding meaning of sign of AProd + // NB the true tag doesn't really mean anything for combinatorial background Double_t random = LauRandom::randomFun()->Rndm(); - if ( random <= 0.5 ) { + if ( random <= 0.5 * ( 1.0 - AProdBkgnd_[bkgndID]->unblindValue() ) ) { curEvtTrueTagFlv_ = LauFlavTag::Flavour::B; } else { curEvtTrueTagFlv_ = LauFlavTag::Flavour::Bbar; } - // generate the true decay flavour - again this doesn't make much sense for combinatorial so we just flip a coin - // TODO - we maybe need an asymmetry parameter here as well? + LauKinematics* kinematics { kinematicsB0_ }; + if ( cpEigenValue_ == CPEigenvalue::QFS ) { - if (random <= 0.5 ) { - curEvtDecayFlv_ = LauFlavTag::Flavour::B; + if ( BkgndDPModelsBbar_[bkgndID] != nullptr ) { + // generate the true decay flavour and the corresponding DP position + // (the supply of two DP models indicates a possible asymmetry) + const Double_t rateB { BkgndDPModelsB_[bkgndID]->getPdfNorm() }; + const Double_t rateBbar { BkgndDPModelsBbar_[bkgndID]->getPdfNorm() }; + const Double_t ADet { ( rateBbar - rateB ) / ( rateBbar + rateB ) }; + random = LauRandom::randomFun()->Rndm(); + if ( random <= 0.5 * ( 1.0 - ADet ) ) { + curEvtDecayFlv_ = LauFlavTag::Flavour::B; + BkgndDPModelsB_[bkgndID]->generate(); + kinematics = kinematicsB0_; + } else { + curEvtDecayFlv_ = LauFlavTag::Flavour::Bbar; + BkgndDPModelsBbar_[bkgndID]->generate(); + kinematics = kinematicsB0bar_; + } } else { - curEvtDecayFlv_ = LauFlavTag::Flavour::Bbar; + // generate the true decay flavour + // (the supply of only a single model indicates no asymmetry) + random = LauRandom::randomFun()->Rndm(); + if ( random <= 0.5 ) { + curEvtDecayFlv_ = LauFlavTag::Flavour::B; + } else { + curEvtDecayFlv_ = LauFlavTag::Flavour::Bbar; + } + + // generate the DP position + BkgndDPModelsB_[bkgndID]->generate(); } - } + } else { + // mark that the decay flavour is unknown + curEvtDecayFlv_ = LauFlavTag::Flavour::Unknown; - // generate the DP position - BkgndDPModelsB_[bkgndID]->generate(); + // generate the DP position + BkgndDPModelsB_[bkgndID]->generate(); + } // generate decay time and its error curEvtDecayTimeErr_ = BkgndDecayTimePdfs_[bkgndID]->generateError(kTRUE); - curEvtDecayTime_ = BkgndDecayTimePdfs_[bkgndID]->generate( kinematicsB0_ ); + curEvtDecayTime_ = BkgndDecayTimePdfs_[bkgndID]->generate( kinematics ); - // generate the flavour tagging response - flavTag_->generateBkgndEventInfo( bkgndID, curEvtTrueTagFlv_, curEvtDecayTime_ ); + // generate the flavour tagging information from the true tag and decay flavour + // (we do this after accepting the event to save time) + flavTag_->generateBkgndEventInfo( bkgndID, curEvtTrueTagFlv_, curEvtDecayFlv_, curEvtDecayTime_ ); curEvtTagFlv_ = flavTag_->getCurEvtTagFlv(); curEvtMistag_ = flavTag_->getCurEvtMistag(); break; } case LauFlavTag::BkgndType::FlavourSpecific: { const LauDecayTime::FuncType dtType { BkgndDecayTimePdfs_[bkgndID]->getFuncType() }; if ( dtType == LauDecayTime::FuncType::ExpTrig or dtType == LauDecayTime::FuncType::ExpHypTrig ) { nGenLoop_ = 0; Bool_t generatedEvent{kFALSE}; do { curEvtTrueTagFlv_ = LauFlavTag::Flavour::Unknown; curEvtDecayFlv_ = LauFlavTag::Flavour::Unknown; // First choose the true tag, accounting for the production asymmetry // CONVENTION WARNING regarding meaning of sign of AProd Double_t random = LauRandom::randomFun()->Rndm(); if (random <= 0.5 * ( 1.0 - AProdBkgnd_[bkgndID]->unblindValue() ) ) { curEvtTrueTagFlv_ = LauFlavTag::Flavour::B; } else { curEvtTrueTagFlv_ = LauFlavTag::Flavour::Bbar; } // Generate the DP position Double_t m13Sq{0.0}, m23Sq{0.0}; kinematicsB0bar_->genFlatPhaseSpace(m13Sq, m23Sq); // Next, calculate the total A^2 and Abar^2 for the given DP position BkgndDPModelsB_[bkgndID]->calcLikelihoodInfo(m13Sq, m23Sq); BkgndDPModelsBbar_[bkgndID]->calcLikelihoodInfo(m13Sq, m23Sq); // Generate decay time const Double_t tMin = BkgndDecayTimePdfs_[bkgndID]->minAbscissa(); const Double_t tMax = BkgndDecayTimePdfs_[bkgndID]->maxAbscissa(); curEvtDecayTime_ = LauRandom::randomFun()->Uniform(tMin,tMax); // Generate the decay time error (NB the kTRUE forces the generation of a new value) curEvtDecayTimeErr_ = BkgndDecayTimePdfs_[bkgndID]->generateError(kTRUE); // Calculate all the decay time info BkgndDecayTimePdfs_[bkgndID]->calcLikelihoodInfo(curEvtDecayTime_,curEvtDecayTimeErr_); // Retrieve the DP intensities const Double_t ASq { BkgndDPModelsB_[bkgndID]->getUnNormValue() }; const Double_t AbarSq { BkgndDPModelsBbar_[bkgndID]->getUnNormValue() }; // Also retrieve all the decay time terms const Double_t dtCos { BkgndDecayTimePdfs_[bkgndID]->getCosTerm() }; const Double_t dtCosh { BkgndDecayTimePdfs_[bkgndID]->getCoshTerm() }; // and the decay time acceptance const Double_t dtEff { BkgndDecayTimePdfs_[bkgndID]->getEffiTerm() }; + // TODO - I think actually we should always generate FlavourSpecific background as per this QFS section, regardless of the type of the signal + // - the else section is essentially identical anyway, you just loose the MC truth info on the decay flavour if ( cpEigenValue_ == QFS) { // Calculate the total intensities for each flavour-specific final state const Double_t ATotSq { ( ASq * dtCosh + curEvtTrueTagFlv_ * ASq * dtCos ) * dtEff }; const Double_t AbarTotSq { ( AbarSq * dtCosh - curEvtTrueTagFlv_ * AbarSq * dtCos ) * dtEff }; const Double_t ASumSq { ATotSq + AbarTotSq }; // TODO - check if this really is the max possible const Double_t ASumSqMax { 2.0 * ( BkgndDPModelsB_[bkgndID]->getMaxHeight() + BkgndDPModelsBbar_[bkgndID]->getMaxHeight() ) }; // Finally we throw the dice to see whether this event should be generated (and, if so, which final state) const Double_t randNum = LauRandom::randomFun()->Rndm(); if (randNum <= ASumSq / ASumSqMax ) { generatedEvent = kTRUE; nGenLoop_ = 0; if (ASumSq > ASumSqMax) { std::cerr << "WARNING in LauTimeDepFitModel::generateBkgndEvent : ASumSq > ASumSqMax" << std::endl; } if ( randNum <= ATotSq / ASumSqMax ) { curEvtDecayFlv_ = LauFlavTag::Flavour::B; } else { curEvtDecayFlv_ = LauFlavTag::Flavour::Bbar; } - // Generate the flavour tagging information from the true tag + // Generate the flavour tagging information from the true tag and decay flavour // (we do this after accepting the event to save time) - flavTag_->generateBkgndEventInfo( bkgndID, curEvtTrueTagFlv_, curEvtDecayTime_ ); + flavTag_->generateBkgndEventInfo( bkgndID, curEvtTrueTagFlv_, curEvtDecayFlv_, curEvtDecayTime_ ); curEvtTagFlv_ = flavTag_->getCurEvtTagFlv(); curEvtMistag_ = flavTag_->getCurEvtMistag(); } else { nGenLoop_++; } } else { // Calculate the DP terms const Double_t aSqSum { ASq + AbarSq }; const Double_t aSqDif { ASq - AbarSq }; // Combine DP and decay-time info for all terms const Double_t coshTerm { aSqSum * dtCosh }; const Double_t cosTerm { aSqDif * dtCos }; // Sum to obtain the total and multiply by the efficiency // Multiplying the cos term by the true flavour at production const Double_t ATotSq { ( coshTerm + curEvtTrueTagFlv_ * cosTerm ) * dtEff }; // TODO - check if this really is the max possible const Double_t ATotSqMax { 2.0 * TMath::Max( BkgndDPModelsB_[bkgndID]->getMaxHeight(), BkgndDPModelsBbar_[bkgndID]->getMaxHeight() ) }; // Finally we throw the dice to see whether this event should be generated const Double_t randNum = LauRandom::randomFun()->Rndm(); if (randNum <= ATotSq/ATotSqMax ) { generatedEvent = kTRUE; nGenLoop_ = 0; if (ATotSq > ATotSqMax) { // TODO std::cerr << "WARNING in LauTimeDepFitModel::generateBkgndEvent : ATotSq > ATotSqMax" << std::endl; } - // Generate the flavour tagging information from the true tag + // Generate the flavour tagging information from the true tag and decay flavour // (we do this after accepting the event to save time) - flavTag_->generateBkgndEventInfo( bkgndID, curEvtTrueTagFlv_, curEvtDecayTime_ ); + flavTag_->generateBkgndEventInfo( bkgndID, curEvtTrueTagFlv_, curEvtDecayFlv_, curEvtDecayTime_ ); curEvtTagFlv_ = flavTag_->getCurEvtTagFlv(); curEvtMistag_ = flavTag_->getCurEvtMistag(); } else { nGenLoop_++; } } } while (generatedEvent == kFALSE && nGenLoop_ < iterationsMax_); } else { // Hist, Delta, Exp, DeltaExp decay-time types - // First choose the true tag, accounting for the production asymmetry - // CONVENTION WARNING regarding meaning of sign of AProd - Double_t random = LauRandom::randomFun()->Rndm(); - if (random <= 0.5 * ( 1.0 - AProdBkgnd_[bkgndID]->unblindValue() ) ) { - curEvtTrueTagFlv_ = LauFlavTag::Flavour::B; - } else { - curEvtTrueTagFlv_ = LauFlavTag::Flavour::Bbar; - } - // Since there are no oscillations for these decay-time types, // the true decay flavour must be equal to the true tag flavour - curEvtDecayFlv_ = curEvtTrueTagFlv_; + + // First choose the true tag and decay flavour, accounting for both the production and detection asymmetries + // CONVENTION WARNING regarding meaning of sign of AProd and ADet + + const Double_t AProd { AProdBkgnd_[bkgndID]->unblindValue() }; + + const Double_t rateB { BkgndDPModelsB_[bkgndID]->getPdfNorm() }; + const Double_t rateBbar { BkgndDPModelsBbar_[bkgndID]->getPdfNorm() }; + const Double_t ADet { ( rateBbar - rateB ) / ( rateBbar + rateB ) }; + + const Double_t random = LauRandom::randomFun()->Rndm(); + // TODO - is this the correct way to combine the production and detection asymmetries? + if ( random <= 0.5 * ( 1.0 - AProd ) * ( 1.0 - ADet ) ) { + curEvtDecayFlv_ = curEvtTrueTagFlv_ = LauFlavTag::Flavour::B; + } else { + curEvtDecayFlv_ = curEvtTrueTagFlv_ = LauFlavTag::Flavour::Bbar; + } // generate the DP position + LauKinematics* kinematics{nullptr}; if ( curEvtDecayFlv_ == LauFlavTag::Flavour::B ) { BkgndDPModelsB_[bkgndID]->generate(); + kinematics = kinematicsB0_; } else { BkgndDPModelsBbar_[bkgndID]->generate(); + kinematics = kinematicsB0bar_; } // generate decay time and its error - const LauKinematics* kinematics { ( curEvtDecayFlv_ == LauFlavTag::Flavour::B ) ? kinematicsB0_ : kinematicsB0bar_ }; curEvtDecayTimeErr_ = BkgndDecayTimePdfs_[bkgndID]->generateError(kTRUE); curEvtDecayTime_ = BkgndDecayTimePdfs_[bkgndID]->generate( kinematics ); - // generate the flavour tagging response - flavTag_->generateBkgndEventInfo( bkgndID, curEvtTrueTagFlv_, curEvtDecayTime_ ); + // generate the flavour tagging information from the true tag and decay flavour + // (we do this after accepting the event to save time) + flavTag_->generateBkgndEventInfo( bkgndID, curEvtTrueTagFlv_, curEvtDecayFlv_, curEvtDecayTime_ ); curEvtTagFlv_ = flavTag_->getCurEvtTagFlv(); curEvtMistag_ = flavTag_->getCurEvtMistag(); } break; } case LauFlavTag::BkgndType::SelfConjugate: // TODO break; case LauFlavTag::BkgndType::NonSelfConjugate: // TODO break; } return genOK; } void LauTimeDepFitModel::setupGenNtupleBranches() { // Setup the required ntuple branches this->addGenNtupleDoubleBranch("evtWeight"); this->addGenNtupleIntegerBranch("genSig"); this->addGenNtupleIntegerBranch("cpEigenvalue"); const TString& trueTagVarName { flavTag_->getTrueTagVarName() }; if ( trueTagVarName != "" ) { this->addGenNtupleIntegerBranch(trueTagVarName); } if ( cpEigenValue_ == QFS ) { const TString& decayFlvVarName { flavTag_->getDecayFlvVarName() }; if ( decayFlvVarName == "" ) { std::cerr<<"ERROR in LauTimeDepFitModel::setupGenNtupleBranches : Decay flavour variable not set for QFS decay, see LauFlavTag::setDecayFlvVarName()."<Exit(EXIT_FAILURE); } else { this->addGenNtupleIntegerBranch(decayFlvVarName); } } const std::vector& tagVarNames { flavTag_->getTagVarNames() }; const std::vector& mistagVarNames { flavTag_->getMistagVarNames() }; - const ULong_t nTaggers {flavTag_->getNTaggers()}; - for (ULong_t position{0}; positionaddGenNtupleIntegerBranch(tagVarNames[position]); - this->addGenNtupleDoubleBranch(mistagVarNames[position]); + const std::size_t nTaggers {flavTag_->getNTaggers()}; + for (std::size_t taggerID{0}; taggerIDaddGenNtupleIntegerBranch(tagVarNames[taggerID]); + this->addGenNtupleDoubleBranch(mistagVarNames[taggerID]); } if (this->useDP() == kTRUE) { // Let's add the decay time variables. this->addGenNtupleDoubleBranch(signalDecayTimePdf_->varName()); if ( signalDecayTimePdf_->varErrName() != "" ) { this->addGenNtupleDoubleBranch(signalDecayTimePdf_->varErrName()); } this->addGenNtupleDoubleBranch("m12"); this->addGenNtupleDoubleBranch("m23"); this->addGenNtupleDoubleBranch("m13"); this->addGenNtupleDoubleBranch("m12Sq"); this->addGenNtupleDoubleBranch("m23Sq"); this->addGenNtupleDoubleBranch("m13Sq"); this->addGenNtupleDoubleBranch("cosHel12"); this->addGenNtupleDoubleBranch("cosHel23"); this->addGenNtupleDoubleBranch("cosHel13"); if (kinematicsB0bar_->squareDP() && kinematicsB0_->squareDP()) { this->addGenNtupleDoubleBranch("mPrime"); this->addGenNtupleDoubleBranch("thPrime"); } // Can add the real and imaginary parts of the B0 and B0bar total // amplitudes seen in the generation (restrict this with a flag // that defaults to false) if ( storeGenAmpInfo_ ) { this->addGenNtupleDoubleBranch("reB0Amp"); this->addGenNtupleDoubleBranch("imB0Amp"); this->addGenNtupleDoubleBranch("reB0barAmp"); this->addGenNtupleDoubleBranch("imB0barAmp"); } } // Let's look at the extra variables for signal in one of the tagging categories for ( const LauAbsPdf* pdf : sigExtraPdf_ ) { const std::vector varNames{ pdf->varNames() }; for ( const TString& varName : varNames ) { if ( varName != "m13Sq" && varName != "m23Sq" ) { this->addGenNtupleDoubleBranch( varName ); } } } } void LauTimeDepFitModel::setDPDtBranchValues() { // Store the decay time variables. this->setGenNtupleDoubleBranchValue(signalDecayTimePdf_->varName(),curEvtDecayTime_); if ( signalDecayTimePdf_->varErrName() != "" ) { this->setGenNtupleDoubleBranchValue(signalDecayTimePdf_->varErrName(),curEvtDecayTimeErr_); } // CONVENTION WARNING // TODO check - for now use B0 for any tags //LauKinematics* kinematics(0); //if (curEvtTagFlv_[position]<0) { LauKinematics* kinematics = kinematicsB0_; //} else { // kinematics = kinematicsB0bar_; //} // Store all the DP information this->setGenNtupleDoubleBranchValue("m12", kinematics->getm12()); this->setGenNtupleDoubleBranchValue("m23", kinematics->getm23()); this->setGenNtupleDoubleBranchValue("m13", kinematics->getm13()); this->setGenNtupleDoubleBranchValue("m12Sq", kinematics->getm12Sq()); this->setGenNtupleDoubleBranchValue("m23Sq", kinematics->getm23Sq()); this->setGenNtupleDoubleBranchValue("m13Sq", kinematics->getm13Sq()); this->setGenNtupleDoubleBranchValue("cosHel12", kinematics->getc12()); this->setGenNtupleDoubleBranchValue("cosHel23", kinematics->getc23()); this->setGenNtupleDoubleBranchValue("cosHel13", kinematics->getc13()); if (kinematics->squareDP()) { this->setGenNtupleDoubleBranchValue("mPrime", kinematics->getmPrime()); this->setGenNtupleDoubleBranchValue("thPrime", kinematics->getThetaPrime()); } // Can add the real and imaginary parts of the B0 and B0bar total // amplitudes seen in the generation (restrict this with a flag // that defaults to false) if ( storeGenAmpInfo_ ) { if ( this->getGenNtupleIntegerBranchValue("genSig")==1 ) { LauComplex Abar = sigModelB0bar_->getEvtDPAmp(); LauComplex A = sigModelB0_->getEvtDPAmp(); this->setGenNtupleDoubleBranchValue("reB0Amp", A.re()); this->setGenNtupleDoubleBranchValue("imB0Amp", A.im()); this->setGenNtupleDoubleBranchValue("reB0barAmp", Abar.re()); this->setGenNtupleDoubleBranchValue("imB0barAmp", Abar.im()); } else { this->setGenNtupleDoubleBranchValue("reB0Amp", 0.0); this->setGenNtupleDoubleBranchValue("imB0Amp", 0.0); this->setGenNtupleDoubleBranchValue("reB0barAmp", 0.0); this->setGenNtupleDoubleBranchValue("imB0barAmp", 0.0); } } } void LauTimeDepFitModel::generateExtraPdfValues(LauPdfPList& extraPdfs, LauEmbeddedData* embeddedData) { // CONVENTION WARNING LauKinematics* kinematics = kinematicsB0_; //LauKinematics* kinematics(0); //if (curEvtTagFlv_<0) { // kinematics = kinematicsB0_; //} else { // kinematics = kinematicsB0bar_; //} // Generate from the extra PDFs for (auto& pdf : extraPdfs){ LauFitData genValues; if (embeddedData) { genValues = embeddedData->getValues( pdf->varNames() ); } else { genValues = pdf->generate(kinematics); } for (auto& var : genValues){ TString varName = var.first; if ( varName != "m13Sq" && varName != "m23Sq" ) { Double_t value = var.second; this->setGenNtupleDoubleBranchValue(varName,value); } } } } void LauTimeDepFitModel::propagateParUpdates() { // Update the complex mixing phase if (useSinCos_) { phiMixComplex_.setRealPart(cosPhiMix_.unblindValue()); phiMixComplex_.setImagPart(-1.0*sinPhiMix_.unblindValue()); } else { phiMixComplex_.setRealPart(TMath::Cos(-1.0*phiMix_.unblindValue())); phiMixComplex_.setImagPart(TMath::Sin(-1.0*phiMix_.unblindValue())); } // Update the total normalisation for the signal likelihood if (this->useDP() == kTRUE) { this->updateCoeffs(); sigModelB0bar_->updateCoeffs(coeffsB0bar_); sigModelB0_->updateCoeffs(coeffsB0_); this->calcInterferenceTermNorm(); } // Update the decay time normalisation if ( signalDecayTimePdf_ ) { signalDecayTimePdf_->propagateParUpdates(); } // TODO // - maybe also need to add an update of the background decay time PDFs here // Update the signal events from the background numbers if not doing an extended fit // And update the tagging category fractions this->updateSigEvents(); } void LauTimeDepFitModel::updateSigEvents() { // The background parameters will have been set from Minuit. // We need to update the signal events using these. if (!this->doEMLFit()) { Double_t nTotEvts = this->eventsPerExpt(); Double_t signalEvents = nTotEvts; signalEvents_->range(-2.0*nTotEvts,2.0*nTotEvts); for (auto& nBkgndEvents : bkgndEvents_){ if ( nBkgndEvents->isLValue() ) { LauParameter* yield = dynamic_cast( nBkgndEvents ); yield->range(-2.0*nTotEvts,2.0*nTotEvts); } } // Subtract background events (if any) from signal. if (usingBkgnd_ == kTRUE) { for (auto& nBkgndEvents : bkgndEvents_){ signalEvents -= nBkgndEvents->value(); } } if ( ! signalEvents_->fixed() ) { signalEvents_->value(signalEvents); } } } void LauTimeDepFitModel::cacheInputFitVars() { // Fill the internal data trees of the signal and background models. // Note that we store the events of both charges in both the // negative and the positive models. It's only later, at the stage // when the likelihood is being calculated, that we separate them. LauFitDataTree* inputFitData = this->fitData(); evtCPEigenVals_.clear(); const Bool_t hasCPEV = ( (cpevVarName_ != "") && inputFitData->haveBranch( cpevVarName_ ) ); UInt_t nEvents = inputFitData->nEvents(); evtCPEigenVals_.reserve( nEvents ); LauFitData::const_iterator fitdata_iter; for (UInt_t iEvt = 0; iEvt < nEvents; iEvt++) { const LauFitData& dataValues = inputFitData->getData(iEvt); // if the CP-eigenvalue is in the data use those, otherwise use the default if ( hasCPEV ) { fitdata_iter = dataValues.find( cpevVarName_ ); const Int_t cpEV = static_cast( fitdata_iter->second ); if ( cpEV == 1 ) { cpEigenValue_ = CPEven; } else if ( cpEV == -1 ) { cpEigenValue_ = CPOdd; } else if ( cpEV == 0 ) { cpEigenValue_ = QFS; } else { std::cerr<<"WARNING in LauTimeDepFitModel::cacheInputFitVars : Unknown value: "<useDP() == kTRUE) { // DecayTime and SigmaDecayTime signalDecayTimePdf_->cacheInfo(*inputFitData); // cache all the backgrounds too for(auto& bg : BkgndDecayTimePdfs_) {bg->cacheInfo(*inputFitData);} } // Flavour tagging information flavTag_->cacheInputFitVars(inputFitData,signalDecayTimePdf_->varName()); // ...and then the extra PDFs if (not sigExtraPdf_.empty()){ this->cacheInfo(sigExtraPdf_, *inputFitData); } if(usingBkgnd_ == kTRUE){ for (auto& pdf : BkgndPdfs_){ this->cacheInfo(pdf, *inputFitData); } } if (this->useDP() == kTRUE) { sigModelB0bar_->fillDataTree(*inputFitData); sigModelB0_->fillDataTree(*inputFitData); if (usingBkgnd_ == kTRUE) { for (auto& model : BkgndDPModelsB_){ model->fillDataTree(*inputFitData); } for (auto& model : BkgndDPModelsBbar_){ if (model != nullptr) { model->fillDataTree(*inputFitData); } } } } } Double_t LauTimeDepFitModel::getTotEvtLikelihood(const UInt_t iEvt) { // Get the CP eigenvalue of the current event cpEigenValue_ = evtCPEigenVals_[iEvt]; // Get the DP and DecayTime likelihood for signal (TODO and eventually backgrounds) this->getEvtDPDtLikelihood(iEvt); // Get the combined extra PDFs likelihood for signal (TODO and eventually backgrounds) this->getEvtExtraLikelihoods(iEvt); // Construct the total likelihood for signal, qqbar and BBbar backgrounds Double_t sigLike = sigDPLike_ * sigExtraLike_; Double_t signalEvents = signalEvents_->unblindValue(); // TODO - consider what to do here - do we even want the option not to use the DP in this model? //if ( not this->useDP() ) { //signalEvents *= 0.5 * (1.0 + curEvtTagFlv_ * signalAsym_->unblindValue()); //} // Construct the total event likelihood Double_t likelihood { sigLike * signalEvents }; if (usingBkgnd_) { const UInt_t nBkgnds = this->nBkgndClasses(); for ( UInt_t bkgndID(0); bkgndID < nBkgnds; ++bkgndID ) { // TODO // for combinatorial background (and perhaps others) this factor 0.5 needs to be here // to balance the factor 2 in the signal normalisation that arises from the sum over // tag decisions and integral over eta // for other (more signal-like) backgrounds where we need to think about things depending // on the tag decision and where there may be asymmetries as well this will (probably) arise naturally const Double_t bkgndEvents { 0.5 * bkgndEvents_[bkgndID]->unblindValue() }; likelihood += bkgndEvents*bkgndDPLike_[bkgndID]*bkgndExtraLike_[bkgndID]; } } return likelihood; } Double_t LauTimeDepFitModel::getEventSum() const { Double_t eventSum(0.0); eventSum += signalEvents_->unblindValue(); if (usingBkgnd_) { for ( const auto& yieldPar : bkgndEvents_ ) { eventSum += yieldPar->unblindValue(); } } return eventSum; } void LauTimeDepFitModel::getEvtDPDtLikelihood(const UInt_t iEvt) { // Function to return the signal and background likelihoods for the // Dalitz plot for the given event evtNo. if ( ! this->useDP() ) { // There's always going to be a term in the likelihood for the // signal, so we'd better not zero it. sigDPLike_ = 1.0; const UInt_t nBkgnds = this->nBkgndClasses(); for ( UInt_t bkgndID(0); bkgndID < nBkgnds; ++bkgndID ) { if (usingBkgnd_ == kTRUE) { bkgndDPLike_[bkgndID] = 1.0; } else { bkgndDPLike_[bkgndID] = 0.0; } } return; } // Calculate event quantities // Get the DP dynamics, decay time, and flavour tagging to calculate // everything required for the likelihood calculation sigModelB0bar_->calcLikelihoodInfo(iEvt); sigModelB0_->calcLikelihoodInfo(iEvt); signalDecayTimePdf_->calcLikelihoodInfo(static_cast(iEvt)); flavTag_->updateEventInfo(iEvt); // Retrieve the amplitudes and efficiency from the dynamics LauComplex Abar { sigModelB0bar_->getEvtDPAmp() }; LauComplex A { sigModelB0_->getEvtDPAmp() }; const Double_t dpEff { sigModelB0bar_->getEvtEff() }; // If this is a QFS decay, one of the DP amplitudes needs to be zeroed if (cpEigenValue_ == QFS){ curEvtDecayFlv_ = flavTag_->getCurEvtDecayFlv(); if ( curEvtDecayFlv_ == +1 ) { Abar.zero(); } else if ( curEvtDecayFlv_ == -1 ) { A.zero(); } else { std::cerr<<"ERROR in LauTimeDepFitModel::getEvtDPDtLikelihood : Decay flavour must be known for QFS decays."<Exit(EXIT_FAILURE); } } // Next calculate the DP terms const Double_t aSqSum { A.abs2() + Abar.abs2() }; const Double_t aSqDif { A.abs2() - Abar.abs2() }; Double_t interTermRe { 0.0 }; Double_t interTermIm { 0.0 }; if ( cpEigenValue_ != QFS ) { const LauComplex inter { Abar * A.conj() * phiMixComplex_ }; if ( cpEigenValue_ == CPEven ) { interTermIm = 2.0 * inter.im(); interTermRe = 2.0 * inter.re(); } else { interTermIm = -2.0 * inter.im(); interTermRe = -2.0 * inter.re(); } } // First get all the decay time terms // TODO Backgrounds // Get the decay time acceptance const Double_t dtEff { signalDecayTimePdf_->getEffiTerm() }; // Get all the decay time terms const Double_t dtCos { signalDecayTimePdf_->getCosTerm() }; const Double_t dtSin { signalDecayTimePdf_->getSinTerm() }; const Double_t dtCosh { signalDecayTimePdf_->getCoshTerm() }; const Double_t dtSinh { signalDecayTimePdf_->getSinhTerm() }; // Get the decay time error term const Double_t dtErrLike { signalDecayTimePdf_->getErrTerm() }; // Get flavour tagging terms Double_t omega{1.0}; Double_t omegabar{1.0}; - const ULong_t nTaggers { flavTag_->getNTaggers() }; - for (ULong_t position{0}; positiongetCapitalOmega(position, LauFlavTag::Flavour::B); - omegabar *= flavTag_->getCapitalOmega(position, LauFlavTag::Flavour::Bbar); + const std::size_t nTaggers { flavTag_->getNTaggers() }; + for (std::size_t taggerID{0}; taggerIDgetCapitalOmega(taggerID, LauFlavTag::Flavour::B); + omegabar *= flavTag_->getCapitalOmega(taggerID, LauFlavTag::Flavour::Bbar); } const Double_t prodAsym { AProd_.unblindValue() }; const Double_t ftOmegaHyp { ((1.0 - prodAsym)*omega + (1.0 + prodAsym)*omegabar) }; const Double_t ftOmegaTrig { ((1.0 - prodAsym)*omega - (1.0 + prodAsym)*omegabar) }; const Double_t coshTerm { ftOmegaHyp * dtCosh * aSqSum }; const Double_t sinhTerm { ftOmegaHyp * dtSinh * interTermRe }; const Double_t cosTerm { ftOmegaTrig * dtCos * aSqDif }; const Double_t sinTerm { ftOmegaTrig * dtSin * interTermIm }; // Combine all terms to get the total amplitude squared const Double_t ASq { coshTerm + sinhTerm + cosTerm - sinTerm }; // Calculate the DP and time normalisation const Double_t normASqSum { sigModelB0_->getDPNorm() + sigModelB0bar_->getDPNorm() }; const Double_t normASqDiff { sigModelB0_->getDPNorm() - sigModelB0bar_->getDPNorm() }; Double_t normInterTermRe { 0.0 }; Double_t normInterTermIm { 0.0 }; if ( cpEigenValue_ != QFS ) { // TODO - double check this sign flipping here (it's presumably right but...) normInterTermRe = ( cpEigenValue_ == CPOdd ) ? -1.0 * interTermReNorm_ : interTermReNorm_; normInterTermIm = ( cpEigenValue_ == CPOdd ) ? -1.0 * interTermImNorm_ : interTermImNorm_; } const Double_t normCoshTerm { signalDecayTimePdf_->getNormTermCosh() }; const Double_t normSinhTerm { signalDecayTimePdf_->getNormTermSinh() }; const Double_t normCosTerm { signalDecayTimePdf_->getNormTermCos() }; const Double_t normSinTerm { signalDecayTimePdf_->getNormTermSin() }; const Double_t normHyp { normASqSum * normCoshTerm + normInterTermRe * normSinhTerm }; const Double_t normTrig { - prodAsym * ( normASqDiff * normCosTerm + normInterTermIm * normSinTerm ) }; // Combine all terms to get the total normalisation const Double_t norm { 2.0 * ( normHyp + normTrig ) }; // Multiply the squared-amplitude by the efficiency (DP and decay time) and decay-time error likelihood // and normalise to obtain the signal likelihood sigDPLike_ = ( ASq * dpEff * dtEff * dtErrLike ) / norm; // Background part - // TODO add them into the actual Likelihood calculatiions - // TODO sort out B and Bbar backgrounds for the DP here - // TODO need to include the flavour tagging parts here as well (per tagger and per background source) and will vary by Bkgnd type as well - // TODO add new function as getEvtBkgndLikelihoods? - // TODO normalisation? + // TODO move to new function as getEvtBkgndLikelihoods? const UInt_t nBkgnds = this->nBkgndClasses(); for ( UInt_t bkgndID(0); bkgndID < nBkgnds; ++bkgndID ) { - if (usingBkgnd_ == kTRUE) { - Double_t omegaBkgnd{1.0}; - Double_t omegaBarBkgnd{1.0}; - - BkgndDecayTimePdfs_[bkgndID]->calcLikelihoodInfo(static_cast(iEvt)); - - // Consider background type - // TODO would this not be cleaner as a switch/cases block? - if (BkgndTypes_[bkgndID] == LauFlavTag::BkgndType::Combinatorial){ - // For Histogram Dt Pdfs - // TODO - any other decay time function types that make sense for combinatorial? - // - if so, maybe convert this to a switch with a default case to catch the types that don't make sense? - // For comb background the DP and TD models factorise completely, just mulitply them - bkgndDPLike_[bkgndID] = BkgndDPModelsB_[bkgndID]->getLikelihood(iEvt); - if (BkgndDecayTimePdfs_[bkgndID]->getFuncType() == LauDecayTime::FuncType::Hist){ - bkgndDPLike_[bkgndID] *= BkgndDecayTimePdfs_[bkgndID]->getHistTerm(); - } else { - bkgndDPLike_[bkgndID] *= BkgndDecayTimePdfs_[bkgndID]->getExpTerm()/BkgndDecayTimePdfs_[bkgndID]->getNormTermExp(); - } - // For flavour tagging - for (ULong_t position{0}; positiongetCapitalOmegaBkgnd(position, LauFlavTag::Flavour::B, bkgndID); - } - bkgndDPLike_[bkgndID] *= omegaBkgnd; - // TODO Add other bkg types - } else if (BkgndTypes_[bkgndID] == LauFlavTag::BkgndType::FlavourSpecific){ + if ( not usingBkgnd_ ) { + bkgndDPLike_[bkgndID] = 0.0; + continue; + } + + Double_t omegaBkgnd{1.0}; + Double_t omegaBarBkgnd{1.0}; - switch( BkgndDecayTimePdfs_[bkgndID]->getFuncType() ) + BkgndDecayTimePdfs_[bkgndID]->calcLikelihoodInfo(static_cast(iEvt)); + + // Consider background type + switch ( BkgndTypes_[bkgndID] ) { + case LauFlavTag::BkgndType::Combinatorial : { - case LauDecayTime::FuncType::Exp : //it still factorises - { - bkgndDPLike_[bkgndID] = 0.5*(BkgndDPModelsB_[bkgndID]->getLikelihood(iEvt) + BkgndDPModelsBbar_[bkgndID]->getLikelihood(iEvt)); - bkgndDPLike_[bkgndID] *= BkgndDecayTimePdfs_[bkgndID]->getExpTerm()/BkgndDecayTimePdfs_[bkgndID]->getNormTermExp(); - for (ULong_t position{0}; positiongetCapitalOmegaBkgnd(position, LauFlavTag::Flavour::B , bkgndID); - omegaBarBkgnd *= flavTag_->getCapitalOmegaBkgnd(position, LauFlavTag::Flavour::Bbar, bkgndID); - } - bkgndDPLike_[bkgndID] *= ((1.0 - AProdBkgnd_[bkgndID]->unblindValue())*omegaBkgnd + (1.0 + AProdBkgnd_[bkgndID]->unblindValue())*omegaBarBkgnd); - break; + // For combinatorial background the DP and decay-time models factorise completely, just mulitply them + + // Start with the DP likelihood... + if ( (cpEigenValue_ == QFS) and BkgndDPModelsBbar_[bkgndID] != nullptr ) { //Flavour specific (with possible detection asymmetry) + if ( curEvtDecayFlv_ == LauFlavTag::Flavour::B ) { + bkgndDPLike_[bkgndID] = BkgndDPModelsB_[bkgndID]->getUnNormValue(iEvt); + } else { + bkgndDPLike_[bkgndID] = BkgndDPModelsBbar_[bkgndID]->getUnNormValue(iEvt); } - case LauDecayTime::FuncType::Hist: //it still factorises - { - bkgndDPLike_[bkgndID] = 0.5*(BkgndDPModelsB_[bkgndID]->getLikelihood(iEvt) + BkgndDPModelsBbar_[bkgndID]->getLikelihood(iEvt)); + bkgndDPLike_[bkgndID] /= ( BkgndDPModelsB_[bkgndID]->getPdfNorm() + BkgndDPModelsBbar_[bkgndID]->getPdfNorm() ); + } else { + bkgndDPLike_[bkgndID] = BkgndDPModelsB_[bkgndID]->getLikelihood(iEvt); + } + + // ...include the decay time... + switch( BkgndDecayTimePdfs_[bkgndID]->getFuncType() ) { + case LauDecayTime::FuncType::Hist : bkgndDPLike_[bkgndID] *= BkgndDecayTimePdfs_[bkgndID]->getHistTerm(); - for (ULong_t position{0}; positiongetCapitalOmegaBkgnd(position, LauFlavTag::Flavour::B , bkgndID); - omegaBarBkgnd *= flavTag_->getCapitalOmegaBkgnd(position, LauFlavTag::Flavour::Bbar, bkgndID); - } - bkgndDPLike_[bkgndID] *= ((1.0 - AProdBkgnd_[bkgndID]->unblindValue())*omegaBkgnd + (1.0 + AProdBkgnd_[bkgndID]->unblindValue())*omegaBarBkgnd); break; + case LauDecayTime::FuncType::Exp : + bkgndDPLike_[bkgndID] *= ( BkgndDecayTimePdfs_[bkgndID]->getExpTerm() / BkgndDecayTimePdfs_[bkgndID]->getNormTermExp() ); + break; + // TODO - any other decay time function types that make sense for combinatorial? + // - should also have a set of checks in initialise that we have everything we need for the backgrounds and that the various settings make sense + default : + // TODO as per comment just above, once the above mentioned checks are implemented this error message can be removed + std::cerr << "WARNING in LauTimeDepFitModel::getEvtDPDtLikelihood : bkgnd types other than Hist and Exp don't make sense for combinatorial!" << std::endl; + break; + } + + // ...include flavour tagging + for (std::size_t taggerID{0}; taggerIDgetCapitalOmegaBkgnd(bkgndID, taggerID, LauFlavTag::Flavour::B, curEvtDecayFlv_); + } + bkgndDPLike_[bkgndID] *= omegaBkgnd; + + break; + } + + case LauFlavTag::BkgndType::FlavourSpecific : + { + // DP terms needed by all decay-time cases + Double_t Asq { BkgndDPModelsB_[bkgndID]->getUnNormValue(iEvt) }; + Double_t Asqbar { BkgndDPModelsBbar_[bkgndID]->getUnNormValue(iEvt) }; + if ( cpEigenValue_ == QFS ){ + // If the signal is flavour-specific we can know which DP to use, so zero the other one + curEvtDecayFlv_ = flavTag_->getCurEvtDecayFlv(); + if ( curEvtDecayFlv_ == LauFlavTag::Flavour::B ) { + Asqbar = 0.0; + } else if ( curEvtDecayFlv_ == LauFlavTag::Flavour::Bbar ) { + Asq = 0.0; } - case LauDecayTime::FuncType::ExpTrig: // it doesn't factorise - case LauDecayTime::FuncType::ExpHypTrig: - { - //DP components first - Double_t Asq { BkgndDPModelsB_[bkgndID] ->getUnNormValue(iEvt) }; - Double_t Asqbar { BkgndDPModelsBbar_[bkgndID]->getUnNormValue(iEvt) }; - - //Used in the normalisation - const Double_t AsqNorm { BkgndDPModelsB_[bkgndID] ->getPdfNorm() }; - const Double_t AsqbarNorm { BkgndDPModelsBbar_[bkgndID]->getPdfNorm() }; - - //Do different things depending on whether the signal is Flav Specific or Self Conjugate - if (cpEigenValue_ == QFS){ //Flavour specific - curEvtDecayFlv_ = flavTag_->getCurEvtDecayFlv(); - if ( curEvtDecayFlv_ == +1 ) { - Asqbar = 0.; - } else if ( curEvtDecayFlv_ == -1 ) { - Asq = 0.; - } + } + const Double_t AsqSum { Asq + Asqbar }; + + // DP norm terms needed by all decay-time cases + const Double_t AsqNorm { BkgndDPModelsB_[bkgndID]->getPdfNorm() }; + const Double_t AsqbarNorm { BkgndDPModelsBbar_[bkgndID]->getPdfNorm() }; + const Double_t AsqNormSum { AsqNorm + AsqbarNorm }; + + // FT terms needed by all decay-time cases + omegaBkgnd = omegaBarBkgnd = 1.0; + for (std::size_t taggerID{0}; taggerIDgetCapitalOmegaBkgnd(bkgndID, taggerID, LauFlavTag::Flavour::B, curEvtDecayFlv_); + omegaBarBkgnd *= flavTag_->getCapitalOmegaBkgnd(bkgndID, taggerID, LauFlavTag::Flavour::Bbar, curEvtDecayFlv_); + } + const Double_t AProd { AProdBkgnd_[bkgndID]->unblindValue() }; + const Double_t ftOmegaHypBkgnd { (1.0 - AProd)*omegaBkgnd + (1.0 + AProd)*omegaBarBkgnd }; + + switch( BkgndDecayTimePdfs_[bkgndID]->getFuncType() ) + { + case LauDecayTime::FuncType::Hist: // DP and decay-time still factorise + { + // Start with the DP terms... + bkgndDPLike_[bkgndID] = AsqSum / AsqNormSum; + + // ...include the decay time... + bkgndDPLike_[bkgndID] *= BkgndDecayTimePdfs_[bkgndID]->getHistTerm(); + + // ...include flavour tagging + bkgndDPLike_[bkgndID] *= ftOmegaHypBkgnd; + + break; } - const Double_t AsqSum { Asq + Asqbar }; - const Double_t AsqDiff { Asq - Asqbar }; - - const Double_t AsqNormSum { AsqNorm + AsqbarNorm }; - //TODO check this shouldn't be `fabs`ed - const Double_t AsqNormDiff { AsqNorm - AsqbarNorm }; - - // Now get all the decay time terms - // Sin and Sinh terms are ignored: they FS modes can't exhibit TD CPV - const Double_t dtCosBkgnd { BkgndDecayTimePdfs_[bkgndID]->getCosTerm() }; - const Double_t dtCoshBkgnd { BkgndDecayTimePdfs_[bkgndID]->getCoshTerm() }; - // Get all norm terms - const Double_t normCosTermBkgnd { BkgndDecayTimePdfs_[bkgndID]->getNormTermCos() }; - const Double_t normCoshTermBkgnd { BkgndDecayTimePdfs_[bkgndID]->getNormTermCosh() }; - // Use signal flavour tagging - for (ULong_t position{0}; positiongetCapitalOmegaBkgnd(position, LauFlavTag::Flavour::B , bkgndID); - omegaBarBkgnd *= flavTag_->getCapitalOmegaBkgnd(position, LauFlavTag::Flavour::Bbar, bkgndID); + case LauDecayTime::FuncType::Exp : // DP and decay-time still factorise + { + // Start with the DP terms... + bkgndDPLike_[bkgndID] = AsqSum / AsqNormSum; + + // ...include the decay time... + bkgndDPLike_[bkgndID] *= ( BkgndDecayTimePdfs_[bkgndID]->getExpTerm() / BkgndDecayTimePdfs_[bkgndID]->getNormTermExp() ); + + // ...include flavour tagging + bkgndDPLike_[bkgndID] *= ftOmegaHypBkgnd; + + break; } - // Depends on the background source? Or use the signal one? - const Double_t ftOmegaHypBkgnd { ((1.0 - AProdBkgnd_[bkgndID]->unblindValue())*omegaBkgnd + (1.0 + AProdBkgnd_[bkgndID]->unblindValue())*omegaBarBkgnd) }; - const Double_t ftOmegaTrigBkgnd { ((1.0 - AProdBkgnd_[bkgndID]->unblindValue())*omegaBkgnd - (1.0 + AProdBkgnd_[bkgndID]->unblindValue())*omegaBarBkgnd) }; - //ExpTrig or ExpHypTrig modes - //TODO Check normalisation - const Double_t coshTermBkgnd { ftOmegaHypBkgnd * dtCoshBkgnd * AsqSum }; - const Double_t cosTermBkgnd { ftOmegaTrigBkgnd * dtCosBkgnd * AsqDiff }; - - //See Laura note eq. 41 - const Double_t normBkgnd { (normCoshTermBkgnd * AsqNormSum) - AProdBkgnd_[bkgndID]->unblindValue()*(normCosTermBkgnd * AsqNormDiff) }; - - bkgndDPLike_[bkgndID] *= (coshTermBkgnd + cosTermBkgnd)/normBkgnd; + case LauDecayTime::FuncType::ExpTrig: // DP and decay-time don't factorise + case LauDecayTime::FuncType::ExpHypTrig: + { + // DP and FT terms specific to this case + const Double_t AsqDiff { Asq - Asqbar }; + const Double_t AsqNormDiff { AsqNorm - AsqbarNorm }; //TODO check this shouldn't be `fabs`ed + const Double_t ftOmegaTrigBkgnd { (1.0 - AProd)*omegaBkgnd - (1.0 + AProd)*omegaBarBkgnd }; + + // decay time terms + // Sin and Sinh terms are ignored: the FS modes can't exhibit TD CPV + const Double_t dtCoshBkgnd { BkgndDecayTimePdfs_[bkgndID]->getCoshTerm() }; + const Double_t dtCosBkgnd { BkgndDecayTimePdfs_[bkgndID]->getCosTerm() }; + const Double_t normCoshTermBkgnd { BkgndDecayTimePdfs_[bkgndID]->getNormTermCosh() }; + const Double_t normCosTermBkgnd { BkgndDecayTimePdfs_[bkgndID]->getNormTermCos() }; + + // Combine the DP, FT, and decay time terms + const Double_t coshTermBkgnd { ftOmegaHypBkgnd * dtCoshBkgnd * AsqSum }; + const Double_t cosTermBkgnd { ftOmegaTrigBkgnd * dtCosBkgnd * AsqDiff }; + // Similarly for the normalisation, see Laura note eq. 41 + const Double_t normBkgnd { (normCoshTermBkgnd * AsqNormSum) - AProd*(normCosTermBkgnd * AsqNormDiff) }; + + bkgndDPLike_[bkgndID] = (coshTermBkgnd + cosTermBkgnd) / normBkgnd; + + break; + } + case LauDecayTime::FuncType::Delta: + case LauDecayTime::FuncType::DeltaExp: + // TODO as per comment above, once the checks in initialise are implemented this error message can be removed + std::cerr << "WARNING in LauTimeDepFitModel::getEvtDPDtLikelihood : bkgnd types Delta and DeltaExp don't make sense!" << std::endl; break; - } - case LauDecayTime::FuncType::Delta: //prompt case: irrellevant - case LauDecayTime::FuncType::DeltaExp: - //TODO move this error message - std::cerr << "WARNING in LauTimeDepFitModel::getEvtDPDtLikelihood : bkgnd types Delta and DeltaExp don't make sense!" << std::endl; - break; + } + + break; } - } else if (BkgndTypes_[bkgndID] == LauFlavTag::BkgndType::SelfConjugate) { + case LauFlavTag::BkgndType::SelfConjugate : //Copy this from the CPeigenstate signal case std::cerr << "WARNING in LauTimeDepFitModel::getEvtDPDtLikelihood : SelfConjugate states aren't implemented yet!" << std::endl; - bkgndDPLike_[bkgndID] = 0.0; break; - } else if (BkgndTypes_[bkgndID] == LauFlavTag::BkgndType::NonSelfConjugate) { + bkgndDPLike_[bkgndID] = 0.0; + break; + case LauFlavTag::BkgndType::NonSelfConjugate : // TODO this has been ignored for now since it's not used in the B->Dpipi case std::cerr << "WARNING in LauTimeDepFitModel::getEvtDPDtLikelihood : NonSelfConjugate states aren't implemented yet!" << std::endl; - bkgndDPLike_[bkgndID] = 0.0; break; - } - - // Get the decay time acceptance - const Double_t dtEffBkgnd { BkgndDecayTimePdfs_[bkgndID]->getEffiTerm() }; - // Get the decay time error term - const Double_t dtErrLikeBkgnd { BkgndDecayTimePdfs_[bkgndID]->getErrTerm() }; - // Include these terms in the background likelihood - bkgndDPLike_[bkgndID] *= dtEffBkgnd * dtErrLikeBkgnd; - } else { - bkgndDPLike_[bkgndID] = 0.0; + bkgndDPLike_[bkgndID] = 0.0; + break; } + + // Get the decay time acceptance + const Double_t dtEffBkgnd { BkgndDecayTimePdfs_[bkgndID]->getEffiTerm() }; + // Get the decay time error term + const Double_t dtErrLikeBkgnd { BkgndDecayTimePdfs_[bkgndID]->getErrTerm() }; + // Include these terms in the background likelihood + bkgndDPLike_[bkgndID] *= dtEffBkgnd * dtErrLikeBkgnd; } } void LauTimeDepFitModel::getEvtExtraLikelihoods(const UInt_t iEvt) { // Function to return the signal and background likelihoods for the // extra variables for the given event evtNo. sigExtraLike_ = 1.0; //There's always a likelihood term for signal, so we better not zero it. // First, those independent of the tagging of the event: // signal if ( not sigExtraPdf_.empty() ) { sigExtraLike_ = this->prodPdfValue( sigExtraPdf_, iEvt ); } // Background const UInt_t nBkgnds = this->nBkgndClasses(); for ( UInt_t bkgndID(0); bkgndID < nBkgnds; ++bkgndID ) { if (usingBkgnd_) { bkgndExtraLike_[bkgndID] = this->prodPdfValue( BkgndPdfs_[bkgndID], iEvt ); } else { bkgndExtraLike_[bkgndID] = 0.0; } } } void LauTimeDepFitModel::updateCoeffs() { coeffsB0bar_.clear(); coeffsB0_.clear(); coeffsB0bar_.reserve(nSigComp_); coeffsB0_.reserve(nSigComp_); for (UInt_t i = 0; i < nSigComp_; ++i) { coeffsB0bar_.push_back(coeffPars_[i]->antiparticleCoeff()); coeffsB0_.push_back(coeffPars_[i]->particleCoeff()); } } void LauTimeDepFitModel::checkMixingPhase() { Double_t phase = phiMix_.value(); Double_t genPhase = phiMix_.genValue(); // Check now whether the phase lies in the right range (-pi to pi). Bool_t withinRange(kFALSE); while (withinRange == kFALSE) { if (phase > -LauConstants::pi && phase < LauConstants::pi) { withinRange = kTRUE; } else { // Not within the specified range if (phase > LauConstants::pi) { phase -= LauConstants::twoPi; } else if (phase < -LauConstants::pi) { phase += LauConstants::twoPi; } } } // A further problem can occur when the generated phase is close to -pi or pi. // The phase can wrap over to the other end of the scale - // this leads to artificially large pulls so we wrap it back. Double_t diff = phase - genPhase; if (diff > LauConstants::pi) { phase -= LauConstants::twoPi; } else if (diff < -LauConstants::pi) { phase += LauConstants::twoPi; } // finally store the new value in the parameter // and update the pull phiMix_.value(phase); phiMix_.updatePull(); } void LauTimeDepFitModel::embedSignal(const TString& fileName, const TString& treeName, const Bool_t reuseEventsWithinEnsemble, const Bool_t reuseEventsWithinExperiment, const Bool_t useReweighting) { if (signalTree_) { std::cerr<<"ERROR in LauTimeDepFitModel::embedSignal : Already embedding signal from file."<findBranches(); if (!dataOK) { delete signalTree_; signalTree_ = 0; std::cerr<<"ERROR in LauTimeDepFitModel::embedSignal : Problem creating data tree for embedding."<enableEmbedding(kTRUE); } void LauTimeDepFitModel::embedBkgnd(const TString& bkgndClass, const TString& fileName, const TString& treeName, const Bool_t reuseEventsWithinEnsemble, const Bool_t reuseEventsWithinExperiment, const Bool_t useReweighting) { if ( ! this->validBkgndClass( bkgndClass ) ) { std::cerr << "ERROR in LauSimpleFitModel::embedBkgnd : Invalid background class \"" << bkgndClass << "\"." << std::endl; std::cerr << " : Background class names must be provided in \"setBkgndClassNames\" before any other background-related actions can be performed." << std::endl; return; } UInt_t bkgndID = this->bkgndClassID( bkgndClass ); LauEmbeddedData* bkgTree = bkgndTree_[bkgndID]; if (bkgTree) { std::cerr << "ERROR in LauSimpleFitModel::embedBkgnd : Already embedding background from a file." << std::endl; return; } bkgTree = new LauEmbeddedData(fileName,treeName,reuseEventsWithinExperiment); Bool_t dataOK = bkgTree->findBranches(); if (!dataOK) { delete bkgTree; bkgTree = 0; std::cerr << "ERROR in LauSimpleFitModel::embedBkgnd : Problem creating data tree for embedding." << std::endl; return; } reuseBkgnd_[bkgndID] = reuseEventsWithinEnsemble; useReweighting_ = useReweighting; this->enableEmbedding(kTRUE); } void LauTimeDepFitModel::setupSPlotNtupleBranches() { // add branches for storing the experiment number and the number of // the event within the current experiment this->addSPlotNtupleIntegerBranch("iExpt"); this->addSPlotNtupleIntegerBranch("iEvtWithinExpt"); // Store the efficiency of the event (for inclusive BF calculations). if (this->storeDPEff()) { this->addSPlotNtupleDoubleBranch("efficiency"); } // Store the total event likelihood for each species. this->addSPlotNtupleDoubleBranch("sigTotalLike"); if (usingBkgnd_) { const UInt_t nBkgnds = this->nBkgndClasses(); for ( UInt_t iBkgnd(0); iBkgnd < nBkgnds; ++iBkgnd ) { TString name( this->bkgndClassName(iBkgnd) ); name += "TotalLike"; this->addSPlotNtupleDoubleBranch(name); } } // Store the DP likelihoods if (this->useDP()) { this->addSPlotNtupleDoubleBranch("sigDPLike"); if (usingBkgnd_) { const UInt_t nBkgnds = this->nBkgndClasses(); for ( UInt_t iBkgnd(0); iBkgnd < nBkgnds; ++iBkgnd ) { TString name( this->bkgndClassName(iBkgnd) ); name += "DPLike"; this->addSPlotNtupleDoubleBranch(name); } } } // Store the likelihoods for each extra PDF this->addSPlotNtupleBranches(sigExtraPdf_, "sig"); if (usingBkgnd_) { const UInt_t nBkgnds = this->nBkgndClasses(); for ( UInt_t iBkgnd(0); iBkgnd < nBkgnds; ++iBkgnd ) { const TString& bkgndClass = this->bkgndClassName(iBkgnd); this->addSPlotNtupleBranches(BkgndPdfs_[iBkgnd], bkgndClass); } } } void LauTimeDepFitModel::addSPlotNtupleBranches(const LauPdfPList& extraPdfs, const TString& prefix) { // Loop through each of the PDFs for ( const LauAbsPdf* pdf : extraPdfs ) { // Count the number of input variables that are not // DP variables (used in the case where there is DP // dependence for e.g. MVA) UInt_t nVars{0}; const std::vector varNames { pdf->varNames() }; for ( const TString& varName : varNames ) { if ( varName != "m13Sq" && varName != "m23Sq" ) { ++nVars; } } if ( nVars == 1 ) { // If the PDF only has one variable then // simply add one branch for that variable TString name{prefix}; name += pdf->varName(); name += "Like"; this->addSPlotNtupleDoubleBranch(name); } else if ( nVars == 2 ) { // If the PDF has two variables then we // need a branch for them both together and // branches for each TString allVars{""}; for ( const TString& varName : varNames ) { if ( varName != "m13Sq" && varName != "m23Sq" ) { allVars += varName; TString name{prefix}; name += varName; name += "Like"; this->addSPlotNtupleDoubleBranch(name); } } TString name{prefix}; name += allVars; name += "Like"; this->addSPlotNtupleDoubleBranch(name); } else { std::cerr<<"WARNING in LauTimeDepFitModel::addSPlotNtupleBranches : Can't yet deal with 3D PDFs."<calcLikelihoodInfo(iEvt); extraLike = pdf->getLikelihood(); totalLike *= extraLike; // Count the number of input variables that are not // DP variables (used in the case where there is DP // dependence for e.g. MVA) UInt_t nVars{0}; const std::vector varNames { pdf->varNames() }; for ( const TString& varName : varNames ) { if ( varName != "m13Sq" && varName != "m23Sq" ) { ++nVars; } } if ( nVars == 1 ) { // If the PDF only has one variable then // simply store the value for that variable TString name{prefix}; name += pdf->varName(); name += "Like"; this->setSPlotNtupleDoubleBranchValue(name, extraLike); } else if ( nVars == 2 ) { // If the PDF has two variables then we // store the value for them both together // and for each on their own TString allVars{""}; for ( const TString& varName : varNames ) { if ( varName != "m13Sq" && varName != "m23Sq" ) { allVars += varName; TString name{prefix}; name += varName; name += "Like"; const Double_t indivLike = pdf->getLikelihood( varName ); this->setSPlotNtupleDoubleBranchValue(name, indivLike); } } TString name{prefix}; name += allVars; name += "Like"; this->setSPlotNtupleDoubleBranchValue(name, extraLike); } else { std::cerr<<"WARNING in LauAllFitModel::setSPlotNtupleBranchValues : Can't yet deal with 3D PDFs."<useDP()) { nameSet.insert("DP"); } for ( const LauAbsPdf* pdf : sigExtraPdf_ ) { // Loop over the variables involved in each PDF const std::vector varNames { pdf->varNames() }; for ( const TString& varName : varNames ) { // If they are not DP coordinates then add them if ( varName != "m13Sq" && varName != "m23Sq" ) { nameSet.insert( varName ); } } } return nameSet; } LauSPlot::NumbMap LauTimeDepFitModel::freeSpeciesNames() const { LauSPlot::NumbMap numbMap; if (!signalEvents_->fixed() && this->doEMLFit()) { numbMap["sig"] = signalEvents_->genValue(); } if ( usingBkgnd_ ) { const UInt_t nBkgnds = this->nBkgndClasses(); for ( UInt_t iBkgnd(0); iBkgnd < nBkgnds; ++iBkgnd ) { const TString& bkgndClass = this->bkgndClassName(iBkgnd); const LauAbsRValue* par = bkgndEvents_[iBkgnd]; if (!par->fixed()) { numbMap[bkgndClass] = par->genValue(); if ( ! par->isLValue() ) { std::cerr << "WARNING in LauTimeDepFitModel::freeSpeciesNames : \"" << par->name() << "\" is a LauFormulaPar, which implies it is perhaps not entirely free to float in the fit, so the sWeight calculation may not be reliable" << std::endl; } } } } return numbMap; } LauSPlot::NumbMap LauTimeDepFitModel::fixdSpeciesNames() const { LauSPlot::NumbMap numbMap; if (signalEvents_->fixed() && this->doEMLFit()) { numbMap["sig"] = signalEvents_->genValue(); } if ( usingBkgnd_ ) { const UInt_t nBkgnds = this->nBkgndClasses(); for ( UInt_t iBkgnd(0); iBkgnd < nBkgnds; ++iBkgnd ) { const TString& bkgndClass = this->bkgndClassName(iBkgnd); const LauAbsRValue* par = bkgndEvents_[iBkgnd]; if (par->fixed()) { numbMap[bkgndClass] = par->genValue(); } } } return numbMap; } LauSPlot::TwoDMap LauTimeDepFitModel::twodimPDFs() const { LauSPlot::TwoDMap twodimMap; for ( const LauAbsPdf* pdf : sigExtraPdf_ ) { // Count the number of input variables that are not DP variables UInt_t nVars{0}; const std::vector varNames { pdf->varNames() }; for ( const TString& varName : varNames ) { if ( varName != "m13Sq" && varName != "m23Sq" ) { ++nVars; } } if ( nVars == 2 ) { twodimMap.insert( std::make_pair( "sig", std::make_pair( varNames[0], varNames[1] ) ) ); } } if (usingBkgnd_) { const UInt_t nBkgnds = this->nBkgndClasses(); for ( UInt_t iBkgnd(0); iBkgnd < nBkgnds; ++iBkgnd ) { const TString& bkgndClass = this->bkgndClassName(iBkgnd); for ( const LauAbsPdf* pdf : BkgndPdfs_[iBkgnd] ) { // Count the number of input variables that are not DP variables UInt_t nVars{0}; const std::vector varNames { pdf->varNames() }; for ( const TString& varName : varNames ) { if ( varName != "m13Sq" && varName != "m23Sq" ) { ++nVars; } } if ( nVars == 2 ) { twodimMap.insert( std::make_pair( bkgndClass, std::make_pair( varNames[0], varNames[1] ) ) ); } } } } return twodimMap; } void LauTimeDepFitModel::storePerEvtLlhds() { std::cout<<"INFO in LauTimeDepFitModel::storePerEvtLlhds : Storing per-event likelihood values..."<fitData(); // if we've not been using the DP model then we need to cache all // the info here so that we can get the efficiency from it if (!this->useDP() && this->storeDPEff()) { sigModelB0bar_->initialise(coeffsB0bar_); sigModelB0_->initialise(coeffsB0_); sigModelB0bar_->fillDataTree(*inputFitData); sigModelB0_->fillDataTree(*inputFitData); } UInt_t evtsPerExpt(this->eventsPerExpt()); LauIsobarDynamics* sigModel(sigModelB0bar_); for (UInt_t iEvt = 0; iEvt < evtsPerExpt; ++iEvt) { // Find out whether we have B0bar or B0 flavTag_->updateEventInfo(iEvt); curEvtTagFlv_ = flavTag_->getCurEvtTagFlv(); curEvtMistag_ = flavTag_->getCurEvtMistag(); // the DP information this->getEvtDPDtLikelihood(iEvt); if (this->storeDPEff()) { if (!this->useDP()) { sigModel->calcLikelihoodInfo(iEvt); } this->setSPlotNtupleDoubleBranchValue("efficiency",sigModel->getEvtEff()); } if (this->useDP()) { sigTotalLike_ = sigDPLike_; this->setSPlotNtupleDoubleBranchValue("sigDPLike",sigDPLike_); if (usingBkgnd_) { const UInt_t nBkgnds = this->nBkgndClasses(); for ( UInt_t iBkgnd(0); iBkgnd < nBkgnds; ++iBkgnd ) { TString name = this->bkgndClassName(iBkgnd); name += "DPLike"; this->setSPlotNtupleDoubleBranchValue(name,bkgndDPLike_[iBkgnd]); } } } else { sigTotalLike_ = 1.0; } // the signal PDF values sigTotalLike_ *= this->setSPlotNtupleBranchValues(sigExtraPdf_, "sig", iEvt); // the background PDF values if (usingBkgnd_) { const UInt_t nBkgnds = this->nBkgndClasses(); for ( UInt_t iBkgnd(0); iBkgnd < nBkgnds; ++iBkgnd ) { const TString& bkgndClass = this->bkgndClassName(iBkgnd); LauPdfPList& pdfs = BkgndPdfs_[iBkgnd]; bkgndTotalLike_[iBkgnd] *= this->setSPlotNtupleBranchValues(pdfs, bkgndClass, iEvt); } } // the total likelihoods this->setSPlotNtupleDoubleBranchValue("sigTotalLike",sigTotalLike_); if (usingBkgnd_) { const UInt_t nBkgnds = this->nBkgndClasses(); for ( UInt_t iBkgnd(0); iBkgnd < nBkgnds; ++iBkgnd ) { TString name = this->bkgndClassName(iBkgnd); name += "TotalLike"; this->setSPlotNtupleDoubleBranchValue(name,bkgndTotalLike_[iBkgnd]); } } // fill the tree this->fillSPlotNtupleBranches(); } std::cout<<"INFO in LauTimeDepFitModel::storePerEvtLlhds : Finished storing per-event likelihood values."<