diff --git a/inc/LauAbsDecayTimeEfficiency.hh b/inc/LauAbsDecayTimeEfficiency.hh index 1c2edb2..ad3cb8c 100644 --- a/inc/LauAbsDecayTimeEfficiency.hh +++ b/inc/LauAbsDecayTimeEfficiency.hh @@ -1,93 +1,99 @@ /* Copyright 2021 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 LauAbsDecayTimeEfficiency.hh \brief File containing declaration of LauAbsDecayTimeEfficiency class. */ /*! \class LauAbsDecayTimeEfficiency \brief Class for defining the abstract interface for modelling decay time efficiency */ #ifndef LAU_ABS_DECAYTIME_EFFICIENCY #define LAU_ABS_DECAYTIME_EFFICIENCY #include #include "Rtypes.h" class LauAbsRValue; class LauAbsDecayTimeEfficiency { public: //! Retrieve the efficiency for a given value of the decay time /*! \param abscissa the value of the decay time \return the efficiency */ virtual Double_t getEfficiency( const Double_t abscissa ) const = 0; + //! Find the maximum value of the efficiency in the range + /*! + \return the maximum of the efficiency distribution + */ + virtual Double_t findMaximum() const = 0; + //! Retrieve the parameters of the efficiency model so that they can be loaded into a fit /*! \return the parameters of the efficiency model */ virtual std::vector getParameters() = 0; //! Initialise the parameter cache /*! Must be called prior to starting fitting or generation */ virtual void initialise() = 0; //! Propagate any updates to parameters and recalculate information as neeeded /*! Should be called at each fit iteration */ virtual void propagateParUpdates() = 0; //! Retrieve whether any of the parameters have changed in the latest fit iteration virtual const bool& anythingChanged() const = 0; //! Constructor LauAbsDecayTimeEfficiency() = default; //! Destructor virtual ~LauAbsDecayTimeEfficiency() = default; //! Move constructor (default) LauAbsDecayTimeEfficiency(LauAbsDecayTimeEfficiency&& other) = default; //! Move assignment operator (default) LauAbsDecayTimeEfficiency& operator=(LauAbsDecayTimeEfficiency&& other) = default; protected: //! Copy constructor (default but protected) LauAbsDecayTimeEfficiency(const LauAbsDecayTimeEfficiency& other) = default; //! Copy assignment operator (default but protected) LauAbsDecayTimeEfficiency& operator=(const LauAbsDecayTimeEfficiency& other) = default; private: ClassDef(LauAbsDecayTimeEfficiency, 0) }; #endif diff --git a/inc/LauBinnedDecayTimeEfficiency.hh b/inc/LauBinnedDecayTimeEfficiency.hh index cdcf6fd..173bebd 100644 --- a/inc/LauBinnedDecayTimeEfficiency.hh +++ b/inc/LauBinnedDecayTimeEfficiency.hh @@ -1,114 +1,120 @@ /* Copyright 2021 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 LauBinnedDecayTimeEfficiency.hh \brief File containing declaration of LauBinnedDecayTimeEfficiency class. */ /*! \class LauBinnedDecayTimeEfficiency \brief Class for defining a binned model for decay time efficiency */ #ifndef LAU_BINNED_DECAYTIME_EFFICIENCY #define LAU_BINNED_DECAYTIME_EFFICIENCY #include #include #include "Rtypes.h" #include "TH1.h" #include "LauAbsDecayTimeEfficiency.hh" class LauAbsRValue; class LauBinnedDecayTimeEfficiency : public LauAbsDecayTimeEfficiency { public: //! Constructor explicit LauBinnedDecayTimeEfficiency( const TH1& effHist ); //! Retrieve the efficiency for a given value of the decay time /*! \param abscissa the value of the decay time \return the efficiency */ Double_t getEfficiency( const Double_t abscissa ) const override; + //! Find the maximum value of the efficiency in the range + /*! + \return the maximum of the efficiency distribution + */ + Double_t findMaximum() const override; + //! Retrieve the parameters of the efficiency model so that they can be loaded into a fit /*! \return the parameters of the efficiency model */ std::vector getParameters() override { return {}; } //! Initialise the parameter cache /*! Must be called prior to starting fitting or generation */ void initialise() override {} //! Propagate any updates to parameters and recalculate information as neeeded /*! Should be called at each fit iteration */ void propagateParUpdates() override {} //! Retrieve whether any of the parameters have changed in the latest fit iteration const bool& anythingChanged() const override { return anythingChanged_; } //! Struct to group all info on decay time efficiency bins struct BinInfo { //! Constructor BinInfo( Double_t lowEdge, Double_t highEdge, Double_t eff ) : loEdge{lowEdge}, hiEdge{highEdge}, efficiency{eff} { } //! The low edge of the bin Double_t loEdge; //! The high edge of the bin Double_t hiEdge; //! The efficiency value Double_t efficiency; }; //! Obtain the binning information /*! \return the information on each bin */ std::vector getBinningInfo() const; private: //! The binned values of the efficiency const std::unique_ptr effHist_; //! Nothing will change but we need to be able to return that information as a reference const bool anythingChanged_{false}; ClassDefOverride(LauBinnedDecayTimeEfficiency, 0) }; #endif diff --git a/inc/LauDecayTimePdf.hh b/inc/LauDecayTimePdf.hh index ba3be65..0ef5733 100644 --- a/inc/LauDecayTimePdf.hh +++ b/inc/LauDecayTimePdf.hh @@ -1,491 +1,503 @@ /* 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 LauDecayTimePdf.hh \brief File containing declaration of LauDecayTimePdf class. */ /*! \class LauDecayTimePdf \brief Class for defining the PDFs used in the time-dependent fit model to describe the decay time. LauDecayTimePdf is a class that provides the PDFs for describing the time-dependence of the various terms in a particle/antiparticle decay to a common final state. The various terms have the form of exponentially decaying trigonometric or hyperbolic functions convolved with a N-Gaussian resolution function. */ #ifndef LAU_DECAYTIME_PDF #define LAU_DECAYTIME_PDF #include #include #include #include "TString.h" #include "LauAbsRValue.hh" #include "LauComplex.hh" #include "LauDecayTime.hh" #include "LauDecayTimePhysicsModel.hh" #include "LauDecayTimeResolution.hh" #include "LauAbsDecayTimeCalculator.hh" #include "LauAbsDecayTimeEfficiency.hh" #include "LauAbsDecayTimeIntegrator.hh" #include "LauFitDataTree.hh" #include "LauBinnedDecayTimeEfficiency.hh" #include "LauSplineDecayTimeEfficiency.hh" #include "LauUniformDecayTimeEfficiency.hh" #include "LauNonSmearedSplineEfficiencyDecayTimeIntegrator.hh" #include "LauSmearedSplineEfficiencyDecayTimeIntegrator.hh" class TH1; class Lau1DHistPdf; class LauKinematics; // TODO - Should this have Pdf in the name? // - Audit function names and public/private access category // - Audit what should be given to constructor and what can be set later (maybe different constructors for different scenarios, e.g. smeared with per-event error/smeared with avg error/not smeared) class LauDecayTimePdf final { public: //! Constructor for FuncType::Hist form /*! In this form the decay time error distribution is not supplied. NB only to be used if ALL decay time functions in the model do not use the deacy time error. \param [in] theVarName the name of the decay time variable in the input data \param [in] minAbscissaVal the minimum value of the decay time \param [in] maxAbscissaVal the maximum value of the decay time \param [in] dtHist the histogram to define the decay time dependence \param [in] method set the type of the time measurement used in the given experiment (defaults to absolute decay time measurement) */ LauDecayTimePdf(const TString& theVarName, const Double_t minAbscissaVal, const Double_t maxAbscissaVal, const TH1* dtHist, const LauDecayTime::TimeMeasurementMethod method = LauDecayTime::TimeMeasurementMethod::DecayTime); //! Constructor for FuncType::Hist form /*! In this form the decay time error distribution is also supplied. If other components in your model use the decay time error, you muse use this form. \param [in] theVarName the name of the decay time variable in the input data \param [in] minAbscissaVal the minimum value of the decay time \param [in] maxAbscissaVal the maximum value of the decay time \param [in] theVarErrName the name of the decay time error variable in the input data \param [in] minAbscissaErr the minimum value of the decay time error \param [in] maxAbscissaErr the maximum value of the decay time error \param [in] dtHist the histogram to define the decay time dependence \param [in] dtErrHist the histogram to define the decay time error dependence \param [in] method set the type of the time measurement used in the given experiment (defaults to absolute decay time measurement) */ LauDecayTimePdf(const TString& theVarName, const Double_t minAbscissaVal, const Double_t maxAbscissaVal, const TString& theVarErrName, const Double_t minAbscissaErr, const Double_t maxAbscissaErr, const TH1* dtHist, const TH1* dtErrHist, const LauDecayTime::TimeMeasurementMethod method = LauDecayTime::TimeMeasurementMethod::DecayTime); //! Constructor for parametric forms, in absence of decay time resolution /*! \param [in] theVarName the name of the decay time variable in the input data \param [in] minAbscissaVal the minimum value of the decay time \param [in] maxAbscissaVal the maximum value of the decay time \param [in] physicsModel the functional form of the model \param [in] method set the type of the time measurement used in the given experiment (defaults to absolute decay time measurement) */ LauDecayTimePdf(const TString& theVarName, const Double_t minAbscissaVal, const Double_t maxAbscissaVal, std::unique_ptr physicsModel, const LauDecayTime::TimeMeasurementMethod method = LauDecayTime::TimeMeasurementMethod::DecayTime); //! Constructor for parametric forms, with decay time resolution (without use of event-by-event error) /*! \param [in] theVarName the name of the decay time variable in the input data \param [in] minAbscissaVal the minimum value of the decay time \param [in] maxAbscissaVal the maximum value of the decay time \param [in] physicsModel the functional form of the physics model \param [in] resolutionModel the functional form of the resolution model \param [in] method set the type of the time measurement used in the given experiment (defaults to absolute decay time measurement) */ LauDecayTimePdf(const TString& theVarName, const Double_t minAbscissaVal, const Double_t maxAbscissaVal, std::unique_ptr physicsModel, std::unique_ptr resolutionModel, const LauDecayTime::TimeMeasurementMethod method = LauDecayTime::TimeMeasurementMethod::DecayTime); //! Constructor for parametric forms, with decay time resolution (including use of event-by-event error) /*! \param [in] theVarName the name of the decay time variable in the input data \param [in] minAbscissaVal the minimum value of the decay time \param [in] maxAbscissaVal the maximum value of the decay time \param [in] theVarErrName the name of the decay time error variable in the input data \param [in] minAbscissaErr the minimum value of the decay time error \param [in] maxAbscissaErr the maximum value of the decay time error \param [in] physicsModel the functional form of the physics model \param [in] resolutionModel the functional form of the resolution model \param [in] dtErrHist the histogram to define the decay time error dependence \param [in] method set the type of the time measurement used in the given experiment (defaults to absolute decay time measurement) */ LauDecayTimePdf(const TString& theVarName, const Double_t minAbscissaVal, const Double_t maxAbscissaVal, const TString& theVarErrName, const Double_t minAbscissaErr, const Double_t maxAbscissaErr, std::unique_ptr physicsModel, std::unique_ptr resolutionModel, const TH1* dtErrHist, const LauDecayTime::TimeMeasurementMethod method = LauDecayTime::TimeMeasurementMethod::DecayTime); //! Copy constructor (deleted) LauDecayTimePdf(const LauDecayTimePdf& other) = delete; //! Copy assignment operator (deleted) LauDecayTimePdf& operator=(const LauDecayTimePdf& other) = delete; //! Move constructor (deleted) LauDecayTimePdf(LauDecayTimePdf&& other) = delete; //! Move assignment operator (deleted) LauDecayTimePdf& operator=(LauDecayTimePdf&& other) = delete; //! Destructor ~LauDecayTimePdf() = default; //! Set the efficiency model to be in binned form /*! \param [in] effModel the binned efficiency model */ void setBinnedEfficiency( std::unique_ptr effModel ); //! Set the efficiency model to be in spline interpolated form /*! \param [in] effModel the spline-interpolated efficiency model */ template void setSplineEfficiency( std::unique_ptr> effModel ); //! Get FuncType from model LauDecayTime::FuncType getFuncType() const {return type_;} //! Retrieve the name of the variable const TString& varName() const {return varName_;} //! Retrieve the name of the error variable const TString& varErrName() const {return varErrName_;} // TODO - not sure we need this anymore (at least as a public function) //! Determine if the resolution function is turned on or off bool doSmearing() const {return smear_;} //! Cache information from data /*! \param [in] inputData the dataset to be used to calculate everything */ void cacheInfo(const LauFitDataTree& inputData); //! Calculate the likelihood (and all associated information) given value of the abscissa /*! \param [in] abscissa the value of the abscissa */ void calcLikelihoodInfo(const Double_t abscissa); //! Calculate the likelihood (and all associated information) given value of the abscissa and its error /*! \param [in] abscissa the value of the abscissa \param [in] abscissaErr the error on the abscissa */ void calcLikelihoodInfo(const Double_t abscissa, const Double_t abscissaErr); //! Retrieve the likelihood (and all associated information) given the event number /*! \param [in] iEvt the event number */ void calcLikelihoodInfo(const std::size_t iEvt); // TODO shouldn't be public (maybe will be removed anyway) //! Determine the efficiency value for the given abscissa /*! \param [in] abscissa the value of the abscissa \return the corresponding efficiency value */ Double_t calcEffiTerm( const Double_t abscissa ) const; // TODO - should maybe do away with exp term (and it's norm) since it's just the cosh term when DG=0 and it's confusing to have both // - counter argument is to keep it for backgrounds that have a lifetime-like behaviour // - need to make final decision on this - it is kept for now //! Get the exponential term Double_t getExpTerm() const {return terms_.expTerm;} //! Get the cos(Dm*t) term (multiplied by the exponential) Double_t getCosTerm() const {return terms_.cosTerm;} //! Get the sin(Dm*t) term (multiplied by the exponential) Double_t getSinTerm() const {return terms_.sinTerm;} //! Get the cosh(DG/2*t) term (multiplied by the exponential) Double_t getCoshTerm() const {return terms_.coshTerm;} //! Get the sinh(DG/2*t) term (multiplied by the exponential) Double_t getSinhTerm() const {return terms_.sinhTerm;} //! Get the hist term from a histogram Double_t getHistTerm() const {return histTerm_;} //! Get the normalisation related to the exponential term only Double_t getNormTermExp() const {return normTerms_.expTerm;} //! Get the normalisation related to the cos term only Double_t getNormTermCos() const {return normTerms_.cosTerm;} //! Get the normalisation related to the sin term only Double_t getNormTermSin() const {return normTerms_.sinTerm;} //! Get the first term in the normalisation (from integrating the cosh) Double_t getNormTermCosh() const {return normTerms_.coshTerm;} //! Get the second term in the normalisation (from integrating the sinh) Double_t getNormTermSinh() const {return normTerms_.sinhTerm;} //! Get error probability density from Error distribution Double_t getErrTerm() const{return errTerm_;} //! Get efficiency probability density from efficiency distribution Double_t getEffiTerm() const{return effiTerm_;} //! Retrieve the parameters of the PDF, e.g. so that they can be loaded into a fit /*! \return the parameters of the PDF */ const std::vector& getParameters() const { return params_; } //! Retrieve the parameters of the PDF, e.g. so that they can be loaded into a fit /*! \return the parameters of the PDF */ std::vector& getParameters() { return params_; } //! Update the pulls for all parameters void updatePulls(); //! Generate the value of the error /*! If scaling by the error should call this before calling generate \param [in] forceNew forces generation of a new value \return the generated decay time error */ Double_t generateError(const bool forceNew = kFALSE); //! Generate the value of the decay time /*! NB this only makes sense for cases where the decay time and DP are not intrinsically linked, i.e. not the ExpTrig and ExpHypTrig cases. Simple correlations with the DP position (e.g. of the resolution function parameters) can be handled using the kinematics parameter. \param [in] kinematics allows to determine the DP position \return the generated decay time */ Double_t generate(const LauKinematics* kinematics); + //! Determine the maximum of the efficiency distribution + /*! + \return the maximum efficiency + */ + Double_t getMaxEfficiency(); + //! Determine the maximum height of the PDF /*! NB this only makes sense for cases where the decay time and DP are not intrinsically linked, i.e. not the ExpTrig and ExpHypTrig cases. Simple correlations with the DP position (e.g. of the resolution function parameters) can be handled using the kinematics parameter. \param [in] kinematics allows to determine the DP position \return the PDF maximum */ Double_t getMaxHeight(const LauKinematics* kinematics); //! Retrieve the decay time minimum value Double_t minAbscissa() const {return minAbscissa_;} //! Retrieve the decay time maximum value Double_t maxAbscissa() const {return maxAbscissa_;} //! Retrieve the decay time error minimum value Double_t minAbscissaError() const {return minAbscissaError_;} //! Retrieve the decay time error maximum value Double_t maxAbscissaError() const {return maxAbscissaError_;} //! Propagate any updates necessary to the decay time Efficiency and recalculate normalisation if necessary void propagateParUpdates(); //! Set up the initial state correctly - called by the fit model's initialise function void initialise(); //! Retrieve the number of PDF parameters /*! \return the number of PDF parameters */ std::size_t nParameters() const {return params_.size();} private: //! Update the cache values for all events void updateCache(); //! Determine if any parameters in the supplied container are floating /*! \param [in] pars the container of parameters \return true if any parameter is floating, false if none are */ bool anyParFloating( const std::vector& pars ) const; //! Add all parameters in the supplied container to our internal store /*! \param [in] pars the container of parameters */ void addParams( std::vector& pars ); //! Which type of decay time function is this? const LauDecayTime::FuncType type_; //! Are we using absolute decay time or decay time difference? const LauDecayTime::TimeMeasurementMethod method_{LauDecayTime::TimeMeasurementMethod::DecayTime}; //! Name of the decay time variable const TString varName_; //! Name of the decay time error variable const TString varErrName_{""}; //! The minimum value of the decay time const Double_t minAbscissa_; //! The maximum value of the decay time const Double_t maxAbscissa_; //! The minimum value of the decay time error const Double_t minAbscissaError_{0.0}; //! The maximum value of the decay time error const Double_t maxAbscissaError_{0.0}; //! The physics model std::unique_ptr physicsModel_; //! The resolution model std::unique_ptr resolutionModel_; //! The efficiency model std::unique_ptr efficiencyModel_; //! The calculator of the numerator terms std::unique_ptr calculator_; //! The calculator of the normalisation terms std::unique_ptr integrator_; //! The parameters of the PDF std::vector params_; //! Smear with a resolution model? const bool smear_{false}; //! Resolution uses per-event error? const bool scaleWithPerEventError_{false}; //! The current value of the decay time error Double_t abscissaError_{0.0}; //! Flag whether a value for the decay time error has been generated bool abscissaErrorGenerated_{false}; //! The numerator terms LauDecayTimeTerms terms_; //! The normalisation terms LauDecayTimeNormTerms normTerms_; //! Error PDF (NB there is no equivalent cache since the PDF errHist_ keeps a cache) Double_t errTerm_{0.0}; //! Efficiency Double_t effiTerm_{0.0}; //! Hist PDF term (NB there is no equivalent cache since the PDF pdfHist_ keeps a cache) Double_t histTerm_{0.0}; //! The maximum height of the PDF (used for generating in Exp, Delta, DeltaExp cases) Double_t maxHeight_{0.0}; - //! Flag to indicate if the maxHeight_ value it up-to-date + //! Flag to indicate if the maxHeight_ value is up-to-date bool heightUpToDate_{false}; + //! The maximum value of the efficiency distribution + Double_t maxEff_{1.0}; + + //! Flag to indicate if the maxEff_ value is up-to-date + bool maxEffUpToDate_{false}; + //! The cache of the decay times std::vector abscissas_; //! The cache of the per-event errors on the decay time std::vector abscissaErrors_; //! The cache of the numerator terms std::vector termsStore_; //! The cache of the normalisation terms std::vector normTermsStore_; //! The cache of the efficiency std::vector effiTerms_; //! Histogram PDF for abscissa distribution std::unique_ptr pdfHist_; //! Histogram PDF for abscissa error distribution std::unique_ptr errHist_; // Caching / bookkeeping //! Are any parameters floating in the fit? bool anythingFloating_{false}; //! Are any physics parameters floating in the fit? bool physicsParFloating_{false}; //! Are any resolution parameters floating in the fit? bool resoParFloating_{false}; //! Are any efficiency parameters floating in the fit? bool effiParFloating_{false}; //! Have any parameters changed in the latest fit iteration? bool anythingChanged_{false}; //! Have any physics parameters changed in the latest fit iteration? bool physicsParChanged_{false}; //! Have any resolution parameters changed in the latest fit iteration? bool resoParChanged_{false}; //! Have any efficiency parameters changed in the latest fit iteration? bool effiParChanged_{false}; ClassDef(LauDecayTimePdf,0) // Define the Delta t PDF }; template void LauDecayTimePdf::setSplineEfficiency( std::unique_ptr> effModel ) { if ( not effModel ) { std::cerr << "WARNING in LauDecayTimePdf::setSplineEfficiency : supplied spline efficiency model pointer is null" << std::endl; return; } // Create the approptiate integrator // NB need to use effModel here since it needs to be of concrete type if ( smear_ ) { integrator_ = std::make_unique>( minAbscissa_, maxAbscissa_, *physicsModel_, *effModel, *resolutionModel_ ); } else { integrator_ = std::make_unique>( minAbscissa_, maxAbscissa_, *physicsModel_, *effModel ); } // Store the efficiency model (as a pointer to base) efficiencyModel_ = std::move(effModel); } #endif diff --git a/inc/LauSplineDecayTimeEfficiency.hh b/inc/LauSplineDecayTimeEfficiency.hh index e78091c..21393f8 100644 --- a/inc/LauSplineDecayTimeEfficiency.hh +++ b/inc/LauSplineDecayTimeEfficiency.hh @@ -1,449 +1,446 @@ /* Copyright 2021 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 LauSplineDecayTimeEfficiency.hh \brief File containing declaration of LauSplineDecayTimeEfficiency class. */ /*! \class LauSplineDecayTimeEfficiency \brief Class for defining a spline-interpolated model for decay time efficiency */ #ifndef LAU_SPLINE_DECAYTIME_EFFICIENCY #define LAU_SPLINE_DECAYTIME_EFFICIENCY #include #include #include #include "Rtypes.h" #include "TFitResult.h" #include "TMath.h" #include "TSystem.h" #include "Lau1DCubicSpline.hh" #include "LauAbsDecayTimeEfficiency.hh" #include "LauParameter.hh" class TH1; //! Defines the allowed orders of spline polynomials enum class LauSplineOrder : std::size_t { Cubic = 3, //!< 3rd order Sixth = 6 //!< 6th order }; template class LauSplineDecayTimeEfficiency : public LauAbsDecayTimeEfficiency { public: //! Constructor for a Cubic spline /*! \param [in] prefix the prefix to use when forming the names of the knot parameters \param [in] effSpline the cubic spline to be used to represent the efficiency variation */ template = true> LauSplineDecayTimeEfficiency( const TString& prefix, std::unique_ptr effSpline ) : prefix_{prefix}, effSpline_{std::move(effSpline)} { this->initialSetup(); } //! Constructor for a Sixth order spline /*! \param [in] prefix the prefix to use when forming the names of the knot parameters \param [in] effSpline the cubic spline being used to represent the efficiency variation in another channel \param [in] correctionSpline the cubic spline to be used to represent the correction to effSpline to obtain the efficiency variation for this channel */ template = true> LauSplineDecayTimeEfficiency( const TString& prefix, const LauSplineDecayTimeEfficiency& effSpline, std::unique_ptr correctionSpline ) : prefix_{prefix}, effSpline_{std::move(correctionSpline)}, otherSpline_{std::make_unique>(effSpline)} { this->initialSetup(); } //! Destructor ~LauSplineDecayTimeEfficiency() = default; //! Move constructor (default) LauSplineDecayTimeEfficiency(LauSplineDecayTimeEfficiency&& other) = default; //! Move assignment operator (default) LauSplineDecayTimeEfficiency& operator=(LauSplineDecayTimeEfficiency&& other) = default; //! Copy constructor (custom) LauSplineDecayTimeEfficiency(const LauSplineDecayTimeEfficiency& other); //! Copy assignment operator (deleted) LauSplineDecayTimeEfficiency& operator=(const LauSplineDecayTimeEfficiency& other) = delete; //! The number of coefficients of each spline segment static constexpr std::size_t nCoeffs { static_cast>(Order) + 1 }; //! Retrieve the efficiency for a given value of the decay time /*! \param abscissa the value of the decay time \return the efficiency */ Double_t getEfficiency( const Double_t abscissa ) const override; + //! Find the maximum value of the efficiency in the range + /*! + Works analytically for cubic splines and numerically for 6th order splines + + \return the maximum of the spline + */ + Double_t findMaximum() const override; + //! Retrieve the parameters of the efficiency model so that they can be loaded into a fit /*! \return the parameters of the efficiency model */ std::vector getParameters() override { return params_; } //! Initialise the parameter cache /*! Must be called prior to starting fitting or generation */ void initialise() override; //! Propagate any updates to parameters and recalculate information as neeeded /*! Should be called at each fit iteration */ void propagateParUpdates() override; //! Retrieve the number of segments in the spline std::size_t nSegments() const { return effSpline_->getnKnots() - 1; } //! Retrieve the positions of the spline knots const std::vector& knotPositions() const { return effSpline_->getXValues(); } //! Fix all knots void fixKnots(); //! Float all knots void floatKnots(); //! Fix or float a specific knot /*! \param knotIndex the index of the knot to fix/float \param fixed true if knot to be fixed, false if knot to be floated */ void fixKnot( const std::size_t knotIndex, const bool fixed ); //! Retrieve the polynomial coefficients for the given spline segment /*! \param segmentIndex the index of the spline segment \return the polynomial coefficients */ std::array getCoefficients( const std::size_t segmentIndex ) const; //! Retrieve whether any of the parameters are floating in the fit bool anythingFloating() const { return anyKnotFloating_; } //! Retrieve whether any of the parameters have changed in the latest fit iteration const bool& anythingChanged() const override { return anyKnotChanged_; } //! Fit our spline to a TH1 /*! Useful to obtain reasonable starting values and uncertainties for the knot parameters \param [in] hist the histogram to be fit to \param [in] printLevel the level of printout desired from fit \param [in] doWL If true do a weighted likelihood fit, else chi2 */ void fitToTH1( TH1* hist, const LauOutputLevel printLevel = LauOutputLevel::Quiet, const bool doWL = false ); - //! Find the maximum of the spline - /*! - Works analytically for cubic splines and numerically for 6th order splines - - \return the maximum of the spline - */ - Double_t findMaximum() const; - private: //! Perform the initial setup - shared by the various constructors void initialSetup( const LauSplineDecayTimeEfficiency* other = nullptr ); //! Update the cached parameter values void updateParameterCache(); //! The prefix for the parameter names const TString prefix_; //! The spline std::unique_ptr effSpline_; //! The other spline std::unique_ptr> otherSpline_; //! The spline parameters std::vector> ownedParams_; //! The spline parameters (for giving access) std::vector params_; //! The spline values std::vector values_; //! Are any of our knot parameters floating in the fit? bool ourKnotsFloating_{false}; //! Are any of the other spline's knot parameters floating in the fit? bool otherKnotsFloating_{false}; //! Are any of the knot parameters floating in the fit? bool anyKnotFloating_{false}; //! Have any of our knot parameters changed in the latest fit iteration? bool ourKnotsChanged_{false}; //! Have any of the other spline's knot parameters changed in the latest fit iteration? bool otherKnotsChanged_{false}; //! Have any of the knot parameters changed in the lastest fit iteration? bool anyKnotChanged_{false}; ClassDefOverride(LauSplineDecayTimeEfficiency, 0) }; templateClassImp(LauSplineDecayTimeEfficiency); template void LauSplineDecayTimeEfficiency::initialSetup( const LauSplineDecayTimeEfficiency* other ) { if ( not effSpline_ ) { std::cerr<<"ERROR in LauSplineDecayTimeEfficiency::initialSetup : supplied efficiency spline pointer is null"<Exit(EXIT_FAILURE); } if constexpr ( Order == LauSplineOrder::Sixth ) { std::vector ourKnots { effSpline_->getXValues() }; std::vector otherKnots { otherSpline_->knotPositions() }; if ( ourKnots != otherKnots ) { std::cerr<<"ERROR in LauSplineDecayTimeEfficiency::initialSetup : mismatch in knot positions"<Exit(EXIT_FAILURE); } // TODO - any other checks we need to do? } values_ = effSpline_->getYValues(); const std::size_t nPars { values_.size() }; ownedParams_.reserve( nPars ); if ( other ) { for ( auto& ptr : other->ownedParams_ ) { // TODO - maybe need a way to give these a unique prefix? ownedParams_.emplace_back( ptr->createClone() ); } } else { for( std::size_t index{0}; index < nPars; ++index ) { constexpr Double_t maxVal { (Order == LauSplineOrder::Cubic) ? 1.0 : 2.0 }; ownedParams_.emplace_back( std::make_unique( Form( "%s_knot_%lu", prefix_.Data(), index ), values_[index], 0.0, maxVal, kTRUE ) ); } } if constexpr ( Order == LauSplineOrder::Sixth ) { params_ = otherSpline_->getParameters(); params_.reserve( 2*nPars ); } else { params_.reserve( nPars ); } for ( auto& ptr : ownedParams_ ) { params_.push_back( ptr.get() ); } } template LauSplineDecayTimeEfficiency::LauSplineDecayTimeEfficiency(const LauSplineDecayTimeEfficiency& other) : prefix_{ other.prefix_ }, effSpline_{ std::make_unique( * other.effSpline_ ) }, otherSpline_{ other.otherSpline_ ? std::make_unique>( *other.otherSpline_ ) : nullptr } { this->initialSetup( &other ); } template void LauSplineDecayTimeEfficiency::fixKnots() { for ( auto& ptr : ownedParams_ ) { ptr->fixed(true); } } template void LauSplineDecayTimeEfficiency::floatKnots() { for ( auto& ptr : ownedParams_ ) { ptr->fixed(false); } } template void LauSplineDecayTimeEfficiency::fixKnot( const std::size_t knotIndex, const bool fixed ) { if ( knotIndex >= ownedParams_.size() ) { std::cerr<<"ERROR in LauSplineDecayTimeEfficiency::fixKnot : supplied knot index is out of range"<fixed(fixed); } template Double_t LauSplineDecayTimeEfficiency::getEfficiency( const Double_t abscissa ) const { Double_t eff { effSpline_->evaluate( abscissa ) }; if constexpr ( Order == LauSplineOrder::Sixth ) { eff *= otherSpline_->getEfficiency( abscissa ); } return eff; } template std::array::nCoeffs> LauSplineDecayTimeEfficiency::getCoefficients( const std::size_t segmentIndex ) const { if constexpr ( Order == LauSplineOrder::Cubic ) { return effSpline_->getCoefficients(segmentIndex); } else { std::array ourCoeffs { effSpline_->getCoefficients(segmentIndex) }; std::array otherCoeffs { otherSpline_->getCoefficients(segmentIndex) }; std::array coeffs; coeffs[0] = ourCoeffs[0] * otherCoeffs[0]; coeffs[1] = ourCoeffs[0] * otherCoeffs[1] + ourCoeffs[1] * otherCoeffs[0]; coeffs[2] = ourCoeffs[0] * otherCoeffs[2] + ourCoeffs[1] * otherCoeffs[1] + ourCoeffs[2] * otherCoeffs[0]; coeffs[3] = ourCoeffs[0] * otherCoeffs[3] + ourCoeffs[1] * otherCoeffs[2] + ourCoeffs[2] * otherCoeffs[1] + ourCoeffs[3] * otherCoeffs[0]; coeffs[4] = ourCoeffs[1] * otherCoeffs[3] + ourCoeffs[2] * otherCoeffs[2] + ourCoeffs[3] * otherCoeffs[1]; coeffs[5] = ourCoeffs[2] * otherCoeffs[3] + ourCoeffs[3] * otherCoeffs[2]; coeffs[6] = ourCoeffs[3] * otherCoeffs[3]; return coeffs; } } template void LauSplineDecayTimeEfficiency::initialise() { static auto isFixed = []( const std::unique_ptr& par ){ return par->fixed(); }; anyKnotFloating_ = ourKnotsFloating_ = not std::all_of( ownedParams_.begin(), ownedParams_.end(), isFixed ); if constexpr ( Order == LauSplineOrder::Sixth ) { otherSpline_->initialise(); otherKnotsFloating_ = otherSpline_->anythingFloating(); anyKnotFloating_ |= otherKnotsFloating_; } this->updateParameterCache(); } template void LauSplineDecayTimeEfficiency::updateParameterCache() { static auto assignValue = []( const std::unique_ptr& par ){ return par->unblindValue(); }; // Update our local cache std::transform( ownedParams_.begin(), ownedParams_.end(), values_.begin(), assignValue ); // Update the spline itself effSpline_->updateYValues( values_ ); } template void LauSplineDecayTimeEfficiency::propagateParUpdates() { // If none of the parameters are floating there's nothing to do if ( not anyKnotFloating_ ) { return; } // Otherwise, determine which of the floating parameters have changed (if any) and act accordingly if ( ourKnotsFloating_ ) { static auto checkEquality = []( const std::unique_ptr& par, const Double_t cacheVal ){ return par->unblindValue() == cacheVal; }; anyKnotChanged_ = ourKnotsChanged_ = not std::equal( ownedParams_.begin(), ownedParams_.end(), values_.begin(), checkEquality); // Update the acceptance spline if any of the knot values have changed if ( ourKnotsChanged_ ) { this->updateParameterCache(); } } if constexpr ( Order == LauSplineOrder::Sixth ) { if ( otherKnotsFloating_ ) { otherSpline_->propagateParUpdates(); otherKnotsChanged_ = otherSpline_->anythingChanged(); anyKnotChanged_ |= otherKnotsChanged_; } } } template void LauSplineDecayTimeEfficiency::fitToTH1( TH1* hist, const LauOutputLevel printLevel, const bool doWL ) { std::cout << "INFO in LauSplineDecayTimeEfficiency::fitToTH1 : fitting " << prefix_ << " spline to supplied histogram \"" << hist->GetName() << "\"\n"; std::cout << " : to obtain initial estimates of parameter values and errors" << std::endl; TFitResultPtr fitResult { effSpline_->fitToTH1( hist, printLevel, doWL ) }; if ( fitResult->Status() != 0 || fitResult->CovMatrixStatus() < 2 ) { std::cerr << "WARNING in LauSplineDecayTimeEfficiency::fitToTH1 : fit failed with status " << fitResult->Status() << " and covariance matrix status " << fitResult->CovMatrixStatus() << "\n"; std::cerr << " : will not update spline parameters based on this fit result" << std::endl; return; } if ( fitResult->CovMatrixStatus() == 2 ) { std::cerr << "WARNING in LauSplineDecayTimeEfficiency::fitToTH1 : final covariance matrix not positive definite\n"; std::cerr << " : continuing, but double check your fit!" << std::endl; } const std::size_t nKnots { ownedParams_.size() }; for ( std::size_t knot{0}; knot < nKnots; ++knot ) { const Double_t knotVal { fitResult->Value(knot) }; const Double_t knotErr { fitResult->Error(knot) }; std::cout << " : Setting parameter " << ownedParams_[knot]->name() << " to " << knotVal << " +/- " << knotErr << std::endl; ownedParams_[knot]->value( knotVal ); ownedParams_[knot]->genValue( knotVal ); ownedParams_[knot]->initValue( knotVal ); ownedParams_[knot]->error( knotErr ); } this->updateParameterCache(); } template Double_t LauSplineDecayTimeEfficiency::findMaximum() const { - if(Order == LauSplineOrder::Cubic) - {return effSpline_->findMaximum();} - if(Order == LauSplineOrder::Sixth) - { + if constexpr ( Order == LauSplineOrder::Cubic ) { + return effSpline_->findMaximum(); + } else { //Build a lambda to construct a TF1 - auto sixthOrder = [this](Double_t x[], Double_t /*p[]*/) - {return effSpline_->evaluate(x[0])*otherSpline_->effSpline_->evaluate(x[0]);}; - TF1 func("function", sixthOrder, effSpline_->getXValues().front(), otherSpline_->effSpline_->getXValues().back(), 0); + auto sixthOrder = [this](Double_t x[], [[maybe_unused]] Double_t p[]) + {return effSpline_->evaluate(x[0])*otherSpline_->getEfficiency(x[0]);}; + TF1 func("function", sixthOrder, effSpline_->getXValues().front(), effSpline_->getXValues().back(), 0); return func.GetMaximum(func.GetXmin(), func.GetXmax()); } - //If all else fails return 0 - return 0.0; } #endif diff --git a/inc/LauUniformDecayTimeEfficiency.hh b/inc/LauUniformDecayTimeEfficiency.hh index 0ffeee4..9a487fb 100644 --- a/inc/LauUniformDecayTimeEfficiency.hh +++ b/inc/LauUniformDecayTimeEfficiency.hh @@ -1,92 +1,98 @@ /* Copyright 2021 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 LauUniformDecayTimeEfficiency.hh \brief File containing declaration of LauUniformDecayTimeEfficiency class. */ /*! \class LauUniformDecayTimeEfficiency \brief Class for defining a uniform model for decay time efficiency */ #ifndef LAU_UNIFORM_DECAYTIME_EFFICIENCY #define LAU_UNIFORM_DECAYTIME_EFFICIENCY #include #include "Rtypes.h" #include "LauAbsDecayTimeEfficiency.hh" class LauAbsRValue; class LauUniformDecayTimeEfficiency : public LauAbsDecayTimeEfficiency { public: //! Constructor LauUniformDecayTimeEfficiency() = default; //! Constructor explicit LauUniformDecayTimeEfficiency( const Double_t efficiency ) : efficiency_{efficiency} {} //! Retrieve the efficiency for a given value of the decay time /*! \param abscissa the value of the decay time \return the efficiency */ Double_t getEfficiency( [[maybe_unused]] const Double_t abscissa ) const override { return efficiency_; } + //! Find the maximum value of the efficiency in the range + /*! + \return the maximum of the efficiency distribution + */ + Double_t findMaximum() const override { return efficiency_; }; + //! Initialise the parameter cache /*! Must be called prior to starting fitting or generation */ void initialise() override {} //! Propagate any updates to parameters and recalculate information as neeeded /*! Should be called at each fit iteration */ void propagateParUpdates() override {} //! Retrieve whether any of the parameters have changed in the latest fit iteration const bool& anythingChanged() const override { return anythingChanged_; } //! Retrieve the parameters of the efficiency model so that they can be loaded into a fit /*! \return the parameters of the efficiency model */ std::vector getParameters() override { return {}; } private: //! The uniform value of the efficiency const Double_t efficiency_{1.0}; //! Nothing will change but we need to be able to return that information as a reference const bool anythingChanged_{false}; ClassDefOverride(LauUniformDecayTimeEfficiency, 0) }; #endif diff --git a/src/LauBinnedDecayTimeEfficiency.cc b/src/LauBinnedDecayTimeEfficiency.cc index bd38160..a30d819 100644 --- a/src/LauBinnedDecayTimeEfficiency.cc +++ b/src/LauBinnedDecayTimeEfficiency.cc @@ -1,68 +1,73 @@ /* Copyright 2021 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 LauBinnedDecayTimeEfficiency.cc \brief File containing implementation of LauBinnedDecayTimeEfficiency class. */ #include #include #include "TH1.h" #include "LauBinnedDecayTimeEfficiency.hh" ClassImp(LauBinnedDecayTimeEfficiency); LauBinnedDecayTimeEfficiency::LauBinnedDecayTimeEfficiency( const TH1& effHist ) : effHist_{ dynamic_cast( effHist.Clone() ) } { // Make sure ROOT won't try to manage the histogram lifetime effHist_->SetDirectory(nullptr); // Normalise the hist if the (relative) efficiencies have very large values if ( effHist_->GetMaximum() > 1.0 ) { std::cout << "INFO in LauBinnedDecayTimeEfficiency::LauBinnedDecayTimeEfficiency : Supplied histogram for decay time acceptance has very large values: normalising..." << std::endl; effHist_->Scale( 1.0 / effHist_->Integral() ); } } Double_t LauBinnedDecayTimeEfficiency::getEfficiency( const Double_t abscissa ) const { return effHist_->GetBinContent(effHist_->FindFixBin(abscissa)); } +Double_t LauBinnedDecayTimeEfficiency::findMaximum() const +{ + return effHist_->GetBinContent(effHist_->GetMaximumBin()); +} + std::vector LauBinnedDecayTimeEfficiency::getBinningInfo() const { const Int_t nBins { effHist_->GetNbinsX() }; std::vector bins; bins.reserve(nBins); for ( Int_t bin{1}; bin <= nBins; ++bin ) { const Double_t loEdge {effHist_->GetBinLowEdge(bin)}; const Double_t hiEdge {loEdge + effHist_->GetBinWidth(bin)}; const Double_t effVal {effHist_->GetBinContent(bin)}; bins.emplace_back( loEdge, hiEdge, effVal ); } return bins; } diff --git a/src/LauDecayTimePdf.cc b/src/LauDecayTimePdf.cc index bbd9896..0360559 100644 --- a/src/LauDecayTimePdf.cc +++ b/src/LauDecayTimePdf.cc @@ -1,614 +1,624 @@ /* 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 LauDecayTimePdf.cc \brief File containing implementation of LauDecayTimePdf class. */ #include #include #include #include #include #include #include "TMath.h" #include "TRandom.h" #include "TSystem.h" #include "TH1.h" #include "RooMath.h" #include "Lau1DCubicSpline.hh" #include "Lau1DHistPdf.hh" #include "LauConstants.hh" #include "LauComplex.hh" #include "LauDecayTimePdf.hh" #include "LauFitDataTree.hh" #include "LauParameter.hh" #include "LauParamFixed.hh" #include "LauRandom.hh" #include "LauNonSmearedDecayTimeCalculator.hh" #include "LauNonSmearedUniformEfficiencyDecayTimeIntegrator.hh" #include "LauNonSmearedBinnedEfficiencyDecayTimeIntegrator.hh" #include "LauNonSmearedSplineEfficiencyDecayTimeIntegrator.hh" #include "LauSmearedDecayTimeCalculator.hh" #include "LauSmearedUniformEfficiencyDecayTimeIntegrator.hh" #include "LauSmearedBinnedEfficiencyDecayTimeIntegrator.hh" #include "LauSmearedSplineEfficiencyDecayTimeIntegrator.hh" ClassImp(LauDecayTimePdf) LauDecayTimePdf::LauDecayTimePdf(const TString& theVarName, const Double_t minAbscissaVal, const Double_t maxAbscissaVal, const TH1* dtHist, const LauDecayTime::TimeMeasurementMethod method) : type_{LauDecayTime::FuncType::Hist}, method_{method}, varName_{theVarName}, minAbscissa_{minAbscissaVal}, maxAbscissa_{maxAbscissaVal}, pdfHist_{ (dtHist==nullptr) ? nullptr : std::make_unique( varName_, dtHist, minAbscissa_, maxAbscissa_ ) } // TODO - check this, once we've consolidated all the data members { } LauDecayTimePdf::LauDecayTimePdf(const TString& theVarName, const Double_t minAbscissaVal, const Double_t maxAbscissaVal, const TString& theVarErrName, const Double_t minAbscissaErr, const Double_t maxAbscissaErr, const TH1* dtHist, const TH1* dtErrHist, const LauDecayTime::TimeMeasurementMethod method) : type_{LauDecayTime::FuncType::Hist}, method_{method}, varName_{theVarName}, varErrName_{theVarErrName}, minAbscissa_{minAbscissaVal}, maxAbscissa_{maxAbscissaVal}, minAbscissaError_{minAbscissaErr}, maxAbscissaError_{maxAbscissaErr}, pdfHist_{ (dtHist==nullptr) ? nullptr : std::make_unique( varName_, dtHist, minAbscissa_, maxAbscissa_ ) }, errHist_{ (dtErrHist==nullptr) ? nullptr : std::make_unique( varErrName_, dtErrHist, minAbscissaError_, maxAbscissaError_ ) } // TODO - check this, once we've consolidated all the data members { } LauDecayTimePdf::LauDecayTimePdf(const TString& theVarName, const Double_t minAbscissaVal, const Double_t maxAbscissaVal, std::unique_ptr physicsModel, const LauDecayTime::TimeMeasurementMethod method) : type_{physicsModel->getFunctionType()}, method_{method}, varName_{theVarName}, minAbscissa_{minAbscissaVal}, maxAbscissa_{maxAbscissaVal}, physicsModel_{std::move(physicsModel)} // TODO - check this, once we've consolidated all the data members { auto effModel = std::make_unique(1.0); calculator_ = std::make_unique( minAbscissa_, maxAbscissa_, *physicsModel_ ); integrator_ = std::make_unique( minAbscissa_, maxAbscissa_, *physicsModel_, *effModel ); efficiencyModel_ = std::move( effModel ); } LauDecayTimePdf::LauDecayTimePdf(const TString& theVarName, const Double_t minAbscissaVal, const Double_t maxAbscissaVal, std::unique_ptr physicsModel, std::unique_ptr resolutionModel, const LauDecayTime::TimeMeasurementMethod method) : type_{physicsModel->getFunctionType()}, method_{method}, varName_{theVarName}, minAbscissa_{minAbscissaVal}, maxAbscissa_{maxAbscissaVal}, physicsModel_{std::move(physicsModel)}, resolutionModel_{std::move(resolutionModel)}, smear_{true} // TODO - check this, once we've consolidated all the data members { auto effModel = std::make_unique(1.0); calculator_ = std::make_unique( minAbscissa_, maxAbscissa_, *physicsModel_, *resolutionModel_ ); integrator_ = std::make_unique( minAbscissa_, maxAbscissa_, *physicsModel_, *effModel, *resolutionModel_ ); efficiencyModel_ = std::move( effModel ); } LauDecayTimePdf::LauDecayTimePdf(const TString& theVarName, const Double_t minAbscissaVal, const Double_t maxAbscissaVal, const TString& theVarErrName, const Double_t minAbscissaErr, const Double_t maxAbscissaErr, std::unique_ptr physicsModel, std::unique_ptr resolutionModel, const TH1* dtErrHist, const LauDecayTime::TimeMeasurementMethod method) : type_{physicsModel->getFunctionType()}, method_{method}, varName_{theVarName}, varErrName_{theVarErrName}, minAbscissa_{minAbscissaVal}, maxAbscissa_{maxAbscissaVal}, minAbscissaError_{minAbscissaErr}, maxAbscissaError_{maxAbscissaErr}, physicsModel_{std::move(physicsModel)}, resolutionModel_{std::move(resolutionModel)}, smear_{true}, scaleWithPerEventError_{true}, errHist_{ (dtErrHist==nullptr) ? nullptr : std::make_unique( varErrName_, dtErrHist, minAbscissaError_, maxAbscissaError_ ) } // TODO - check this, once we've consolidated all the data members { auto effModel = std::make_unique(1.0); calculator_ = std::make_unique( minAbscissa_, maxAbscissa_, *physicsModel_, *resolutionModel_ ); integrator_ = std::make_unique( minAbscissa_, maxAbscissa_, *physicsModel_, *effModel, *resolutionModel_ ); efficiencyModel_ = std::move( effModel ); } void LauDecayTimePdf::initialise() { if (type_ == LauDecayTime::FuncType::Hist) { if ( not pdfHist_ ) { std::cerr << "ERROR in LauDecayTimePdf::initialise : Hist type should have a histogram PDF supplied" << std::endl; gSystem->Exit(EXIT_FAILURE); } return; } if ( smear_ and scaleWithPerEventError_ ) { if ( not errHist_ ) { std::cerr << "ERROR in LauDecayTimePdf::initialise : scaling with per-event error but no error distribution supplied" << std::endl; gSystem->Exit(EXIT_FAILURE); } } // TODO other consistency checks? // Initialise the physics model physicsModel_->initialise(); // Initialise the resolution model if ( resolutionModel_ ) { resolutionModel_->initialise(); } // Initialise the efficiency model efficiencyModel_->initialise(); // Get all the parameters and consolidate them so we can pass them to the fit model std::vector physicsPars { physicsModel_->getParameters() }; physicsParFloating_ = this->anyParFloating( physicsPars ); this->addParams( physicsPars ); if ( resolutionModel_ ) { std::vector resoPars { resolutionModel_->getParameters() }; resoParFloating_ = this->anyParFloating( resoPars ); this->addParams( resoPars ); } std::vector effiPars { efficiencyModel_->getParameters() }; effiParFloating_ = this->anyParFloating( effiPars ); this->addParams( effiPars ); anythingFloating_ = physicsParFloating_ or resoParFloating_ or effiParFloating_; } void LauDecayTimePdf::cacheInfo(const LauFitDataTree& inputData) { const std::size_t nEvents { inputData.nEvents() }; // If we're a histogram form then there's not so much to do if ( type_ == LauDecayTime::FuncType::Hist ) { // Pass the data to the decay-time PDF for caching pdfHist_->cacheInfo(inputData); // Pass the data to the decay-time error PDF for caching if ( errHist_ ) { errHist_->cacheInfo(inputData); } // Make cache of effiTerms // Efficiency will always be 1 by definition effiTerms_.assign(nEvents,1.0); return; } // Otherwise... // Check that the input data contains the decay time variable bool hasBranch { inputData.haveBranch( varName_ ) }; if (!hasBranch) { std::cerr << "ERROR in LauDecayTimePdf::cacheInfo : Input data does not contain variable \"" << varName_ << "\"" << std::endl; gSystem->Exit(EXIT_FAILURE); } // If we're scaling by the per-event error, also check that the input data contains the decay time error variable const bool needPerEventNormTerms { smear_ and scaleWithPerEventError_ }; if ( needPerEventNormTerms ) { hasBranch = inputData.haveBranch( varErrName_ ); if (!hasBranch) { std::cerr << "ERROR in LauDecayTimePdf::cacheInfo : Input data does not contain variable \"" << varErrName_ << "\"" << std::endl; gSystem->Exit(EXIT_FAILURE); } // Pass the data to the decay-time error PDF for caching errHist_->cacheInfo(inputData); } // Clear the vectors and reserve enough space in the caches of the terms abscissas_.clear(); abscissas_.resize(nEvents); abscissaErrors_.clear(); abscissaErrors_.resize(nEvents); termsStore_.clear(); termsStore_.resize(nEvents); effiTerms_.clear(); effiTerms_.resize(nEvents); // Correctly size the normalisation cache elements // depending on whether we're doing per-event resolution normTermsStore_.clear(); if ( needPerEventNormTerms ) { normTermsStore_.resize(nEvents); } else { normTermsStore_.resize(1); } // Determine the abscissa and abscissa error values for each event for ( std::size_t iEvt {0}; iEvt < nEvents; iEvt++ ) { const LauFitData& dataValues { inputData.getData(iEvt) }; const Double_t abscissa { dataValues.at( varName_ ) }; if ( abscissa > maxAbscissa_ or abscissa < minAbscissa_ ) { std::cerr << "ERROR in LauDecayTimePdf::cacheInfo : Given value of the decay time: " << abscissa << " is outside allowed range: [" << minAbscissa_ << "," << maxAbscissa_ << "]" << std::endl; gSystem->Exit(EXIT_FAILURE); } abscissas_[iEvt] = abscissa; const Double_t abscissaErr { needPerEventNormTerms ? dataValues.at( varErrName_ ) : 0.0 }; if ( errHist_ and ( abscissaErr > maxAbscissaError_ or abscissaErr < minAbscissaError_ ) ) { std::cerr << "ERROR in LauDecayTimePdf::cacheInfo : Given value of the decay-time error: " << abscissaErr << " is outside allowed range: [" << minAbscissaError_ << "," << maxAbscissaError_ << "]." << std::endl; gSystem->Exit(EXIT_FAILURE); } abscissaErrors_[iEvt] = abscissaErr; } // Cache the numerator terms calculator_->cacheInfo( abscissas_, abscissaErrors_ ); // Cache the normalisations integrator_->cacheInfo( abscissaErrors_ ); // Force storing of all info this first time around physicsParChanged_ = true; resoParChanged_ = true; effiParChanged_ = true; this->updateCache(); } bool LauDecayTimePdf::anyParFloating( const std::vector& pars ) const { LauParamFixed isFixed; return not std::all_of( pars.begin(), pars.end(), isFixed ); } void LauDecayTimePdf::addParams( std::vector& pars ) { for ( auto& par : pars ) { params_.push_back( par ); } } void LauDecayTimePdf::updateCache() { // Calculate the values of all terms for each event const std::size_t nEvents { abscissas_.size() }; // If any of the physics or resolution parameters have changed we need // to update all numerator terms if ( physicsParChanged_ or resoParChanged_ ) { for (std::size_t iEvt {0}; iEvt < nEvents; iEvt++) { termsStore_[iEvt] = calculator_->getTerms( iEvt ); } } // If any of the efficiency parameters have changed we need to // recalculate the efficiency if ( effiParChanged_ ) { + maxEffUpToDate_ = false; for (std::size_t iEvt {0}; iEvt < nEvents; iEvt++) { effiTerms_[iEvt] = this->calcEffiTerm( abscissas_[iEvt] ); } } // Calculate the normalisation terms // If we're not doing per-event scaling, // we only need to calculate the normalisations once const std::array nNormEntries { 1, nEvents }; const bool needPerEventNormTerms { smear_ and scaleWithPerEventError_ }; for ( std::size_t iEvt{0}; iEvt < nNormEntries[needPerEventNormTerms]; ++iEvt ) { normTermsStore_[iEvt] = integrator_->getNormTerms( iEvt ); } } void LauDecayTimePdf::calcLikelihoodInfo(const std::size_t iEvt) { // Extract all the terms and their normalisations if (type_ == LauDecayTime::FuncType::Hist) { pdfHist_->calcLikelihoodInfo(iEvt); histTerm_ = pdfHist_->getLikelihood(); } else { terms_ = termsStore_[iEvt]; const bool needPerEventNormTerms { smear_ and scaleWithPerEventError_ }; const std::size_t normTermElement { needPerEventNormTerms * iEvt }; normTerms_ = normTermsStore_[normTermElement]; } // Extract the decay time error PDF value if ( errHist_ ) { errHist_->calcLikelihoodInfo(iEvt); errTerm_ = errHist_->getLikelihood(); } else { errTerm_ = 1.0; } // Extract the decay time efficiency effiTerm_ = effiTerms_[iEvt]; } void LauDecayTimePdf::calcLikelihoodInfo( const Double_t abscissa ) { // Check whether any of the gaussians should be scaled - if any of them should we need the per-event error if ( smear_ and scaleWithPerEventError_ ) { std::cerr << "ERROR in LauDecayTimePdf::calcLikelihoodInfo : Per-event error on decay time not provided, cannot calculate anything." << std::endl; return; } this->calcLikelihoodInfo(abscissa, 0.0); } Double_t LauDecayTimePdf::calcEffiTerm( const Double_t abscissa ) const { Double_t effiTerm { efficiencyModel_->getEfficiency( abscissa ) }; // TODO print warning messages for these, but not every time // - do we even want the upper limit imposed? if ( effiTerm > 1.0 ) { effiTerm = 1.0; } // else if ( effiTerm < 0.0 ) { effiTerm = 0.0; } else if ( effiTerm <= 0.0 ) { effiTerm = 1e-20; } return effiTerm; } void LauDecayTimePdf::calcLikelihoodInfo(const Double_t abscissa, const Double_t abscissaErr) { // Check that the decay time and the decay time error are in valid ranges if ( abscissa > maxAbscissa_ or abscissa < minAbscissa_ ) { std::cerr << "ERROR in LauDecayTimePdf::calcLikelihoodInfo : Given value of the decay time: " << abscissa << " is outside allowed range: [" << minAbscissa_ << "," << maxAbscissa_ << "]" << std::endl; gSystem->Exit(EXIT_FAILURE); } if ( errHist_ and ( abscissaErr > maxAbscissaError_ or abscissaErr < minAbscissaError_ ) ) { std::cerr << "ERROR in LauDecayTimePdf::calcLikelihoodInfo : Given value of the decay-time error: " << abscissaErr << " is outside allowed range: [" << minAbscissaError_ << "," << maxAbscissaError_ << "]." << std::endl; gSystem->Exit(EXIT_FAILURE); } // Calculate the decay time error PDF value if ( errHist_ ) { const std::vector absErrVec {abscissaErr}; errHist_->calcLikelihoodInfo(absErrVec); errTerm_ = errHist_->getLikelihood(); } else { errTerm_ = 1.0; } // For the histogram PDF just calculate that term and return if ( type_ == LauDecayTime::FuncType::Hist ){ pdfHist_->calcLikelihoodInfo(abscissa); histTerm_ = pdfHist_->getLikelihood(); effiTerm_ = 1.0; return; } // Determine the decay time efficiency effiTerm_ = this->calcEffiTerm( abscissa ); // Determine the other terms terms_ = calculator_->calcTerms( abscissa, {1.0, abscissaErr} ); // TODO - do we need to do this? //if ( smear_ and scaleWithPerEventError_ ) { //normTerms_ = integrator_->calcNormTerms( {1.0, abscissaErr} ); //} } Double_t LauDecayTimePdf::generateError( bool forceNew ) { if ( errHist_ && ( forceNew or not abscissaErrorGenerated_ ) ) { LauFitData errData { errHist_->generate(nullptr) }; abscissaError_ = errData.at( varErrName_ ); abscissaErrorGenerated_ = true; } return abscissaError_; } Double_t LauDecayTimePdf::generate( const LauKinematics* kinematics ) { // generateError SHOULD have been called before this // function but will call it here just to make sure // (has no effect if has already been called) abscissaError_ = this->generateError(); Double_t abscissa{0.0}; switch ( type_ ) { case LauDecayTime::FuncType::ExpTrig : case LauDecayTime::FuncType::ExpHypTrig : std::cerr << "ERROR in LauDecayTimePdf::generate : direct generation does not make sense for ExpTrig and ExpHypTrig types" << std::endl; return abscissa; case LauDecayTime::FuncType::Hist : { const LauFitData genAbscissa { pdfHist_ -> generate( kinematics ) }; abscissa = genAbscissa.at(this->varName()); break; } case LauDecayTime::FuncType::Exp : { do { abscissa = LauRandom::randomFun()->Uniform(minAbscissa_,maxAbscissa_); this->calcLikelihoodInfo( abscissa, abscissaError_ ); const Double_t pdfVal { this->getExpTerm() * this->getEffiTerm() }; const Double_t maxVal { this->getMaxHeight(kinematics) }; if ( pdfVal > maxVal ) { std::cerr << "WARNING in LauDecayTimePdf::generate : PDF value = " << pdfVal << " is larger than the maximum PDF height " << maxVal << "\n"; std::cerr << " : This occurs for the abscissa = " << abscissa << "\n"; std::cerr << " : This really should not happen!!" << std::endl; } if ( LauRandom::randomFun()->Rndm() <= pdfVal/maxVal ) { break; } } while ( true ); break; } case LauDecayTime::FuncType::Delta : { // TODO std::cerr << "WARNING in LauDecayTimePdf::generate : generation of Delta case not currently implemented" << std::endl; break; } case LauDecayTime::FuncType::DeltaExp : { // TODO std::cerr << "WARNING in LauDecayTimePdf::generate : generation of DeltaExp case not currently implemented" << std::endl; break; } } // mark that we need a new error to be generated next time abscissaErrorGenerated_ = false; return abscissa; } +Double_t LauDecayTimePdf::getMaxEfficiency() +{ + if ( ! maxEffUpToDate_ ) { + maxEff_ = efficiencyModel_->findMaximum(); + maxEffUpToDate_ = true; + } + return maxEff_; +} + Double_t LauDecayTimePdf::getMaxHeight(const LauKinematics* /*kinematics*/) { if ( heightUpToDate_ ) { return maxHeight_; } // TODO this is brute force - can we do this in a more refined way? // Scan in small increments across the space to find the maximum height const std::size_t nPoints { 1000 }; const Double_t range { maxAbscissa_ - minAbscissa_ }; const Double_t delta { range / nPoints }; maxHeight_ = 0.0; for ( Double_t point {minAbscissa_}; point <= maxAbscissa_; point += delta ) { this->calcLikelihoodInfo(point, abscissaError_); Double_t heightAtPoint { 0.0 }; if ( type_ == LauDecayTime::FuncType::Exp ) { heightAtPoint = this->getExpTerm(); } else { // TODO - implement the Delta and ExpDelta cases std::cerr << "WARNING in LauDecayTimePdf::getMaxHeight : only Exp case currently implemented" << std::endl; } heightAtPoint *= this->getEffiTerm(); if ( heightAtPoint > maxHeight_ ) { maxHeight_ = heightAtPoint; } } // Mutliply by 120% to be on the safe side maxHeight_ *= 1.2; // Mark the height as being up to date // (unless we're scaling by per-event error) heightUpToDate_ = not ( smear_ and scaleWithPerEventError_ ); return maxHeight_; } void LauDecayTimePdf::setBinnedEfficiency( std::unique_ptr effModel ) { if ( not effModel ) { std::cerr << "WARNING in LauDecayTimePdf::setBinnedEfficiency : supplied binned efficiency model pointer is null" << std::endl; return; } // Create the approptiate integrator // NB need to use effModel here since it needs to be of concrete type if ( smear_ ) { integrator_ = std::make_unique( minAbscissa_, maxAbscissa_, *physicsModel_, *effModel, *resolutionModel_ ); } else { integrator_ = std::make_unique( minAbscissa_, maxAbscissa_, *physicsModel_, *effModel ); } // Store the efficiency model (as a pointer to base) efficiencyModel_ = std::move(effModel); } void LauDecayTimePdf::updatePulls() { for ( LauAbsRValue* rValPtr : params_ ) { std::vector params = rValPtr->getPars(); for ( LauParameter* param : params ) { if ( not param->fixed() ) { param->updatePull(); } } } } void LauDecayTimePdf::propagateParUpdates() { // If none of the parameters are floating there's nothing to do if ( not anythingFloating_ ) { return; } physicsModel_->propagateParUpdates(); physicsParChanged_ = physicsModel_->anythingChanged(); if ( resolutionModel_ ) { resolutionModel_->propagateParUpdates(); resoParChanged_ = resolutionModel_->anythingChanged(); } efficiencyModel_->propagateParUpdates(); effiParChanged_ = efficiencyModel_->anythingChanged(); // If nothing has changed, there's nothing to do anythingChanged_ = physicsParChanged_ or resoParChanged_ or effiParChanged_; if ( not anythingChanged_ ) { return; } calculator_->propagateParUpdates(); integrator_->propagateParUpdates(); // Otherwise we need to update the cache this->updateCache(); } diff --git a/src/LauTimeDepFitModel.cc b/src/LauTimeDepFitModel.cc index 7864080..8bf5c67 100644 --- a/src/LauTimeDepFitModel.cc +++ b/src/LauTimeDepFitModel.cc @@ -1,3190 +1,3190 @@ /* 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::Flavour::Unknown), curEvtDecayFlv_(LauFlavTag::Flavour::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 std::size_t nBkgnds { this->nBkgndClasses() }; if ( nBkgnds > 0 ){ usingBkgnd_ = kTRUE; 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){ 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 { 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(); } } // Finalise the pulls on the flavour tagging parameters flavTag_->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 std::size_t nTaggers {flavTag_->getNTaggers()}; 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); if (this->useDP()) { if (signalTree_) { signalTree_->getEmbeddedEvent(kinematicsB0bar_); //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(); //} // LauKinematics* kinematics{nullptr}; switch ( BkgndTypes_[bkgndID] ) { case LauFlavTag::BkgndType::Combinatorial: { // 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 * ( 1.0 - AProdBkgnd_[bkgndID]->unblindValue() ) ) { curEvtTrueTagFlv_ = LauFlavTag::Flavour::B; } else { curEvtTrueTagFlv_ = LauFlavTag::Flavour::Bbar; } kinematics = kinematicsB0_; if ( cpEigenValue_ == CPEigenvalue::QFS ) { 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 { // 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 decay time and its error curEvtDecayTimeErr_ = BkgndDecayTimePdfs_[bkgndID]->generateError(kTRUE); curEvtDecayTime_ = BkgndDecayTimePdfs_[bkgndID]->generate( kinematics ); // 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 ) { + const Double_t tMin = BkgndDecayTimePdfs_[bkgndID]->minAbscissa(); + const Double_t tMax = BkgndDecayTimePdfs_[bkgndID]->maxAbscissa(); + const Double_t maxDtEff { BkgndDecayTimePdfs_[bkgndID]->getMaxEfficiency() }; + // TODO - do we need the factor 2? + const Double_t ASumSqMax { 2.0 * ( BkgndDPModelsB_[bkgndID]->getMaxHeight() + BkgndDPModelsBbar_[bkgndID]->getMaxHeight() ) * maxDtEff }; + 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 and calculate the total A^2 and Abar^2 kinematics = BkgndDPModelsB_[bkgndID]->genUniformPoint(); BkgndDPModelsB_[bkgndID]->calcLikelihoodInfo(kinematics); BkgndDPModelsBbar_[bkgndID]->calcLikelihoodInfo(kinematics); // 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]->getRawValue() }; const Double_t AbarSq { BkgndDPModelsBbar_[bkgndID]->getRawValue() }; // 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() }; // 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 - need to multiply by the max value of dtEff (needs some implementation in LauDecayTimePdf) - // - do we need the factor 2? - 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 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(); } else { nGenLoop_++; } } while (generatedEvent == kFALSE && nGenLoop_ < iterationsMax_); } else { // Hist, Delta, Exp, DeltaExp decay-time types // Since there are no oscillations for these decay-time types, // the true decay flavour must be equal to the true tag flavour // 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 if ( curEvtDecayFlv_ == LauFlavTag::Flavour::B ) { BkgndDPModelsB_[bkgndID]->generate(); kinematics = kinematicsB0_; } else { BkgndDPModelsBbar_[bkgndID]->generate(); kinematics = kinematicsB0bar_; } // generate decay time and its error curEvtDecayTimeErr_ = BkgndDecayTimePdfs_[bkgndID]->generateError(kTRUE); curEvtDecayTime_ = BkgndDecayTimePdfs_[bkgndID]->generate( kinematics ); // 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; } if ( genOK ) { // Make sure both kinematics objects are up-to-date kinematicsB0_->updateKinematics(kinematics->getm13Sq(), kinematics->getm23Sq() ); kinematicsB0bar_->updateKinematics(kinematics->getm13Sq(), kinematics->getm23Sq() ); this->generateExtraPdfValues(BkgndPdfs_[bkgndID], bkgndTree_[bkgndID]); } 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 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 ) { const Double_t bkgndEvents { 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 curEvtDecayFlv_ = LauFlavTag::Flavour::Unknown; if (cpEigenValue_ == QFS){ curEvtDecayFlv_ = flavTag_->getCurEvtDecayFlv(); if ( curEvtDecayFlv_ == LauFlavTag::Flavour::B ) { Abar.zero(); } else if ( curEvtDecayFlv_ == LauFlavTag::Flavour::Bbar ) { 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 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 move to new function as getEvtBkgndLikelihoods? const UInt_t nBkgnds = this->nBkgndClasses(); for ( UInt_t bkgndID(0); bkgndID < nBkgnds; ++bkgndID ) { if ( not usingBkgnd_ ) { bkgndDPLike_[bkgndID] = 0.0; continue; } Double_t omegaBkgnd{1.0}; Double_t omegaBarBkgnd{1.0}; BkgndDecayTimePdfs_[bkgndID]->calcLikelihoodInfo(static_cast(iEvt)); // Consider background type switch ( BkgndTypes_[bkgndID] ) { case LauFlavTag::BkgndType::Combinatorial : { // 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); } bkgndDPLike_[bkgndID] /= ( BkgndDPModelsB_[bkgndID]->getPdfNorm() + BkgndDPModelsBbar_[bkgndID]->getPdfNorm() ); } else { bkgndDPLike_[bkgndID] = 0.5 * BkgndDPModelsB_[bkgndID]->getLikelihood(iEvt); } // ...include the decay time... switch( BkgndDecayTimePdfs_[bkgndID]->getFuncType() ) { case LauDecayTime::FuncType::Hist : bkgndDPLike_[bkgndID] *= BkgndDecayTimePdfs_[bkgndID]->getHistTerm(); 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 if ( curEvtDecayFlv_ == LauFlavTag::Flavour::B ) { Asqbar = 0.0; } else if ( curEvtDecayFlv_ == LauFlavTag::Flavour::Bbar ) { Asq = 0.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] *= ( 0.5 * ftOmegaHypBkgnd ); break; } 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] *= ( 0.5 * ftOmegaHypBkgnd ); break; } 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 { 2.0 * ( (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; } break; } 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; 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 ); } } 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."<