diff --git a/inc/LauAbsCoeffSet.hh b/inc/LauAbsCoeffSet.hh index eebc366..932d14a 100644 --- a/inc/LauAbsCoeffSet.hh +++ b/inc/LauAbsCoeffSet.hh @@ -1,406 +1,449 @@ /* 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 LauAbsCoeffSet.hh \brief File containing declaration of LauAbsCoeffSet class. */ #ifndef LAU_ABS_COEFF_SET #define LAU_ABS_COEFF_SET -#include -#include -#include +#include "TString.h" #include -#include "TString.h" +#include +#include +#include +#include class TRandom; class LauComplex; class LauParameter; /*! \brief Types of coefficient sets The different forms that are implemented for the complex coefficients. Each form is represented by a class that inherits from LauAbsCoeffSet. The corresponding class is named in a simlar manner, replacing "Abs" with the enum label. */ enum class LauCoeffType { MagPhase, /*!< \see LauMagPhaseCoeffSet */ RealImag, /*!< \see LauRealImagCoeffSet */ BelleCP, /*!< \see LauBelleCPCoeffSet */ CartesianCP, /*!< \see LauCartesianCPCoeffSet */ CartesianGammaCP, /*!< \see LauCartesianGammaCPCoeffSet */ CleoCP, /*!< \see LauCleoCPCoeffSet */ MagPhaseCP, /*!< \see LauMagPhaseCPCoeffSet */ NSCCartesianCP, /*!< \see LauNSCCartesianCPCoeffSet */ PolarGammaCP, /*!< \see LauPolarGammaCPCoeffSet */ RealImagCP, /*!< \see LauRealImagCPCoeffSet */ RealImagGammaCP /*!< \see LauRealImagGammaCPCoeffSet */ }; +//! Output stream operator +std::ostream& operator<<( std::ostream& os, const LauCoeffType type ); + /*! \class LauAbsCoeffSet \brief Class for defining the abstract interface for complex coefficient classes. Class for defining the abstract interface for complex coefficient classes. Some common code is implemented but most methods are not. */ class LauAbsCoeffSet { public: //! Options for cloning operation enum class CloneOption { All, /*!< no special operation, all parameters cloned */ TiePhase, /*!< phase cloned, magnitude free to vary */ TieMagnitude, /*!< magnitude cloned, phase free to vary */ TieRealPart, /*!< real part cloned, imaginary part free to vary */ TieImagPart, /*!< imaginary part cloned, real part free to vary */ TieCPPars /*!< CP-violating parameters cloned, CP-conserving ones free to vary */ }; + //! Construct a collection of coefficient objects based on values read from a json file + /*! + \param[in] fileName the name of the file from which the JSON should be read + \return the collection of newly constructed coefficients + */ + static std::vector> readFromJson( const TString& fileName ); + + //! Write a collection of coefficient objects to a json file + /*! + \param[in] fileName the name of the file to which the JSON should be written + \param[in] coeffs the collection of coefficients to be written out + */ + static void writeToJson( const TString& fileName, const std::vector>& coeffs ); + //! Destructor virtual ~LauAbsCoeffSet() = default; + //! Determine the type of the coefficient + /*! + \return the type of the coefficient + */ + virtual LauCoeffType type() const = 0; + //! Retrieve the parameters of the coefficient so that they can be loaded into a fit /*! \return the parameters of the coefficient */ virtual std::vector getParameters() = 0; + //! Retrieve the (const) parameters of the coefficient, e.g. so that they can be queried + /*! + \return the (const) parameters of the coefficient + */ + virtual std::vector getParameters() const = 0; + //! Print the current values of the parameters virtual void printParValues() const = 0; //! Print the column headings for a results table /*! \param [out] stream the stream to print to */ virtual void printTableHeading(std::ostream& stream) const = 0; //! Print the parameters of the complex coefficient as a row in the results table /*! \param [out] stream the stream to print to */ virtual void printTableRow(std::ostream& stream) const = 0; //! Randomise the starting values of the parameters for a fit virtual void randomiseInitValues() = 0; //! Make sure values are in "standard" ranges, e.g. phases should be between -pi and pi virtual void finaliseValues() = 0; //! Retrieve the complex coefficient for a particle /*! \return the complex coefficient for a particle */ virtual const LauComplex& particleCoeff() = 0; //! Retrieve the complex coefficient for an antiparticle /*! \return the complex coefficient for an antiparticle */ virtual const LauComplex& antiparticleCoeff() = 0; //! Set the parameters based on the complex coefficients for particles and antiparticles /*! \param [in] coeff the complex coefficient for a particle \param [in] coeffBar the complex coefficient for an antiparticle \param [in] init whether or not the initial and generated values should also be adjusted */ virtual void setCoeffValues( const LauComplex& coeff, const LauComplex& coeffBar, const Bool_t init ) = 0; //! Calculate the CP asymmetry /*! \return the CP asymmetry */ virtual LauParameter acp() = 0; //! Create a clone of the coefficient set /*! \param [in] newName the clone's name \param [in] cloneOption special option for the cloning operation \param [in] constFactor a constant factor by which to multiply the cloned parameters \return a clone of the coefficient set */ std::unique_ptr createClone(const TString& newName, const CloneOption cloneOption = CloneOption::All, const Double_t constFactor = 1.0) { return std::unique_ptr{this->createClone_impl(newName,cloneOption,constFactor)}; } //! Retrieve the name of the coefficient set /*! The name should correspond to the name of the resonance in the model. \return the name of the coefficient set */ virtual TString name() const {return name_;} //! Set the name of the coefficient set /*! The name should correspond to the name of the resonance in the model. \param [in] theName the name to set */ virtual void name(const TString& theName) {name_ = theName;} //! Retrieve the base name of the coefficient set /*! The base name is generally of the form "Ai", where i is an integer. This is used in the fit results ntuple. \return the base name of the coefficient set */ virtual const TString& baseName() const {return basename_;} //! Set the base name of the coefficient set /*! The base name is generally of the form "Ai", where i is an integer. This is used in the fit results ntuple. \param [in] theBasename the base name to set */ virtual void baseName(const TString& theBasename) {basename_ = theBasename;} //! Retrieve the index number of the coefficient set /*! \return the index number of the coefficient set */ virtual UInt_t index() const {return index_;} //! Set the index number of the coefficient set /*! \param [in] newIndex the new index */ virtual void index(const UInt_t newIndex); //! Set the value of the named parameter /*! \param [in] parName the name of the parameter to adjust \param [in] value the new value for the parameter to take \param [in] init whether or not the initial and generated values should also be adjusted */ virtual void setParameterValue(const TString& parName, const Double_t value, const Bool_t init); //! Set the error of the named parameter /*! This is particularly useful for tuning the step size used by MINUIT \param [in] parName the name of the parameter to adjust \param [in] error the new error value for the parameter to take */ virtual void setParameterError(const TString& parName, const Double_t error); //! Set the named parameter to be fixed in the fit /*! \param [in] parName the name of the parameter to adjust */ virtual void fixParameter(const TString& parName); //! Set the named parameter to float in the fit /*! \param [in] parName the name of the parameter to adjust */ virtual void floatParameter(const TString& parName); //! Blind the named parameter /*! See LauBlind documentation for details of blinding procedure \param [in] parName the name of the parameter to adjust \param [in] blindingString the unique blinding string used to seed the random number generator \param [in] width the width of the Gaussian from which the offset should be sampled */ virtual void blindParameter(const TString& parName, const TString& blindingString, const Double_t width); //! Add Gaussian constraint to the named parameter /*! \param [in] parName the name of the parameter to adjust \param [in] mean the mean of the Gaussian constraint \param [in] width the width of the Gaussian constraint */ virtual void addGaussianConstraint(const TString& parName, const Double_t mean, const Double_t width); //! Add suffix to the name of the given parameter /*! \param [in] parName the name of the parameter to adjust \param [in] suffix the suffix to add to the parameter name */ virtual void addSuffixToParameterName(const TString& parName, const TString& suffix); //! Set the allowed range for magnitude parameters /*! \param [in] minMag the lower edge of the range \param [in] maxMag the upper edge of the range */ static void setMagnitudeRange(const Double_t minMag, const Double_t maxMag) { minMagnitude_ = minMag; maxMagnitude_ = maxMag; } //! Set the allowed range for phase parameters /*! \param [in] minPhase the lower edge of the range \param [in] maxPhase the upper edge of the range */ static void setPhaseRange(const Double_t minPhase, const Double_t maxPhase) { minPhase_ = minPhase; maxPhase_ = maxPhase; } //! Set the allowed range for real/imaginary part parameters /*! \param [in] minPar the lower edge of the range \param [in] maxPar the upper edge of the range */ static void setRealImagRange(const Double_t minPar, const Double_t maxPar) { minRealImagPart_ = minPar; maxRealImagPart_ = maxPar; } //! Set the allowed range for CP-violating parameters /*! \param [in] minPar the lower edge of the range \param [in] maxPar the upper edge of the range */ static void setCPParRange(const Double_t minPar, const Double_t maxPar) { minDelta_ = minPar; maxDelta_ = maxPar; } //! Set the randomiser /*! Set the random number generator to use for randomising parameter starting values. Will default to LauRandom::zeroSeedRandom if not explicitly supplied via this function. \param [in] randomiser the random number generator to use for randomising parameter starting values */ static void setRandomiser(TRandom* randomiser) { randomiser_ = randomiser; } //! Access the randomiser /*! \return the random number generator to use for randomising parameter starting values */ static TRandom* getRandomiser(); protected: //! Constructor /*! \param [in] theName the name of the coefficient set \param [in] theBaseName the single character base for the parameter names */ LauAbsCoeffSet(const TString& theName, const TString& theBaseName = "A"); //! Copy constructor /*! \param [in] rhs the coefficient to clone */ LauAbsCoeffSet(const LauAbsCoeffSet& rhs) = default; //! Move constructor /*! \param [in] rhs the coefficient to clone */ LauAbsCoeffSet(LauAbsCoeffSet&& rhs) = default; //! Copy assignment operator /*! \param [in] rhs the coefficient to clone */ LauAbsCoeffSet& operator=(const LauAbsCoeffSet& rhs) = default; //! Move assignment operator /*! \param [in] rhs the coefficient to clone */ LauAbsCoeffSet& operator=(LauAbsCoeffSet&& rhs) = default; //! Find the parameter with the given name /*! \param [in] parName the name of the parameter to be found return the retrieved parameter */ LauParameter* findParameter(const TString& parName); //! Prepend the base name and index to the name of a parameter /*! \param [in,out] par the parameter to be renamed \param [in] oldBaseName the old base name, which might need to be removed before adding the new one */ virtual void adjustName(LauParameter& par, const TString& oldBaseName); //! Minimum allowed value of magnitude parameters static Double_t minMagnitude_; //! Maximum allowed value of magnitude parameters static Double_t maxMagnitude_; //! Minimum allowed value of phase parameters static Double_t minPhase_; //! Maximum allowed value of phase parameters static Double_t maxPhase_; //! Minimum allowed value of real/imaginary part parameters static Double_t minRealImagPart_; //! Maximum allowed value of real/imaginary part parameters static Double_t maxRealImagPart_; //! Minimum allowed value of CP-violating real/imaginary part parameters static Double_t minDelta_; //! Maximum allowed value of CP-violating real/imaginary part parameters static Double_t maxDelta_; private: //! Create a clone of the coefficient set /*! \param [in] newName the clone's name \param [in] cloneOption special option for the cloning operation \param [in] constFactor a constant factor by which to multiply the cloned parameters \return a clone of the coefficient set */ virtual LauAbsCoeffSet* createClone_impl(const TString& newName, const CloneOption cloneOption, const Double_t constFactor) = 0; //! Random number generator to use for randomising parameter starting values static TRandom* randomiser_; //! The name of the coefficient set TString name_; //! The base name of the coefficient set TString basename_; //! The index number of the coefficient set UInt_t index_{0}; ClassDef(LauAbsCoeffSet, 0) }; //! \cond DOXYGEN_IGNORE // map LauCoeffType values to JSON as strings NLOHMANN_JSON_SERIALIZE_ENUM( LauCoeffType, { {LauCoeffType::MagPhase, "MagPhase"}, {LauCoeffType::RealImag, "RealImag"}, {LauCoeffType::BelleCP, "BelleCP"}, {LauCoeffType::CartesianCP, "CartesianCP"}, {LauCoeffType::CartesianGammaCP, "CartesianGammaCP"}, {LauCoeffType::CleoCP, "CleoCP"}, {LauCoeffType::MagPhaseCP, "MagPhaseCP"}, {LauCoeffType::NSCCartesianCP, "NSCCartesianCP"}, {LauCoeffType::PolarGammaCP, "PolarGammaCP"}, {LauCoeffType::RealImagCP, "RealImagCP"}, {LauCoeffType::RealImagGammaCP, "RealImagGammaCP"}, }) // map Lau1DCubicSpline::BoundaryType values to JSON as strings NLOHMANN_JSON_SERIALIZE_ENUM( LauAbsCoeffSet::CloneOption, { {LauAbsCoeffSet::CloneOption::All, "All"}, {LauAbsCoeffSet::CloneOption::TiePhase, "TiePhase"}, {LauAbsCoeffSet::CloneOption::TieMagnitude, "TieMagnitude"}, {LauAbsCoeffSet::CloneOption::TieRealPart, "TieRealPart"}, {LauAbsCoeffSet::CloneOption::TieImagPart, "TieImagPart"}, {LauAbsCoeffSet::CloneOption::TieCPPars, "TieCPPars"}, }) + +// exception to be thrown in case of JSON type issues +class LauWrongCoeffType : public std::runtime_error { + public: + LauWrongCoeffType(const std::string& what) : std::runtime_error(what) {} +}; + +namespace nlohmann { + template <> + struct adl_serializer { + static void to_json(json& j, const LauAbsCoeffSet& t); + }; +} //! \endcond DOXYGEN_IGNORE #endif diff --git a/inc/LauBelleCPCoeffSet.hh b/inc/LauBelleCPCoeffSet.hh index 9cc2058..ffaf0ab 100644 --- a/inc/LauBelleCPCoeffSet.hh +++ b/inc/LauBelleCPCoeffSet.hh @@ -1,207 +1,235 @@ /* 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 LauBelleCPCoeffSet.hh \brief File containing declaration of LauBelleCPCoeffSet class. */ +#ifndef LAU_BELLECP_COEFF_SET +#define LAU_BELLECP_COEFF_SET + +#include "LauAbsCoeffSet.hh" +#include "LauComplex.hh" +#include "LauParameter.hh" + +#include "Rtypes.h" + +#include +#include +#include + + /*! \class LauBelleCPCoeffSet \brief Class for defining a complex coefficient using the Belle CP convention. Holds a set of real values that define the complex coefficient of an amplitude component. The amplitude has the form a * exp(i*delta) * ( 1 +/- b * exp(i*phi) ) where a is a CP conserving magnitude, b is a CP violating magnitude, delta is the strong phase and phi is the weak phase. [Phys.Rev.Lett. 96 (2006) 251803] */ -#ifndef LAU_BELLECP_COEFF_SET -#define LAU_BELLECP_COEFF_SET - -#include -#include -#include - -#include "Rtypes.h" - -#include "LauAbsCoeffSet.hh" -#include "LauComplex.hh" -#include "LauParameter.hh" - - class LauBelleCPCoeffSet : public LauAbsCoeffSet { public: //! Constructor /*! \param [in] compName the name of the coefficient set \param [in] a the magnitude a \param [in] delta the strong phase \param [in] b the magnitude b \param [in] phi the weak phase \param [in] aFixed whether a is fixed \param [in] deltaFixed whether delta is fixed \param [in] bFixed whether b is fixed \param [in] phiFixed whether phi is fixed \param [in] bSecondStage whether b should be floated only in the second stage of the fit \param [in] phiSecondStage whether phi should be floated only in the second stage of the fit */ LauBelleCPCoeffSet(const TString& compName, const Double_t a, const Double_t delta, const Double_t b, const Double_t phi, const Bool_t aFixed, const Bool_t deltaFixed, const Bool_t bFixed, const Bool_t phiFixed, const Bool_t bSecondStage = kFALSE, const Bool_t phiSecondStage = kFALSE); + //! Move constructor (default) + /*! + \param [in] rhs the coefficient to clone + */ + LauBelleCPCoeffSet(LauBelleCPCoeffSet&& rhs) = default; + + //! Move assignment operator (default) + /*! + \param [in] rhs the coefficient to clone + */ + LauBelleCPCoeffSet& operator=(LauBelleCPCoeffSet&& rhs) = default; + + //! Determine the type of the coefficient + /*! + \return the type of the coefficient + */ + LauCoeffType type() const override { return LauCoeffType::BelleCP; } + //! Retrieve the parameters of the coefficient, e.g. so that they can be loaded into a fit /*! - \return the parameters of the coefficient + \return the parameters of the coefficient [ a, delta, b, phi ] */ - std::vector getParameters() override; + std::vector getParameters() override + { + return { a_.get(), delta_.get(), b_.get(), phi_.get() }; + } + + //! Retrieve the (const) parameters of the coefficient, e.g. so that they can be queried + /*! + \return the (const) parameters of the coefficient [ a, delta, b, phi ] + */ + std::vector getParameters() const override + { + return { a_.get(), delta_.get(), b_.get(), phi_.get() }; + } //! Print the current values of the parameters void printParValues() const override; //! Print the column headings for a results table /*! \param [out] stream the stream to print to */ void printTableHeading(std::ostream& stream) const override; //! Print the parameters of the complex coefficient as a row in the results table /*! \param [out] stream the stream to print to */ void printTableRow(std::ostream& stream) const override; //! Randomise the starting values of the parameters for a fit void randomiseInitValues() override; //! Make sure values are in "standard" ranges, e.g. phases should be between -pi and pi void finaliseValues() override; //! Retrieve the complex coefficient for a particle /*! \return the complex coefficient for a particle */ const LauComplex& particleCoeff() override; //! Retrieve the complex coefficient for an antiparticle /*! \return the complex coefficient for an antiparticle */ const LauComplex& antiparticleCoeff() override; //! Set the parameters based on the complex coefficients for particles and antiparticles /*! \param [in] coeff the complex coefficient for a particle \param [in] coeffBar the complex coefficient for an antiparticle \param [in] init whether or not the initial and generated values should also be adjusted */ void setCoeffValues( const LauComplex& coeff, const LauComplex& coeffBar, const Bool_t init ) override; //! Calculate the CP asymmetry /*! \return the CP asymmetry */ LauParameter acp() override; //! Create a clone of the coefficient set /*! \param [in] newName the clone's name \param [in] cloneOption special option for the cloning operation \param [in] constFactor a constant factor by which to multiply the cloned parameters \return a clone of the coefficient set */ std::unique_ptr createClone(const TString& newName, const CloneOption cloneOption = CloneOption::All, const Double_t constFactor = 1.0) { return std::unique_ptr{this->createClone_impl(newName,cloneOption,constFactor)}; } private: //! Copy constructor (with options) /*! This creates cloned parameters, not copies. \param [in] rhs the coefficient to clone \param [in] cloneOption special option for the cloning operation \param [in] constFactor a constant factor to multiply the clone's parameters by */ LauBelleCPCoeffSet(const LauBelleCPCoeffSet& rhs, const CloneOption cloneOption = CloneOption::All, const Double_t constFactor = 1.0); //! Copy constructor (deleted) /*! \param [in] rhs the coefficient to clone */ LauBelleCPCoeffSet(const LauBelleCPCoeffSet& rhs) = delete; - //! Move constructor (default) - /*! - \param [in] rhs the coefficient to clone - */ - LauBelleCPCoeffSet(LauBelleCPCoeffSet&& rhs) = default; - //! Copy assignment operator (deleted) /*! \param [in] rhs the coefficient to clone */ LauBelleCPCoeffSet& operator=(const LauBelleCPCoeffSet& rhs) = delete; - //! Move assignment operator (default) - /*! - \param [in] rhs the coefficient to clone - */ - LauBelleCPCoeffSet& operator=(LauBelleCPCoeffSet&& rhs) = default; - //! Create a clone of the coefficient set /*! \param [in] newName the clone's name \param [in] cloneOption special option for the cloning operation \param [in] constFactor a constant factor by which to multiply the cloned parameters \return a clone of the coefficient set */ LauBelleCPCoeffSet* createClone_impl(const TString& newName, const LauAbsCoeffSet::CloneOption cloneOption, const Double_t constFactor) override; // the actual fit parameters // (need to be pointers so they can be cloned) //! The magnitude a std::unique_ptr a_; //! The magnitude b std::unique_ptr b_; //! The strong phase std::unique_ptr delta_; //! The weak phase std::unique_ptr phi_; //! The particle complex coefficient LauComplex particleCoeff_; //! The antiparticle complex coefficient LauComplex antiparticleCoeff_; //! The CP asymmetry LauParameter acp_; ClassDefOverride(LauBelleCPCoeffSet, 0) }; +//! \cond DOXYGEN_IGNORE +namespace nlohmann { + template <> + struct adl_serializer { + static LauBelleCPCoeffSet from_json(const json& j); + static void to_json(json& j, const LauBelleCPCoeffSet& t); + }; +} +//! \endcond DOXYGEN_IGNORE + #endif diff --git a/inc/LauCartesianCPCoeffSet.hh b/inc/LauCartesianCPCoeffSet.hh index 657a84c..dc37de5 100644 --- a/inc/LauCartesianCPCoeffSet.hh +++ b/inc/LauCartesianCPCoeffSet.hh @@ -1,203 +1,225 @@ /* 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 LauCartesianCPCoeffSet.hh \brief File containing declaration of LauCartesianCPCoeffSet class. */ /*! \class LauCartesianCPCoeffSet \brief Class for defining a complex coefficient using the Cartesian CP convention. Holds a set of real values that define the complex coefficient of an amplitude component. The amplitude has the form x +/- delta_x + i * ( y +/- delta_y ). [Phys.Rev. D78 (2008) 012004] */ #ifndef LAU_CARTESIANCP_COEFF_SET #define LAU_CARTESIANCP_COEFF_SET #include #include #include #include "Rtypes.h" #include "LauAbsCoeffSet.hh" #include "LauComplex.hh" #include "LauParameter.hh" class LauCartesianCPCoeffSet : public LauAbsCoeffSet { public: //! Constructor /*! \param [in] compName the name of the coefficient set \param [in] x the average real part \param [in] y the average imaginary part \param [in] deltaX the asymmetric real part \param [in] deltaY the asymmetric imaginary part \param [in] xFixed whether x is fixed \param [in] yFixed whether y is fixed \param [in] deltaXFixed whether deltaX is fixed \param [in] deltaYFixed whether deltaY is fixed \param [in] deltaXSecondStage whether deltaX should be floated only in the second stage of the fit \param [in] deltaYSecondStage whether deltaY should be floated only in the second stage of the fit */ LauCartesianCPCoeffSet(const TString& compName, const Double_t x, const Double_t y, const Double_t deltaX, const Double_t deltaY, const Bool_t xFixed, const Bool_t yFixed, const Bool_t deltaXFixed, const Bool_t deltaYFixed, const Bool_t deltaXSecondStage = kFALSE, const Bool_t deltaYSecondStage = kFALSE); + //! Move constructor (default) + /*! + \param [in] rhs the coefficient to clone + */ + LauCartesianCPCoeffSet(LauCartesianCPCoeffSet&& rhs) = default; + + //! Move assignment operator (default) + /*! + \param [in] rhs the coefficient to clone + */ + LauCartesianCPCoeffSet& operator=(LauCartesianCPCoeffSet&& rhs) = default; + + //! Determine the type of the coefficient + /*! + \return the type of the coefficient + */ + LauCoeffType type() const override { return LauCoeffType::CartesianCP; } + //! Retrieve the parameters of the coefficient, e.g. so that they can be loaded into a fit /*! - \return the parameters of the coefficient + \return the parameters of the coefficient [ x, y, deltaX, deltaY ] */ std::vector getParameters() override; + //! Retrieve the (const) parameters of the coefficient, e.g. so that they can be queried + /*! + \return the (const) parameters of the coefficient [ x, y, deltaX, deltaY ] + */ + std::vector getParameters() const override; + //! Print the current values of the parameters void printParValues() const override; //! Print the column headings for a results table /*! \param [out] stream the stream to print to */ void printTableHeading(std::ostream& stream) const override; //! Print the parameters of the complex coefficient as a row in the results table /*! \param [out] stream the stream to print to */ void printTableRow(std::ostream& stream) const override; //! Randomise the starting values of the parameters for a fit void randomiseInitValues() override; //! Make sure values are in "standard" ranges, e.g. phases should be between -pi and pi void finaliseValues() override; //! Retrieve the complex coefficient for a particle /*! \return the complex coefficient for a particle */ const LauComplex& particleCoeff() override; //! Retrieve the complex coefficient for an antiparticle /*! \return the complex coefficient for an antiparticle */ const LauComplex& antiparticleCoeff() override; //! Set the parameters based on the complex coefficients for particles and antiparticles /*! \param [in] coeff the complex coefficient for a particle \param [in] coeffBar the complex coefficient for an antiparticle \param [in] init whether or not the initial and generated values should also be adjusted */ void setCoeffValues( const LauComplex& coeff, const LauComplex& coeffBar, const Bool_t init ) override; //! Calculate the CP asymmetry /*! \return the CP asymmetry */ LauParameter acp() override; //! Create a clone of the coefficient set /*! \param [in] newName the clone's name \param [in] cloneOption special option for the cloning operation \param [in] constFactor a constant factor to multiply the clone's parameters by \return a clone of the coefficient set */ std::unique_ptr createClone(const TString& newName, const CloneOption cloneOption = CloneOption::All, const Double_t constFactor = 1.0) { return std::unique_ptr{this->createClone_impl(newName,cloneOption,constFactor)}; } private: //! Copy constructor (with options) /*! This creates cloned parameters, not copies. \param [in] rhs the coefficient to clone \param [in] cloneOption special option for the cloning operation \param [in] constFactor a constant factor to multiply the clone's parameters by */ LauCartesianCPCoeffSet(const LauCartesianCPCoeffSet& rhs, CloneOption cloneOption = CloneOption::All, Double_t constFactor = 1.0); //! Copy constructor (deleted) /*! \param [in] rhs the coefficient to clone */ LauCartesianCPCoeffSet(const LauCartesianCPCoeffSet& rhs) = delete; - //! Move constructor (default) - /*! - \param [in] rhs the coefficient to clone - */ - LauCartesianCPCoeffSet(LauCartesianCPCoeffSet&& rhs) = default; - //! Copy assignment operator (deleted) /*! \param [in] rhs the coefficient to clone */ LauCartesianCPCoeffSet& operator=(const LauCartesianCPCoeffSet& rhs) = delete; - //! Move assignment operator (default) - /*! - \param [in] rhs the coefficient to clone - */ - LauCartesianCPCoeffSet& operator=(LauCartesianCPCoeffSet&& rhs) = default; - //! Create a clone of the coefficient set /*! \param [in] newName the clone's name \param [in] cloneOption special option for the cloning operation \param [in] constFactor a constant factor by which to multiply the cloned parameters \return a clone of the coefficient set */ LauCartesianCPCoeffSet* createClone_impl(const TString& newName, const LauAbsCoeffSet::CloneOption cloneOption, const Double_t constFactor) override; // the actual fit parameters // (need to be pointers so they can be cloned) //! The average real part std::unique_ptr x_; //! The average imaginary part std::unique_ptr y_; //! The asymmetric real part std::unique_ptr deltaX_; //! The asymmetric imaginary part std::unique_ptr deltaY_; //! The particle complex coefficient LauComplex particleCoeff_; //! The antiparticle complex coefficient LauComplex antiparticleCoeff_; //! The CP asymmetry LauParameter acp_; ClassDefOverride(LauCartesianCPCoeffSet, 0) }; +//! \cond DOXYGEN_IGNORE +namespace nlohmann { + template <> + struct adl_serializer { + static LauCartesianCPCoeffSet from_json(const json& j); + static void to_json(json& j, const LauCartesianCPCoeffSet& t); + }; +} +//! \endcond DOXYGEN_IGNORE + #endif diff --git a/inc/LauCartesianGammaCPCoeffSet.hh b/inc/LauCartesianGammaCPCoeffSet.hh index 0a95f84..3919e50 100644 --- a/inc/LauCartesianGammaCPCoeffSet.hh +++ b/inc/LauCartesianGammaCPCoeffSet.hh @@ -1,219 +1,241 @@ /* Copyright 2014 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 LauCartesianGammaCPCoeffSet.hh \brief File containing declaration of LauCartesianGammaCPCoeffSet class. */ /*! \class LauCartesianGammaCPCoeffSet \brief Class for defining a complex coefficient using the Cartesian gamma CP convention. Holds a set of real values that define the complex coefficient of an amplitude component. The amplitude has the form ( x + i * y ) * ( 1 + xCP +/- delta_xCP + i * ( yCP +/- delta_yCP ) ). [Phys. Rev. D79, 051301 (2009)] */ #ifndef LAU_CARTESIANGAMMACP_COEFF_SET #define LAU_CARTESIANGAMMACP_COEFF_SET #include #include #include #include "Rtypes.h" #include "LauAbsCoeffSet.hh" #include "LauComplex.hh" #include "LauParameter.hh" class LauCartesianGammaCPCoeffSet : public LauAbsCoeffSet { public: //! Constructor /*! \param [in] compName the name of the coefficient set \param [in] x the real nonCP part \param [in] y the imaginary nonCP part \param [in] xCP the average real CP part \param [in] yCP the average imaginary CP part \param [in] deltaXCP the asymmetric real CP part \param [in] deltaYCP the asymmetric imaginary CP part \param [in] xFixed whether x is fixed \param [in] yFixed whether y is fixed \param [in] xCPFixed whether xCP is fixed \param [in] yCPFixed whether yCP is fixed \param [in] deltaXCPFixed whether deltaXCP is fixed \param [in] deltaYCPFixed whether deltaYCP is fixed \param [in] deltaXCPSecondStage whether deltaXCP should be floated only in the second stage of the fit \param [in] deltaYCPSecondStage whether deltaYCP should be floated only in the second stage of the fit */ LauCartesianGammaCPCoeffSet(const TString& compName, const Double_t x, const Double_t y, const Double_t xCP, const Double_t yCP, const Double_t deltaXCP, const Double_t deltaYCP, const Bool_t xFixed, const Bool_t yFixed, const Bool_t xCPFixed, const Bool_t yCPFixed, const Bool_t deltaXCPFixed, const Bool_t deltaYCPFixed, const Bool_t deltaXCPSecondStage = kFALSE, const Bool_t deltaYCPSecondStage = kFALSE); + //! Move constructor (default) + /*! + \param [in] rhs the coefficient to clone + */ + LauCartesianGammaCPCoeffSet(LauCartesianGammaCPCoeffSet&& rhs) = default; + + //! Move assignment operator (default) + /*! + \param [in] rhs the coefficient to clone + */ + LauCartesianGammaCPCoeffSet& operator=(LauCartesianGammaCPCoeffSet&& rhs) = default; + + //! Determine the type of the coefficient + /*! + \return the type of the coefficient + */ + LauCoeffType type() const override { return LauCoeffType::CartesianGammaCP; } + //! Retrieve the parameters of the coefficient, e.g. so that they can be loaded into a fit /*! - \return the parameters of the coefficient + \return the parameters of the coefficient [ x, y, xCP, yCP, deltaXCP, deltaYCP ] */ std::vector getParameters() override; + //! Retrieve the (const) parameters of the coefficient, e.g. so that they can be queried + /*! + \return the (const) parameters of the coefficient [ x, y, xCP, yCP, deltaXCP, deltaYCP ] + */ + std::vector getParameters() const override; + //! Print the current values of the parameters void printParValues() const override; //! Print the column headings for a results table /*! \param [out] stream the stream to print to */ void printTableHeading(std::ostream& stream) const override; //! Print the parameters of the complex coefficient as a row in the results table /*! \param [out] stream the stream to print to */ void printTableRow(std::ostream& stream) const override; //! Randomise the starting values of the parameters for a fit void randomiseInitValues() override; //! Make sure values are in "standard" ranges, e.g. phases should be between -pi and pi void finaliseValues() override; //! Retrieve the complex coefficient for a particle /*! \return the complex coefficient for a particle */ const LauComplex& particleCoeff() override; //! Retrieve the complex coefficient for an antiparticle /*! \return the complex coefficient for an antiparticle */ const LauComplex& antiparticleCoeff() override; //! Set the parameters based on the complex coefficients for particles and antiparticles /*! This method is not supported by this class because there are more than four parameters so there is not a unique solution. \param [in] coeff the complex coefficient for a particle \param [in] coeffBar the complex coefficient for an antiparticle \param [in] init whether or not the initial and generated values should also be adjusted */ void setCoeffValues( const LauComplex& coeff, const LauComplex& coeffBar, const Bool_t init ) override; //! Calculate the CP asymmetry /*! \return the CP asymmetry */ LauParameter acp() override; //! Create a clone of the coefficient set /*! \param [in] newName the clone's name \param [in] cloneOption special option for the cloning operation \param [in] constFactor a constant factor to multiply the clone's parameters by \return a clone of the coefficient set */ std::unique_ptr createClone(const TString& newName, const CloneOption cloneOption = CloneOption::All, const Double_t constFactor = 1.0) { return std::unique_ptr{this->createClone_impl(newName,cloneOption,constFactor)}; } private: //! Copy constructor (with options) /*! This creates cloned parameters, not copies. \param [in] rhs the coefficient to clone \param [in] cloneOption special option for the cloning operation \param [in] constFactor a constant factor to multiply the clone's parameters by */ LauCartesianGammaCPCoeffSet(const LauCartesianGammaCPCoeffSet& rhs, const CloneOption cloneOption = CloneOption::All, const Double_t constFactor = 1.0); //! Copy constructor (deleted) /*! \param [in] rhs the coefficient to clone */ LauCartesianGammaCPCoeffSet(const LauCartesianGammaCPCoeffSet& rhs) = delete; - //! Move constructor (default) - /*! - \param [in] rhs the coefficient to clone - */ - LauCartesianGammaCPCoeffSet(LauCartesianGammaCPCoeffSet&& rhs) = default; - //! Copy assignment operator (deleted) /*! \param [in] rhs the coefficient to clone */ LauCartesianGammaCPCoeffSet& operator=(const LauCartesianGammaCPCoeffSet& rhs) = delete; - //! Move assignment operator (default) - /*! - \param [in] rhs the coefficient to clone - */ - LauCartesianGammaCPCoeffSet& operator=(LauCartesianGammaCPCoeffSet&& rhs) = default; - //! Create a clone of the coefficient set /*! \param [in] newName the clone's name \param [in] cloneOption special option for the cloning operation \param [in] constFactor a constant factor by which to multiply the cloned parameters \return a clone of the coefficient set */ LauCartesianGammaCPCoeffSet* createClone_impl(const TString& newName, const LauAbsCoeffSet::CloneOption cloneOption, const Double_t constFactor) override; // the actual fit parameters // (need to be pointers so they can be cloned) //! The nonCP real part std::unique_ptr x_; //! The nonCP imaginary part std::unique_ptr y_; //! The average CP real part std::unique_ptr xCP_; //! The average CP imaginary part std::unique_ptr yCP_; //! The asymmetric CP real part std::unique_ptr deltaXCP_; //! The asymmetric CP imaginary part std::unique_ptr deltaYCP_; //! The nonCP part of the complex coefficient LauComplex nonCPPart_; //! The CP part of the complex coefficient for the particle LauComplex cpPart_; //! The CP part of the complex coefficient for the antiparticle LauComplex cpAntiPart_; //! The particle complex coefficient LauComplex particleCoeff_; //! The antiparticle complex coefficient LauComplex antiparticleCoeff_; //! The CP asymmetry LauParameter acp_; ClassDefOverride(LauCartesianGammaCPCoeffSet, 0) }; +//! \cond DOXYGEN_IGNORE +namespace nlohmann { + template <> + struct adl_serializer { + static LauCartesianGammaCPCoeffSet from_json(const json& j); + static void to_json(json& j, const LauCartesianGammaCPCoeffSet& t); + }; +} +//! \endcond DOXYGEN_IGNORE + #endif diff --git a/inc/LauCleoCPCoeffSet.hh b/inc/LauCleoCPCoeffSet.hh index 98494e6..9e8d0b0 100644 --- a/inc/LauCleoCPCoeffSet.hh +++ b/inc/LauCleoCPCoeffSet.hh @@ -1,207 +1,229 @@ /* 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 LauCleoCPCoeffSet.hh \brief File containing declaration of LauCleoCPCoeffSet class. */ /*! \class LauCleoCPCoeffSet \brief Class for defining a complex coefficient using the Cleo CP convention. Holds a set of real values that define the complex coefficient of an amplitude component. The amplitude has the form (a +/- b) * exp( i*(delta +/- phi) ) where a is the average magnitude, b is the asymmetric magnitude, delta is the strong phase and phi is the weak phase. [Phys.Rev. D70 (2004) 091101] */ #ifndef LAU_CLEOCP_COEFF_SET #define LAU_CLEOCP_COEFF_SET #include #include #include #include "Rtypes.h" #include "LauAbsCoeffSet.hh" #include "LauComplex.hh" #include "LauParameter.hh" class LauCleoCPCoeffSet : public LauAbsCoeffSet { public: //! Constructor /*! \param [in] compName the name of the coefficient set \param [in] a the magnitude a \param [in] delta the strong phase \param [in] b the magnitude b \param [in] phi the weak phase \param [in] aFixed whether a is fixed \param [in] deltaFixed whether delta is fixed \param [in] bFixed whether b is fixed \param [in] phiFixed whether phi is fixed \param [in] bSecondStage whether b should be floated only in the second stage of the fit \param [in] phiSecondStage whether phi should be floated only in the second stage of the fit */ LauCleoCPCoeffSet(const TString& compName, const Double_t a, const Double_t delta, const Double_t b, const Double_t phi, const Bool_t aFixed, const Bool_t deltaFixed, const Bool_t bFixed, const Bool_t phiFixed, const Bool_t bSecondStage = kFALSE, const Bool_t phiSecondStage = kFALSE); + //! Move constructor (default) + /*! + \param [in] rhs the coefficient to clone + */ + LauCleoCPCoeffSet(LauCleoCPCoeffSet&& rhs) = default; + + //! Move assignment operator (default) + /*! + \param [in] rhs the coefficient to clone + */ + LauCleoCPCoeffSet& operator=(LauCleoCPCoeffSet&& rhs) = default; + + //! Determine the type of the coefficient + /*! + \return the type of the coefficient + */ + LauCoeffType type() const override { return LauCoeffType::CleoCP; } + //! Retrieve the parameters of the coefficient, e.g. so that they can be loaded into a fit /*! - \return the parameters of the coefficient + \return the parameters of the coefficient [ a, delta, b, phi ] */ std::vector getParameters() override; + //! Retrieve the (const) parameters of the coefficient, e.g. so that they can be queried + /*! + \return the (const) parameters of the coefficient [ a, delta, b, phi ] + */ + std::vector getParameters() const override; + //! Print the current values of the parameters void printParValues() const override; //! Print the column headings for a results table /*! \param [out] stream the stream to print to */ void printTableHeading(std::ostream& stream) const override; //! Print the parameters of the complex coefficient as a row in the results table /*! \param [out] stream the stream to print to */ void printTableRow(std::ostream& stream) const override; //! Randomise the starting values of the parameters for a fit void randomiseInitValues() override; //! Make sure values are in "standard" ranges, e.g. phases should be between -pi and pi void finaliseValues() override; //! Retrieve the complex coefficient for a particle /*! return the complex coefficient for a particle */ const LauComplex& particleCoeff() override; //! Retrieve the complex coefficient for an antiparticle /*! \return the complex coefficient for an antiparticle */ const LauComplex& antiparticleCoeff() override; //! Set the parameters based on the complex coefficients for particles and antiparticles /*! \param [in] coeff the complex coefficient for a particle \param [in] coeffBar the complex coefficient for an antiparticle \param [in] init whether or not the initial and generated values should also be adjusted */ void setCoeffValues( const LauComplex& coeff, const LauComplex& coeffBar, const Bool_t init ) override; //! Calculate the CP asymmetry /*! \return the CP asymmetry */ LauParameter acp() override; //! Create a clone of the coefficient set /*! \param [in] newName the clone's name \param [in] cloneOption special option for the cloning operation \param [in] constFactor a constant factor to multiply the clone's parameters by \return a clone of the coefficient set */ std::unique_ptr createClone(const TString& newName, const CloneOption cloneOption = CloneOption::All, const Double_t constFactor = 1.0) { return std::unique_ptr{this->createClone_impl(newName,cloneOption,constFactor)}; } private: //! Copy constructor (with options) /*! This creates cloned parameters, not copies. \param [in] rhs the coefficient to clone \param [in] cloneOption special option for the cloning operation \param [in] constFactor a constant factor to multiply the clone's parameters by */ LauCleoCPCoeffSet(const LauCleoCPCoeffSet& rhs, const CloneOption cloneOption = CloneOption::All, const Double_t constFactor = 1.0); //! Copy constructor (deleted) /*! \param [in] rhs the coefficient to clone */ LauCleoCPCoeffSet(const LauCleoCPCoeffSet& rhs) = delete; - //! Move constructor (default) - /*! - \param [in] rhs the coefficient to clone - */ - LauCleoCPCoeffSet(LauCleoCPCoeffSet&& rhs) = default; - //! Copy assignment operator (deleted) /*! \param [in] rhs the coefficient to clone */ LauCleoCPCoeffSet& operator=(const LauCleoCPCoeffSet& rhs) = delete; - //! Move assignment operator (default) - /*! - \param [in] rhs the coefficient to clone - */ - LauCleoCPCoeffSet& operator=(LauCleoCPCoeffSet&& rhs) = default; - //! Create a clone of the coefficient set /*! \param [in] newName the clone's name \param [in] cloneOption special option for the cloning operation \param [in] constFactor a constant factor by which to multiply the cloned parameters \return a clone of the coefficient set */ LauCleoCPCoeffSet* createClone_impl(const TString& newName, const LauAbsCoeffSet::CloneOption cloneOption, const Double_t constFactor) override; // the actual fit parameters // (need to be pointers so they can be cloned) //! The magnitude a std::unique_ptr a_; //! The magnitude b std::unique_ptr b_; //! The strong phase std::unique_ptr delta_; //! The weak phase std::unique_ptr phi_; //! The particle complex coefficient LauComplex particleCoeff_; //! The antiparticle complex coefficient LauComplex antiparticleCoeff_; //! The CP asymmetry LauParameter acp_; ClassDefOverride(LauCleoCPCoeffSet, 0) }; +//! \cond DOXYGEN_IGNORE +namespace nlohmann { + template <> + struct adl_serializer { + static LauCleoCPCoeffSet from_json(const json& j); + static void to_json(json& j, const LauCleoCPCoeffSet& t); + }; +} +//! \endcond DOXYGEN_IGNORE + #endif diff --git a/inc/LauMagPhaseCPCoeffSet.hh b/inc/LauMagPhaseCPCoeffSet.hh index 968818c..e24ab00 100644 --- a/inc/LauMagPhaseCPCoeffSet.hh +++ b/inc/LauMagPhaseCPCoeffSet.hh @@ -1,203 +1,225 @@ /* Copyright 2011 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 LauMagPhaseCPCoeffSet.hh \brief File containing declaration of LauMagPhaseCPCoeffSet class. */ /*! \class LauMagPhaseCPCoeffSet \brief Class for defining a complex coefficient using seperate magnitudes and phases for particles and antiparticles. Holds a set of real values that define the complex coefficient of an amplitude component. The amplitudes have the form: c = mag * exp(i*phase) cBar = magBar * exp(i*phaseBar) where mag and magBar are the magnitudes for particle and antiparticle and phase and phaseBar are the phases for particle and antiparticle. */ #ifndef LAU_MAGPHASECP_COEFF_SET #define LAU_MAGPHASECP_COEFF_SET #include #include #include #include "Rtypes.h" #include "LauAbsCoeffSet.hh" #include "LauComplex.hh" #include "LauParameter.hh" class LauMagPhaseCPCoeffSet : public LauAbsCoeffSet { public: //! Constructor /*! \param [in] compName the name of the coefficient set \param [in] mag the magnitude for particles \param [in] phase the phase for particles \param [in] magBar the magnitude for antiparticles \param [in] phaseBar the phase for antiparticles \param [in] magFixed whether mag is fixed \param [in] phaseFixed whether phase is fixed \param [in] magBarFixed whether magBar is fixed \param [in] phaseBarFixed whether phaseBar is fixed */ LauMagPhaseCPCoeffSet(const TString& compName, const Double_t mag, const Double_t phase, const Double_t magBar, const Double_t phaseBar, const Bool_t magFixed, const Bool_t phaseFixed, const Bool_t magBarFixed, const Bool_t phaseBarFixed); + //! Move constructor (default) + /*! + \param [in] rhs the coefficient to clone + */ + LauMagPhaseCPCoeffSet(LauMagPhaseCPCoeffSet&& rhs) = default; + + //! Move assignment operator (default) + /*! + \param [in] rhs the coefficient to clone + */ + LauMagPhaseCPCoeffSet& operator=(LauMagPhaseCPCoeffSet&& rhs) = default; + + //! Determine the type of the coefficient + /*! + \return the type of the coefficient + */ + LauCoeffType type() const override { return LauCoeffType::MagPhaseCP; } + //! Retrieve the parameters of the coefficient, e.g. so that they can be loaded into a fit /*! - \return the parameters of the coefficient + \return the parameters of the coefficient [ mag, phase, magBar, phaseBar ] */ std::vector getParameters() override; + //! Retrieve the (const) parameters of the coefficient, e.g. so that they can be queried + /*! + \return the (const) parameters of the coefficient [ mag, phase, magBar, phaseBar ] + */ + std::vector getParameters() const override; + //! Print the current values of the parameters void printParValues() const override; //! Print the column headings for a results table /*! \param [out] stream the stream to print to */ void printTableHeading(std::ostream& stream) const override; //! Print the parameters of the complex coefficient as a row in the results table /*! \param [out] stream the stream to print to */ void printTableRow(std::ostream& stream) const override; //! Randomise the starting values of the parameters for a fit void randomiseInitValues() override; //! Make sure values are in "standard" ranges, e.g. phases should be between -pi and pi void finaliseValues() override; //! Retrieve the complex coefficient for a particle /*! \return the complex coefficient for a particle */ const LauComplex& particleCoeff() override; //! Retrieve the complex coefficient for an antiparticle /*! \return the complex coefficient for an antiparticle */ const LauComplex& antiparticleCoeff() override; //! Set the parameters based on the complex coefficients for particles and antiparticles /*! \param [in] coeff the complex coefficient for a particle \param [in] coeffBar the complex coefficient for an antiparticle \param [in] init whether or not the initial and generated values should also be adjusted */ void setCoeffValues( const LauComplex& coeff, const LauComplex& coeffBar, Bool_t init ) override; //! Calculate the CP asymmetry /*! \return the CP asymmetry */ LauParameter acp() override; //! Create a clone of the coefficient set /*! \param [in] newName the clone's name \param [in] cloneOption special option for the cloning operation \param [in] constFactor a constant factor to multiply the clone's parameters by \return a clone of the coefficient set */ std::unique_ptr createClone(const TString& newName, const CloneOption cloneOption = CloneOption::All, const Double_t constFactor = 1.0) { return std::unique_ptr{this->createClone_impl(newName,cloneOption,constFactor)}; } private: //! Copy constructor (with options) /*! This creates cloned parameters, not copies. \param [in] rhs the coefficient to clone \param [in] cloneOption special option for the cloning operation \param [in] constFactor a constant factor to multiply the clone's parameters by */ LauMagPhaseCPCoeffSet(const LauMagPhaseCPCoeffSet& rhs, CloneOption cloneOption = CloneOption::All, Double_t constFactor = 1.0); //! Copy constructor (deleted) /*! \param [in] rhs the coefficient to clone */ LauMagPhaseCPCoeffSet(const LauMagPhaseCPCoeffSet& rhs) = delete; - //! Move constructor (default) - /*! - \param [in] rhs the coefficient to clone - */ - LauMagPhaseCPCoeffSet(LauMagPhaseCPCoeffSet&& rhs) = default; - //! Copy assignment operator (deleted) /*! \param [in] rhs the coefficient to clone */ LauMagPhaseCPCoeffSet& operator=(const LauMagPhaseCPCoeffSet& rhs) = delete; - //! Move assignment operator (default) - /*! - \param [in] rhs the coefficient to clone - */ - LauMagPhaseCPCoeffSet& operator=(LauMagPhaseCPCoeffSet&& rhs) = default; - //! Create a clone of the coefficient set /*! \param [in] newName the clone's name \param [in] cloneOption special option for the cloning operation \param [in] constFactor a constant factor by which to multiply the cloned parameters \return a clone of the coefficient set */ LauMagPhaseCPCoeffSet* createClone_impl(const TString& newName, const LauAbsCoeffSet::CloneOption cloneOption, const Double_t constFactor) override; // the actual fit parameters // (need to be pointers so they can be cloned) //! The magnitude for particles std::unique_ptr mag_; //! The phase for particles std::unique_ptr phase_; //! The magnitude for antiparticles std::unique_ptr magBar_; //! The phase for antiparticles std::unique_ptr phaseBar_; //! The particle complex coefficient LauComplex particleCoeff_; //! The antiparticle complex coefficient LauComplex antiparticleCoeff_; //! The CP asymmetry LauParameter acp_; ClassDefOverride(LauMagPhaseCPCoeffSet, 0) }; +//! \cond DOXYGEN_IGNORE +namespace nlohmann { + template <> + struct adl_serializer { + static LauMagPhaseCPCoeffSet from_json(const json& j); + static void to_json(json& j, const LauMagPhaseCPCoeffSet& t); + }; +} +//! \endcond DOXYGEN_IGNORE + #endif diff --git a/inc/LauMagPhaseCoeffSet.hh b/inc/LauMagPhaseCoeffSet.hh index 0ebf13c..9fb3ed5 100644 --- a/inc/LauMagPhaseCoeffSet.hh +++ b/inc/LauMagPhaseCoeffSet.hh @@ -1,186 +1,208 @@ /* 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 LauMagPhaseCoeffSet.hh \brief File containing declaration of LauMagPhaseCoeffSet class. */ /*! \class LauMagPhaseCoeffSet \brief Class for defining a complex coefficient using a magnitude and a phase. Holds a set of real values that define the complex coefficient of an amplitude component. The amplitude has the form mag*exp(i*phase). */ #ifndef LAU_MAGPHASE_COEFF_SET #define LAU_MAGPHASE_COEFF_SET #include #include #include #include "Rtypes.h" #include "LauAbsCoeffSet.hh" #include "LauComplex.hh" #include "LauParameter.hh" class LauMagPhaseCoeffSet : public LauAbsCoeffSet { public: //! Constructor /*! \param [in] compName the name of the coefficient set \param [in] magnitude the magnitude \param [in] phase the phase \param [in] magFixed whether mag is fixed \param [in] phaseFixed whether phase is fixed */ LauMagPhaseCoeffSet(const TString& compName, const Double_t magnitude, const Double_t phase, const Bool_t magFixed, const Bool_t phaseFixed); + //! Move constructor (default) + /*! + \param [in] rhs the coefficient to clone + */ + LauMagPhaseCoeffSet(LauMagPhaseCoeffSet&& rhs) = default; + + //! Move assignment operator (default) + /*! + \param [in] rhs the coefficient to clone + */ + LauMagPhaseCoeffSet& operator=(LauMagPhaseCoeffSet&& rhs) = default; + + //! Determine the type of the coefficient + /*! + \return the type of the coefficient + */ + LauCoeffType type() const override { return LauCoeffType::MagPhase; } + //! Retrieve the parameters of the coefficient, e.g. so that they can be loaded into a fit /*! - \return the parameters of the coefficient + \return the parameters of the coefficient [ mag, phase ] */ std::vector getParameters() override; + //! Retrieve the (const) parameters of the coefficient, e.g. so that they can be queried + /*! + \return the (const) parameters of the coefficient [ mag, phase ] + */ + std::vector getParameters() const override; + //! Print the current values of the parameters void printParValues() const override; //! Print the column headings for a results table /*! \param [out] stream the stream to print to */ void printTableHeading(std::ostream& stream) const override; //! Print the parameters of the complex coefficient as a row in the results table /*! \param [out] stream the stream to print to */ void printTableRow(std::ostream& stream) const override; //! Randomise the starting values of the parameters for a fit void randomiseInitValues() override; //! Make sure values are in "standard" ranges, e.g. phases should be between -pi and pi void finaliseValues() override; //! Retrieve the complex coefficient for a particle /*! \return the complex coefficient for a particle */ const LauComplex& particleCoeff() override; //! Retrieve the complex coefficient for an antiparticle /*! \return the complex coefficient for an antiparticle */ const LauComplex& antiparticleCoeff() override; //! Set the parameters based on the complex coefficients for particles and antiparticles /*! This class does not support CP violation so this method takes the average of the two inputs. \param [in] coeff the complex coefficient for a particle \param [in] coeffBar the complex coefficient for an antiparticle \param [in] init whether or not the initial and generated values should also be adjusted */ void setCoeffValues( const LauComplex& coeff, const LauComplex& coeffBar, const Bool_t init ) override; //! Calculate the CP asymmetry /*! \return the CP asymmetry (zero by design) */ LauParameter acp() override; //! Create a clone of the coefficient set /*! \param [in] newName the clone's name \param [in] cloneOption special option for the cloning operation \param [in] constFactor a constant factor to multiply the clone's parameters by \return a clone of the coefficient set */ std::unique_ptr createClone(const TString& newName, const CloneOption cloneOption = CloneOption::All, const Double_t constFactor = 1.0) { return std::unique_ptr{this->createClone_impl(newName,cloneOption,constFactor)}; } private: //! Copy constructor (with options) /*! This creates cloned parameters, not copies. \param [in] rhs the coefficient to clone \param [in] cloneOption special option for the cloning operation \param [in] constFactor a constant factor to multiply the clone's parameters by */ LauMagPhaseCoeffSet(const LauMagPhaseCoeffSet& rhs, const CloneOption cloneOption = CloneOption::All, const Double_t constFactor = 1.0); //! Copy constructor (deleted) /*! \param [in] rhs the coefficient to clone */ LauMagPhaseCoeffSet(const LauMagPhaseCoeffSet& rhs) = delete; - //! Move constructor (default) - /*! - \param [in] rhs the coefficient to clone - */ - LauMagPhaseCoeffSet(LauMagPhaseCoeffSet&& rhs) = default; - //! Copy assignment operator (deleted) /*! \param [in] rhs the coefficient to clone */ LauMagPhaseCoeffSet& operator=(const LauMagPhaseCoeffSet& rhs) = delete; - //! Move assignment operator (default) - /*! - \param [in] rhs the coefficient to clone - */ - LauMagPhaseCoeffSet& operator=(LauMagPhaseCoeffSet&& rhs) = default; - //! Create a clone of the coefficient set /*! \param [in] newName the clone's name \param [in] cloneOption special option for the cloning operation \param [in] constFactor a constant factor by which to multiply the cloned parameters \return a clone of the coefficient set */ LauMagPhaseCoeffSet* createClone_impl(const TString& newName, const CloneOption cloneOption, const Double_t constFactor) override; // the actual fit parameters // (need to be pointers so they can be cloned) //! The magnitude std::unique_ptr magnitude_; //! The phase std::unique_ptr phase_; //! The complex coefficient LauComplex coeff_; ClassDefOverride(LauMagPhaseCoeffSet, 0) }; +//! \cond DOXYGEN_IGNORE +namespace nlohmann { + template <> + struct adl_serializer { + static LauMagPhaseCoeffSet from_json(const json& j); + static void to_json(json& j, const LauMagPhaseCoeffSet& t); + }; +} +//! \endcond DOXYGEN_IGNORE + #endif diff --git a/inc/LauNSCCartesianCPCoeffSet.hh b/inc/LauNSCCartesianCPCoeffSet.hh index f884166..0330cc1 100644 --- a/inc/LauNSCCartesianCPCoeffSet.hh +++ b/inc/LauNSCCartesianCPCoeffSet.hh @@ -1,238 +1,268 @@ /* Copyright 2015 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 LauNSCCartesianCPCoeffSet.hh \brief File containing declaration of LauNSCCartesianCPCoeffSet class. */ /*! \class LauNSCCartesianCPCoeffSet \brief Class for defining complex coefficients using the Cartesian CP convention for two linked Dalitz plots. Holds a set of real values that define the complex coefficients for an amplitude component in two DPs. The amplitudes have the form: A_f = ( x + Delta_x ) + i ( y + Delta_y ) Abar_f = ( x' - Delta_x' ) + i ( y' - Delta_y' ) A_fbar = ( x' + Delta_x' ) + i ( y' + Delta_y' ) Abar_fbar = ( x - Delta_x ) + i ( y - Delta_y ) */ #ifndef LAU_BSCARTESIANCP_COEFF_SET #define LAU_BSCARTESIANCP_COEFF_SET #include #include #include #include "Rtypes.h" #include "LauAbsCoeffSet.hh" #include "LauComplex.hh" #include "LauParameter.hh" class LauNSCCartesianCPCoeffSet : public LauAbsCoeffSet { public: //! Constructor /*! \param [in] compName the name of the coefficient set \param [in] finalStateIsF kTRUE if the final state being considered is f, kFALSE if the final state being considered is fbar \param [in] x the CP-conserving parameter for the real part of A_f and Abar_fbar \param [in] y the CP-conserving parameter for the imaginary part of A_f and Abar_fbar \param [in] deltaX the CP-violating parameter for the real part of A_f and Abar_fbar \param [in] deltaY the CP-violating parameter for the imaginary part of A_f and Abar_fbar \param [in] xFixed whether x is fixed \param [in] yFixed whether y is fixed \param [in] deltaXFixed whether deltaX is fixed \param [in] deltaYFixed whether deltaY is fixed \param [in] deltaXSecondStage whether deltaX should be floated only in the second stage of the fit \param [in] deltaYSecondStage whether deltaY should be floated only in the second stage of the fit \param [in] xPrime the CP-conserving parameter for the real part of A_fbar and Abar_f \param [in] yPrime the CP-conserving parameter for the imaginary part of A_fbar and Abar_f \param [in] deltaXPrime the CP-violating parameter for the real part of A_fbar and Abar_f \param [in] deltaYPrime the CP-violating parameter for the imaginary part of A_fbar and Abar_f \param [in] xPrimeFixed whether xPrime is fixed \param [in] yPrimeFixed whether yPrime is fixed \param [in] deltaXPrimeFixed whether deltaXPrime is fixed \param [in] deltaYPrimeFixed whether deltaYPrime is fixed \param [in] deltaXPrimeSecondStage whether deltaXPrime should be floated only in the second stage of the fit \param [in] deltaYPrimeSecondStage whether deltaYPrime should be floated only in the second stage of the fit */ LauNSCCartesianCPCoeffSet(const TString& compName, const Bool_t finalStateIsF, const Double_t x, const Double_t y, const Double_t deltaX, const Double_t deltaY, const Bool_t xFixed, const Bool_t yFixed, const Bool_t deltaXFixed, const Bool_t deltaYFixed, const Bool_t deltaXSecondStage, const Bool_t deltaYSecondStage, const Double_t xPrime, const Double_t yPrime, const Double_t deltaXPrime, const Double_t deltaYPrime, const Bool_t xPrimeFixed, const Bool_t yPrimeFixed, const Bool_t deltaXPrimeFixed, const Bool_t deltaYPrimeFixed, const Bool_t deltaXPrimeSecondStage, const Bool_t deltaYPrimeSecondStage); + //! Move constructor (default) + /*! + \param [in] rhs the coefficient to clone + */ + LauNSCCartesianCPCoeffSet(LauNSCCartesianCPCoeffSet&& rhs) = default; + + //! Move assignment operator (deleted) + /*! + The const field finalStateIsF implicitly deletes this anyway + + \param [in] rhs the coefficient to clone + */ + LauNSCCartesianCPCoeffSet& operator=(LauNSCCartesianCPCoeffSet&& rhs) = delete; + + //! Determine the type of the coefficient + /*! + \return the type of the coefficient + */ + LauCoeffType type() const override { return LauCoeffType::NSCCartesianCP; } + //! Retrieve the parameters of the coefficient, e.g. so that they can be loaded into a fit /*! - \return the parameters of the coefficient + \return the parameters of the coefficient [ x, y, deltaX, deltaY, x', y', deltaX', deltaY' ] */ std::vector getParameters() override; + //! Retrieve the (const) parameters of the coefficient, e.g. so that they can be queried + /*! + \return the (const) parameters of the coefficient [ x, y, deltaX, deltaY, x', y', deltaX', deltaY' ] + */ + std::vector getParameters() const override; + + //! Determine whether this is the f or fbar final state + /*! + \return kTRUE if the final state is f, kFALSE if fbar + */ + Bool_t finalStateIsF() const { return finalStateIsF_; } + //! Print the current values of the parameters void printParValues() const override; //! Print the column headings for a results table /*! \param [out] stream the stream to print to */ void printTableHeading(std::ostream& stream) const override; //! Print the parameters of the complex coefficient as a row in the results table /*! \param [out] stream the stream to print to */ void printTableRow(std::ostream& stream) const override; //! Randomise the starting values of the parameters for a fit void randomiseInitValues() override; //! Make sure values are in "standard" ranges, e.g. phases should be between -pi and pi void finaliseValues() override; //! Retrieve the complex coefficient for a particle /*! \return the complex coefficient for a particle */ const LauComplex& particleCoeff() override; //! Retrieve the complex coefficient for an antiparticle /*! \return the complex coefficient for an antiparticle */ const LauComplex& antiparticleCoeff() override; //! Set the parameters based on the complex coefficients for particles and antiparticles /*! This method is not supported by this class because there are more than four parameters so there is not a unique solution. \param [in] coeff the complex coefficient for a particle \param [in] coeffBar the complex coefficient for an antiparticle \param [in] init whether or not the initial and generated values should also be adjusted */ void setCoeffValues( const LauComplex& coeff, const LauComplex& coeffBar, const Bool_t init ) override; //! Calculate the CP asymmetry /*! \return the CP asymmetry */ LauParameter acp() override; //! Create a clone of the coefficient set /*! \param [in] newName the clone's name \param [in] cloneOption special option for the cloning operation \param [in] constFactor a constant factor to multiply the clone's parameters by \return a clone of the coefficient set */ std::unique_ptr createClone(const TString& newName, const CloneOption cloneOption = CloneOption::All, const Double_t constFactor = 1.0) { return std::unique_ptr{this->createClone_impl(newName,cloneOption,constFactor)}; } private: //! Copy constructor (with options) /*! This creates cloned parameters, not copies. \param [in] rhs the coefficient to clone \param [in] cloneOption special option for the cloning operation \param [in] constFactor a constant factor to multiply the clone's parameters by */ LauNSCCartesianCPCoeffSet(const LauNSCCartesianCPCoeffSet& rhs, const CloneOption cloneOption = CloneOption::All, const Double_t constFactor = 1.0); //! Copy constructor (deleted) /*! \param [in] rhs the coefficient to clone */ LauNSCCartesianCPCoeffSet(const LauNSCCartesianCPCoeffSet& rhs) = delete; - //! Move constructor (deleted) - /*! - \param [in] rhs the coefficient to clone - */ - LauNSCCartesianCPCoeffSet(LauNSCCartesianCPCoeffSet&& rhs) = delete; - //! Copy assignment operator (deleted) /*! \param [in] rhs the coefficient to clone */ LauNSCCartesianCPCoeffSet& operator=(const LauNSCCartesianCPCoeffSet& rhs) = delete; - //! Move assignment operator (deleted) - /*! - \param [in] rhs the coefficient to clone - */ - LauNSCCartesianCPCoeffSet& operator=(LauNSCCartesianCPCoeffSet&& rhs) = delete; - //! Create a clone of the coefficient set /*! \param [in] newName the clone's name \param [in] cloneOption special option for the cloning operation \param [in] constFactor a constant factor by which to multiply the cloned parameters \return a clone of the coefficient set */ LauNSCCartesianCPCoeffSet* createClone_impl(const TString& newName, const LauAbsCoeffSet::CloneOption cloneOption, const Double_t constFactor) override; //! Boolean controlling which final state information should be returned const Bool_t finalStateIsF_; // the actual fit parameters (need to be pointers so they can be cloned) //! The CP-conserving parameter for the real part of A_f and Abar_fbar std::unique_ptr x_; //! The CP-conserving parameter for the imaginary part of A_f and Abar_fbar std::unique_ptr y_; //! The CP-violating parameter for the real part of A_f and Abar_fbar std::unique_ptr deltaX_; //! The CP-violating parameter for the imaginary part of A_f and Abar_fbar std::unique_ptr deltaY_; //! The CP-conserving parameter for the real part of A_fbar and Abar_f std::unique_ptr xPrime_; //! The CP-conserving parameter for the imaginary part of A_fbar and Abar_f std::unique_ptr yPrime_; //! The CP-violating parameter for the real part of A_fbar and Abar_f std::unique_ptr deltaXPrime_; //! The CP-violating parameter for the imaginary part of A_fbar and Abar_f std::unique_ptr deltaYPrime_; //! The complex coefficient for A_f LauComplex coeffAf_; //! The complex coefficient for A_fbar LauComplex coeffAfbar_; //! The complex coefficient for Abar_f LauComplex coeffAbarf_; //! The complex coefficient for Abar_fbar LauComplex coeffAbarfbar_; //! The CP asymmetry LauParameter acp_; ClassDefOverride(LauNSCCartesianCPCoeffSet, 0) }; +//! \cond DOXYGEN_IGNORE +namespace nlohmann { + template <> + struct adl_serializer { + static LauNSCCartesianCPCoeffSet from_json(const json& j); + static void to_json(json& j, const LauNSCCartesianCPCoeffSet& t); + }; +} +//! \endcond DOXYGEN_IGNORE + #endif diff --git a/inc/LauPolarGammaCPCoeffSet.hh b/inc/LauPolarGammaCPCoeffSet.hh index 9699eff..dd6adc8 100644 --- a/inc/LauPolarGammaCPCoeffSet.hh +++ b/inc/LauPolarGammaCPCoeffSet.hh @@ -1,288 +1,340 @@ /* Copyright 2014 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 LauPolarGammaCPCoeffSet.hh \brief File containing declaration of LauPolarGammaCPCoeffSet class. */ /*! \class LauPolarGammaCPCoeffSet \brief Class for defining a complex coefficient useful for extracting the CKM angle gamma from B -> D h h Dalitz plots. Holds a set of real values that define the complex coefficient of an amplitude component. Depending on the type of the D decay, the amplitude has one of the following forms: CP-odd eigenstate: ( x + i * y ) * ( 1 - rB * exp( i * ( deltaB +/- gamma ) ) ) CP-even eigenstate: ( x + i * y ) * ( 1 + rB * exp( i * ( deltaB +/- gamma ) ) ) ADS favoured state: ( x + i * y ) * ( 1 + rB * rD * exp( i * ( deltaB - deltaD +/- gamma ) ) ) ADS suppressed state: ( x + i * y ) * ( rD * exp( - i * deltaD ) + rB * exp( i * ( deltaB +/- gamma ) ) ) [Phys. Rev. D79, 051301 (2009)] */ #ifndef LAU_POLARGAMMACP_COEFF_SET #define LAU_POLARGAMMACP_COEFF_SET #include #include #include #include "Rtypes.h" #include "LauAbsCoeffSet.hh" #include "LauComplex.hh" #include "LauParameter.hh" class LauPolarGammaCPCoeffSet : public LauAbsCoeffSet { public: //! The possible D decay modes enum class DecayType { GLW_CPOdd, /*!< GLW CP-odd, e.g. D0 -> K0 pi0 */ GLW_CPEven, /*!< GLW CP-even, e.g. D0 -> K+ K- */ ADS_Favoured, /*!< ADS Favoured, e.g. D0 -> K- pi+ */ ADS_Suppressed, /*!< ADS Suppressed, e.g. D0 -> K+ pi- */ GLW_CPOdd_btouOnly, /*!< GLW CP-odd, e.g. D0 -> K0 pi0, where B decay only proceeds via b -> u transition */ GLW_CPEven_btouOnly, /*!< GLW CP-even, e.g. D0 -> K+ K-, where B decay only proceeds via b -> u transition */ ADS_Favoured_btouOnly, /*!< ADS Favoured, e.g. D0 -> K- pi+, where B decay only proceeds via b -> u transition */ ADS_Suppressed_btouOnly, /*!< ADS Suppressed, e.g. D0 -> K+ pi-, where B decay only proceeds via b -> u transition */ }; //! Constructor /*! \param [in] compName the name of the coefficient set \param [in] decayType the type of the D decay \param [in] x the real part of the b -> c amplitude \param [in] y the imaginary part of the b -> c amplitude \param [in] rB the magnitude of the ratio of the b -> u and b -> c amplitudes \param [in] deltaB the relative CP-conserving (strong) phase of the b -> u and b -> c amplitudes \param [in] gamma the relative CP-violating (weak) phase of the b -> u and b -> c amplitudes \param [in] rD the magnitude of the ratio of the favoured and suppressed D-decay amplitudes \param [in] deltaD the relative strong phase of the favoured and suppressed D-decay amplitudes \param [in] xFixed whether x is fixed \param [in] yFixed whether y is fixed \param [in] rBFixed whether rB is fixed \param [in] deltaBFixed whether deltaB is fixed \param [in] gammaFixed whether gamma is fixed \param [in] rDFixed whether rD is fixed \param [in] deltaDFixed whether deltaD is fixed \param [in] rBSecondStage whether rB should be floated only in the second stage of the fit \param [in] deltaBSecondStage whether deltaB should be floated only in the second stage of the fit \param [in] gammaSecondStage whether gamma should be floated only in the second stage of the fit \param [in] rDSecondStage whether rD should be floated only in the second stage of the fit \param [in] deltaDSecondStage whether deltaD should be floated only in the second stage of the fit \param [in] useGlobalGamma whether gamma should be shared with other resonances \param [in] useGlobalADSPars whether rD and deltaD should be shared with other resonances */ LauPolarGammaCPCoeffSet(const TString& compName, const DecayType decayType, const Double_t x, const Double_t y, const Double_t rB, const Double_t deltaB, const Double_t gamma, const Double_t rD, const Double_t deltaD, const Bool_t xFixed, const Bool_t yFixed, const Bool_t rBFixed, const Bool_t deltaBFixed, const Bool_t gammaFixed, const Bool_t rDFixed, const Bool_t deltaDFixed, const Bool_t rBSecondStage = kFALSE, const Bool_t deltaBSecondStage = kFALSE, const Bool_t gammaSecondStage = kFALSE, const Bool_t rDSecondStage = kFALSE, const Bool_t deltaDSecondStage = kFALSE, const Bool_t useGlobalGamma = kFALSE, const Bool_t useGlobalADSPars = kFALSE); + //! Move constructor (default) + /*! + \param [in] rhs the coefficient to clone + */ + LauPolarGammaCPCoeffSet(LauPolarGammaCPCoeffSet&& rhs) = default; + + //! Move assignment operator (deleted) + /*! + \param [in] rhs the coefficient to clone + */ + LauPolarGammaCPCoeffSet& operator=(LauPolarGammaCPCoeffSet&& rhs) = delete; + + //! Determine the type of the coefficient + /*! + \return the type of the coefficient + */ + LauCoeffType type() const override { return LauCoeffType::PolarGammaCP; } + //! Retrieve the parameters of the coefficient, e.g. so that they can be loaded into a fit /*! - \return the parameters of the coefficient + \return the parameters of the coefficient [ x, y, gamma, [rB, deltaB, rD, deltaD] ] */ std::vector getParameters() override; + //! Retrieve the (const) parameters of the coefficient, e.g. so that they can be queried + /*! + \return the (const) parameters of the coefficient [ x, y, gamma, [rB, deltaB, rD, deltaD] ] + */ + std::vector getParameters() const override; + + //! Determine the decay type of the coefficient + /*! + \return the decay type of the coefficient + */ + DecayType decayType() const { return decayType_; } + + //! Determine whether the global value of gamma is used for this coefficient + /*! + \return kTRUE if the global value of gamma is used, false otherwise + */ + Bool_t useGlobalGamma() const { return useGlobalGamma_; } + + //! Determine whether the global values of the ADS parameter are used for this coefficient + /*! + \return kTRUE if the global values are used, false otherwise + */ + Bool_t useGlobalADSPars() const { return useGlobalADSPars_; } + //! Print the current values of the parameters void printParValues() const override; //! Print the column headings for a results table /*! \param [out] stream the stream to print to */ void printTableHeading(std::ostream& stream) const override; //! Print the parameters of the complex coefficient as a row in the results table /*! \param [out] stream the stream to print to */ void printTableRow(std::ostream& stream) const override; //! Randomise the starting values of the parameters for a fit void randomiseInitValues() override; //! Make sure values are in "standard" ranges, e.g. phases should be between -pi and pi void finaliseValues() override; //! Retrieve the complex coefficient for a particle /*! \return the complex coefficient for a particle */ const LauComplex& particleCoeff() override; //! Retrieve the complex coefficient for an antiparticle /*! \return the complex coefficient for an antiparticle */ const LauComplex& antiparticleCoeff() override; //! Set the parameters based on the complex coefficients for particles and antiparticles /*! This method is not supported by this class because there are more than four parameters, hence there is not a unique solution. \param [in] coeff the complex coefficient for a particle \param [in] coeffBar the complex coefficient for an antiparticle \param [in] init whether or not the initial and generated values should also be adjusted */ void setCoeffValues( const LauComplex& coeff, const LauComplex& coeffBar, const Bool_t init ) override; //! Calculate the CP asymmetry /*! \return the CP asymmetry */ LauParameter acp() override; //! Create a clone of the coefficient set /*! \param [in] newName the clone's name \param [in] cloneOption special option for the cloning operation \param [in] constFactor a constant factor to multiply the clone's parameters by \return a clone of the coefficient set */ std::unique_ptr createClone(const TString& newName, const CloneOption cloneOption = CloneOption::All, const Double_t constFactor = 1.0) { return std::unique_ptr{this->createClone_impl(newName,cloneOption,constFactor)}; } private: //! Copy constructor /*! This creates cloned parameters, not copies. \param [in] rhs the coefficient to clone \param [in] cloneOption special option for the cloning operation \param [in] constFactor a constant factor to multiply the clone's parameters by */ LauPolarGammaCPCoeffSet(const LauPolarGammaCPCoeffSet& rhs, const CloneOption cloneOption = CloneOption::All, const Double_t constFactor = 1.0); //! Copy constructor (deleted) /*! \param [in] rhs the coefficient to clone */ LauPolarGammaCPCoeffSet(const LauPolarGammaCPCoeffSet& rhs) = delete; - //! Move constructor (default) - /*! - \param [in] rhs the coefficient to clone - */ - LauPolarGammaCPCoeffSet(LauPolarGammaCPCoeffSet&& rhs) = default; - //! Copy assignment operator (deleted) /*! \param [in] rhs the coefficient to clone */ LauPolarGammaCPCoeffSet& operator=(const LauPolarGammaCPCoeffSet& rhs) = delete; - //! Move assignment operator (deleted) - /*! - \param [in] rhs the coefficient to clone - */ - LauPolarGammaCPCoeffSet& operator=(LauPolarGammaCPCoeffSet&& rhs) = delete; - //! Create a clone of the coefficient set /*! \param [in] newName the clone's name \param [in] cloneOption special option for the cloning operation \param [in] constFactor a constant factor by which to multiply the cloned parameters \return a clone of the coefficient set */ LauPolarGammaCPCoeffSet* createClone_impl(const TString& newName, const LauAbsCoeffSet::CloneOption cloneOption, const Double_t constFactor) override; //! Prepend the base name and index to the name of a parameter /*! \param [in,out] par the parameter to be renamed \param [in] oldBaseName the old base name, which might need to be removed before adding the new one */ void adjustName(LauParameter& par, const TString& oldBaseName) override; //! Update the amplitudes based on the new values of the parameters void updateAmplitudes(); //! The type of the D decay const DecayType decayType_; // the actual fit parameters // (need to be pointers so they can be cloned) //! The real part of the b -> c amplitude std::unique_ptr x_; //! The imaginary part of the b -> c amplitude std::unique_ptr y_; //! the magnitude of the ratio of the b -> u and b -> c amplitudes std::unique_ptr rB_; //! the relative CP-conserving (strong) phase of the b -> u and b -> c amplitudes std::unique_ptr deltaB_; //! the relative CP-violating (weak) phase of the b -> u and b -> c amplitudes std::shared_ptr gamma_; //! the magnitude of the ratio of the favoured and suppressed D-decay amplitudes std::shared_ptr rD_; //! the relative strong phase of the favoured and suppressed D-decay amplitudes std::shared_ptr deltaD_; //! The CP-violating phase (shared by multiple resonances) static std::shared_ptr gammaGlobal_; //! the magnitude of the ratio of the favoured and suppressed D-decay amplitudes (shared by multiple resonances) static std::shared_ptr rDGlobal_; //! the relative strong phase of the favoured and suppressed D-decay amplitudes (shared by multiple resonances) static std::shared_ptr deltaDGlobal_; //! Whether the global gamma is used for this resonance const Bool_t useGlobalGamma_; //! Whether the global rD and deltaD are used for this resonance const Bool_t useGlobalADSPars_; //! The b -> c part of the complex coefficient LauComplex nonCPPart_; //! The b -> u part of the complex coefficient for the particle LauComplex cpPart_; //! The b -> u part of the complex coefficient for the antiparticle LauComplex cpAntiPart_; //! The particle complex coefficient LauComplex particleCoeff_; //! The antiparticle complex coefficient LauComplex antiparticleCoeff_; //! The CP asymmetry LauParameter acp_; ClassDefOverride(LauPolarGammaCPCoeffSet, 0) }; +//! \cond DOXYGEN_IGNORE +// map LauPolarGammaCPCoeffSet::DecayType values to JSON as strings +NLOHMANN_JSON_SERIALIZE_ENUM( LauPolarGammaCPCoeffSet::DecayType, { + {LauPolarGammaCPCoeffSet::DecayType::GLW_CPOdd, "GLW_CPOdd"}, + {LauPolarGammaCPCoeffSet::DecayType::GLW_CPEven, "GLW_CPEven"}, + {LauPolarGammaCPCoeffSet::DecayType::ADS_Favoured, "ADS_Favoured"}, + {LauPolarGammaCPCoeffSet::DecayType::ADS_Suppressed, "ADS_Suppressed"}, + {LauPolarGammaCPCoeffSet::DecayType::GLW_CPOdd_btouOnly, "GLW_CPOdd_btouOnly"}, + {LauPolarGammaCPCoeffSet::DecayType::GLW_CPEven_btouOnly, "GLW_CPEven_btouOnly"}, + {LauPolarGammaCPCoeffSet::DecayType::ADS_Favoured_btouOnly, "ADS_Favoured_btouOnly"}, + {LauPolarGammaCPCoeffSet::DecayType::ADS_Suppressed_btouOnly, "ADS_Suppressed_btouOnly"}, + }) + +namespace nlohmann { + template <> + struct adl_serializer { + static LauPolarGammaCPCoeffSet from_json(const json& j); + static void to_json(json& j, const LauPolarGammaCPCoeffSet& t); + }; +} +//! \endcond DOXYGEN_IGNORE + #endif diff --git a/inc/LauRealImagCPCoeffSet.hh b/inc/LauRealImagCPCoeffSet.hh index 620ed2a..5498ae6 100644 --- a/inc/LauRealImagCPCoeffSet.hh +++ b/inc/LauRealImagCPCoeffSet.hh @@ -1,202 +1,224 @@ /* Copyright 2014 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 LauRealImagCPCoeffSet.hh \brief File containing declaration of LauRealImagCPCoeffSet class. */ /*! \class LauRealImagCPCoeffSet \brief Class for defining a complex coefficient using a simple Cartesian CP convention. Holds a set of real values that define the complex coefficient of an amplitude component. The amplitudes have the form: c = x + i * y cbar = xbar + i * ybar */ #ifndef LAU_REALIMAGCP_COEFF_SET #define LAU_REALIMAGCP_COEFF_SET #include #include #include #include "Rtypes.h" #include "LauAbsCoeffSet.hh" #include "LauComplex.hh" #include "LauParameter.hh" class LauRealImagCPCoeffSet : public LauAbsCoeffSet { public: //! Constructor /*! \param [in] compName the name of the coefficient set \param [in] x the real part for the particle \param [in] y the imaginary part for the particle \param [in] xbar the real part for the antiparticle \param [in] ybar the imaginary part for the antiparticle \param [in] xFixed whether x is fixed \param [in] yFixed whether y is fixed \param [in] xbarFixed whether xbar is fixed \param [in] ybarFixed whether ybar is fixed */ LauRealImagCPCoeffSet(const TString& compName, const Double_t x, const Double_t y, const Double_t xbar, const Double_t ybar, const Bool_t xFixed, const Bool_t yFixed, const Bool_t xbarFixed, const Bool_t ybarFixed); + //! Move constructor (default) + /*! + \param [in] rhs the coefficient to clone + */ + LauRealImagCPCoeffSet(LauRealImagCPCoeffSet&& rhs) = default; + + //! Move assignment operator (default) + /*! + \param [in] rhs the coefficient to clone + */ + LauRealImagCPCoeffSet& operator=(LauRealImagCPCoeffSet&& rhs) = default; + + //! Determine the type of the coefficient + /*! + \return the type of the coefficient + */ + LauCoeffType type() const override { return LauCoeffType::RealImagCP; } + //! Retrieve the parameters of the coefficient, e.g. so that they can be loaded into a fit /*! - \return the parameters of the coefficient + \return the parameters of the coefficient [ x, y, xbar, ybar ] */ std::vector getParameters() override; + //! Retrieve the (const) parameters of the coefficient, e.g. so that they can be queried + /*! + \return the (const) parameters of the coefficient [ x, y, xbar, ybar ] + */ + std::vector getParameters() const override; + //! Print the current values of the parameters void printParValues() const override; //! Print the column headings for a results table /*! \param [out] stream the stream to print to */ void printTableHeading(std::ostream& stream) const override; //! Print the parameters of the complex coefficient as a row in the results table /*! \param [out] stream the stream to print to */ void printTableRow(std::ostream& stream) const override; //! Randomise the starting values of the parameters for a fit void randomiseInitValues() override; //! Make sure values are in "standard" ranges, e.g. phases should be between -pi and pi void finaliseValues() override; //! Retrieve the complex coefficient for a particle /*! \return the complex coefficient for a particle */ const LauComplex& particleCoeff() override; //! Retrieve the complex coefficient for an antiparticle /*! \return the complex coefficient for an antiparticle */ const LauComplex& antiparticleCoeff() override; //! Set the parameters based on the complex coefficients for particles and antiparticles /*! \param [in] coeff the complex coefficient for a particle \param [in] coeffBar the complex coefficient for an antiparticle \param [in] init whether or not the initial and generated values should also be adjusted */ void setCoeffValues( const LauComplex& coeff, const LauComplex& coeffBar, Bool_t init ) override; //! Calculate the CP asymmetry /*! \return the CP asymmetry */ LauParameter acp() override; //! Create a clone of the coefficient set /*! \param [in] newName the clone's name \param [in] cloneOption special option for the cloning operation \param [in] constFactor a constant factor to multiply the clone's parameters by \return a clone of the coefficient set */ std::unique_ptr createClone(const TString& newName, const CloneOption cloneOption = CloneOption::All, const Double_t constFactor = 1.0) { return std::unique_ptr{this->createClone_impl(newName,cloneOption,constFactor)}; } private: //! Copy constructor (with options) /*! This creates cloned parameters, not copies. \param [in] rhs the coefficient to clone \param [in] cloneOption special option for the cloning operation \param [in] constFactor a constant factor to multiply the clone's parameters by */ LauRealImagCPCoeffSet(const LauRealImagCPCoeffSet& rhs, CloneOption cloneOption = CloneOption::All, Double_t constFactor = 1.0); //! Copy constructor (deleted) /*! \param [in] rhs the coefficient to clone */ LauRealImagCPCoeffSet(const LauRealImagCPCoeffSet& rhs) = delete; - //! Move constructor (default) - /*! - \param [in] rhs the coefficient to clone - */ - LauRealImagCPCoeffSet(LauRealImagCPCoeffSet&& rhs) = default; - //! Copy assignment operator (deleted) /*! \param [in] rhs the coefficient to clone */ LauRealImagCPCoeffSet& operator=(const LauRealImagCPCoeffSet& rhs) = delete; - //! Move assignment operator (default) - /*! - \param [in] rhs the coefficient to clone - */ - LauRealImagCPCoeffSet& operator=(LauRealImagCPCoeffSet&& rhs) = default; - //! Create a clone of the coefficient set /*! \param [in] newName the clone's name \param [in] cloneOption special option for the cloning operation \param [in] constFactor a constant factor by which to multiply the cloned parameters \return a clone of the coefficient set */ LauRealImagCPCoeffSet* createClone_impl(const TString& newName, const LauAbsCoeffSet::CloneOption cloneOption, const Double_t constFactor) override; // the actual fit parameters // (need to be pointers so they can be cloned) //! The real part for the particle std::unique_ptr x_; //! The imaginary part for the particle std::unique_ptr y_; //! The real part for the antiparticle std::unique_ptr xbar_; //! The imaginary part for the antiparticle std::unique_ptr ybar_; //! The particle complex coefficient LauComplex particleCoeff_; //! The antiparticle complex coefficient LauComplex antiparticleCoeff_; //! The CP asymmetry LauParameter acp_; ClassDefOverride(LauRealImagCPCoeffSet, 0) }; +//! \cond DOXYGEN_IGNORE +namespace nlohmann { + template <> + struct adl_serializer { + static LauRealImagCPCoeffSet from_json(const json& j); + static void to_json(json& j, const LauRealImagCPCoeffSet& t); + }; +} +//! \endcond DOXYGEN_IGNORE + #endif diff --git a/inc/LauRealImagCoeffSet.hh b/inc/LauRealImagCoeffSet.hh index 2e554fa..9a5ed59 100644 --- a/inc/LauRealImagCoeffSet.hh +++ b/inc/LauRealImagCoeffSet.hh @@ -1,188 +1,216 @@ /* 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 LauRealImagCoeffSet.hh \brief File containing declaration of LauRealImagCoeffSet class. */ -/*! \class LauRealImagCoeffSet - \brief Class for defining a complex coefficient using real and imaginary parts. - - Holds a set of real values that define the complex coefficient of an amplitude component. - The amplitude has the form x + i*y. -*/ - #ifndef LAU_REALIMAG_COEFF_SET #define LAU_REALIMAG_COEFF_SET +#include "LauAbsCoeffSet.hh" +#include "LauComplex.hh" +#include "LauParameter.hh" + +#include "Rtypes.h" + +#include + #include #include #include -#include -#include "Rtypes.h" - -#include "LauAbsCoeffSet.hh" -#include "LauComplex.hh" -#include "LauParameter.hh" +/*! \class LauRealImagCoeffSet + \brief Class for defining a complex coefficient using real and imaginary parts. + Holds a set of real values that define the complex coefficient of an amplitude component. + The amplitude has the form x + i*y. +*/ class LauRealImagCoeffSet : public LauAbsCoeffSet { public: //! Constructor /*! \param [in] compName the name of the coefficient set \param [in] x the real part \param [in] y the imaginary part \param [in] xFixed whether x is fixed \param [in] yFixed whether y is fixed */ LauRealImagCoeffSet(const TString& compName, const Double_t x, const Double_t y, const Bool_t xFixed, const Bool_t yFixed); + //! Move constructor (default) + /*! + \param [in] rhs the coefficient to clone + */ + LauRealImagCoeffSet(LauRealImagCoeffSet&& rhs) = default; + + //! Move assignment operator (default) + /*! + \param [in] rhs the coefficient to clone + */ + LauRealImagCoeffSet& operator=(LauRealImagCoeffSet&& rhs) = default; + + //! Determine the type of the coefficient + /*! + \return the type of the coefficient + */ + LauCoeffType type() const override { return LauCoeffType::RealImag; } + //! Retrieve the parameters of the coefficient, e.g. so that they can be loaded into a fit /*! - \return the parameters of the coefficient + \return the parameters of the coefficient [ x, y ] + */ + std::vector getParameters() override + { + return { x_.get(), y_.get() }; + } + + //! Retrieve the (const) parameters of the coefficient, e.g. so that they can be queried + /*! + \return the (const) parameters of the coefficient [ x, y ] */ - std::vector getParameters() override; + std::vector getParameters() const override + { + return { x_.get(), y_.get() }; + } //! Print the current values of the parameters void printParValues() const override; //! Print the column headings for a results table /*! \param [out] stream the stream to print to */ void printTableHeading(std::ostream& stream) const override; //! Print the parameters of the complex coefficient as a row in the results table /*! \param [out] stream the stream to print to */ void printTableRow(std::ostream& stream) const override; //! Randomise the starting values of the parameters for a fit void randomiseInitValues() override; //! Make sure values are in "standard" ranges, e.g. phases should be between -pi and pi void finaliseValues() override; //! Retrieve the complex coefficient for a particle /*! \return the complex coefficient for a particle */ const LauComplex& particleCoeff() override; //! Retrieve the complex coefficient for an antiparticle /*! \return the complex coefficient for an antiparticle */ const LauComplex& antiparticleCoeff() override; //! Set the parameters based on the complex coefficients for particles and antiparticles /*! This class does not support CP violation so this method takes the average of the two inputs. \param [in] coeff the complex coefficient for a particle \param [in] coeffBar the complex coefficient for an antiparticle \param [in] init whether or not the initial and generated values should also be adjusted */ void setCoeffValues( const LauComplex& coeff, const LauComplex& coeffBar, Bool_t init ) override; //! Calculate the CP asymmetry /*! \return the CP asymmetry (zero by design) */ LauParameter acp() override; //! Create a clone of the coefficient set /*! \param [in] newName the clone's name \param [in] cloneOption special option for the cloning operation \param [in] constFactor a constant factor to multiply the clone's parameters by \return a clone of the coefficient set */ std::unique_ptr createClone(const TString& newName, const CloneOption cloneOption = CloneOption::All, const Double_t constFactor = 1.0) { return std::unique_ptr{this->createClone_impl(newName,cloneOption,constFactor)}; } private: //! Copy constructor (with options) /*! This creates cloned parameters, not copies. \param [in] rhs the coefficient to clone \param [in] cloneOption special option for the cloning operation \param [in] constFactor a constant factor to multiply the clone's parameters by */ LauRealImagCoeffSet(const LauRealImagCoeffSet& rhs, const CloneOption cloneOption = CloneOption::All, const Double_t constFactor = 1.0); //! Copy constructor (deleted) /*! \param [in] rhs the coefficient to clone */ LauRealImagCoeffSet(const LauRealImagCoeffSet& rhs) = delete; - //! Move constructor (default) - /*! - \param [in] rhs the coefficient to clone - */ - LauRealImagCoeffSet(LauRealImagCoeffSet&& rhs) = default; - //! Copy assignment operator (deleted) /*! \param [in] rhs the coefficient to clone */ LauRealImagCoeffSet& operator=(const LauRealImagCoeffSet& rhs) = delete; - //! Move assignment operator (default) - /*! - \param [in] rhs the coefficient to clone - */ - LauRealImagCoeffSet& operator=(LauRealImagCoeffSet&& rhs) = default; - //! Create a clone of the coefficient set /*! \param [in] newName the clone's name \param [in] cloneOption special option for the cloning operation \param [in] constFactor a constant factor by which to multiply the cloned parameters \return a clone of the coefficient set */ LauRealImagCoeffSet* createClone_impl(const TString& newName, const LauAbsCoeffSet::CloneOption cloneOption, const Double_t constFactor) override; // the actual fit parameters // (need to be pointers so they can be cloned) //! The real part std::unique_ptr x_; //! The imaginary part std::unique_ptr y_; //! The complex coefficient LauComplex coeff_; ClassDefOverride(LauRealImagCoeffSet, 0) }; +//! \cond DOXYGEN_IGNORE +namespace nlohmann { + template <> + struct adl_serializer { + static LauRealImagCoeffSet from_json(const json& j); + static void to_json(json& j, const LauRealImagCoeffSet& t); + }; +} +//! \endcond DOXYGEN_IGNORE + #endif diff --git a/inc/LauRealImagGammaCPCoeffSet.hh b/inc/LauRealImagGammaCPCoeffSet.hh index 4960a51..0783962 100644 --- a/inc/LauRealImagGammaCPCoeffSet.hh +++ b/inc/LauRealImagGammaCPCoeffSet.hh @@ -1,218 +1,240 @@ /* Copyright 2014 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 LauRealImagGammaCPCoeffSet.hh \brief File containing declaration of LauRealImagGammaCPCoeffSet class. */ /*! \class LauRealImagGammaCPCoeffSet \brief Class for defining a complex coefficient using a Cartesian nonCP part multiplied by a simple Cartesian CP convention. Holds a set of real values that define the complex coefficient of an amplitude component. The amplitudes have the form: c = ( x + i * y ) * ( 1 + xCP + i * yCP ) cbar = ( x + i * y ) * ( 1 + xbarCP + i * ybarCP ) [Phys. Rev. D79, 051301 (2009)] */ #ifndef LAU_REALIMAGGAMMACP_COEFF_SET #define LAU_REALIMAGGAMMACP_COEFF_SET #include #include #include #include "Rtypes.h" #include "LauAbsCoeffSet.hh" #include "LauComplex.hh" #include "LauParameter.hh" class LauRealImagGammaCPCoeffSet : public LauAbsCoeffSet { public: //! Constructor /*! \param [in] compName the name of the coefficient set \param [in] x the real nonCP part \param [in] y the imaginary nonCP part \param [in] xCP the real CP part for the particle \param [in] yCP the imaginary CP part for the particle \param [in] xbarCP the real CP part for the antiparticle \param [in] ybarCP the imaginary CP part for the antiparticle \param [in] xFixed whether x is fixed \param [in] yFixed whether y is fixed \param [in] xCPFixed whether x is fixed \param [in] yCPFixed whether y is fixed \param [in] xbarCPFixed whether xbar is fixed \param [in] ybarCPFixed whether ybar is fixed */ LauRealImagGammaCPCoeffSet(const TString& compName, const Double_t x, const Double_t y, const Double_t xCP, const Double_t yCP, const Double_t xbarCP, const Double_t ybarCP, const Bool_t xFixed, const Bool_t yFixed, const Bool_t xCPFixed, const Bool_t yCPFixed, const Bool_t xbarCPFixed, const Bool_t ybarCPFixed); + //! Move constructor (default) + /*! + \param [in] rhs the coefficient to clone + */ + LauRealImagGammaCPCoeffSet(LauRealImagGammaCPCoeffSet&& rhs) = default; + + //! Move assignment operator (default) + /*! + \param [in] rhs the coefficient to clone + */ + LauRealImagGammaCPCoeffSet& operator=(LauRealImagGammaCPCoeffSet&& rhs) = default; + + //! Determine the type of the coefficient + /*! + \return the type of the coefficient + */ + LauCoeffType type() const override { return LauCoeffType::RealImagGammaCP; } + //! Retrieve the parameters of the coefficient, e.g. so that they can be loaded into a fit /*! - \return the parameters of the coefficient + \return the parameters of the coefficient [ x, y, xCP, yCP, xbarCP, ybarCP ] */ std::vector getParameters() override; + //! Retrieve the (const) parameters of the coefficient, e.g. so that they can be queried + /*! + \return the (const) parameters of the coefficient [ x, y, xCP, yCP, xbarCP, ybarCP ] + */ + std::vector getParameters() const override; + //! Print the current values of the parameters void printParValues() const override; //! Print the column headings for a results table /*! \param [out] stream the stream to print to */ void printTableHeading(std::ostream& stream) const override; //! Print the parameters of the complex coefficient as a row in the results table /*! \param [out] stream the stream to print to */ void printTableRow(std::ostream& stream) const override; //! Randomise the starting values of the parameters for a fit void randomiseInitValues() override; //! Make sure values are in "standard" ranges, e.g. phases should be between -pi and pi void finaliseValues() override; //! Retrieve the complex coefficient for a particle /*! \return the complex coefficient for a particle */ const LauComplex& particleCoeff() override; //! Retrieve the complex coefficient for an antiparticle /*! \return the complex coefficient for an antiparticle */ const LauComplex& antiparticleCoeff() override; //! Set the parameters based on the complex coefficients for particles and antiparticles /*! This method is not supported by this class because there are more than four parameters so there is not a unique solution. \param [in] coeff the complex coefficient for a particle \param [in] coeffBar the complex coefficient for an antiparticle \param [in] init whether or not the initial and generated values should also be adjusted */ void setCoeffValues( const LauComplex& coeff, const LauComplex& coeffBar, Bool_t init ) override; //! Calculate the CP asymmetry /*! \return the CP asymmetry */ LauParameter acp() override; //! Create a clone of the coefficient set /*! \param [in] newName the clone's name \param [in] cloneOption special option for the cloning operation \param [in] constFactor a constant factor to multiply the clone's parameters by \return a clone of the coefficient set */ std::unique_ptr createClone(const TString& newName, const CloneOption cloneOption = CloneOption::All, const Double_t constFactor = 1.0) { return std::unique_ptr{this->createClone_impl(newName,cloneOption,constFactor)}; } private: //! Copy constructor (with options) /*! This creates cloned parameters, not copies. \param [in] rhs the coefficient to clone \param [in] cloneOption special option for the cloning operation \param [in] constFactor a constant factor to multiply the clone's parameters by */ LauRealImagGammaCPCoeffSet(const LauRealImagGammaCPCoeffSet& rhs, const CloneOption cloneOption = CloneOption::All, const Double_t constFactor = 1.0); //! Copy constructor (deleted) /*! \param [in] rhs the coefficient to clone */ LauRealImagGammaCPCoeffSet(const LauRealImagGammaCPCoeffSet& rhs) = delete; - //! Move constructor (default) - /*! - \param [in] rhs the coefficient to clone - */ - LauRealImagGammaCPCoeffSet(LauRealImagGammaCPCoeffSet&& rhs) = default; - //! Copy assignment operator (deleted) /*! \param [in] rhs the coefficient to clone */ LauRealImagGammaCPCoeffSet& operator=(const LauRealImagGammaCPCoeffSet& rhs) = delete; - //! Move assignment operator (default) - /*! - \param [in] rhs the coefficient to clone - */ - LauRealImagGammaCPCoeffSet& operator=(LauRealImagGammaCPCoeffSet&& rhs) = default; - //! Create a clone of the coefficient set /*! \param [in] newName the clone's name \param [in] cloneOption special option for the cloning operation \param [in] constFactor a constant factor by which to multiply the cloned parameters \return a clone of the coefficient set */ LauRealImagGammaCPCoeffSet* createClone_impl(const TString& newName, const CloneOption cloneOption, const Double_t constFactor) override; // the actual fit parameters // (need to be pointers so they can be cloned) //! The real nonCP part std::unique_ptr x_; //! The imaginary nonCP part std::unique_ptr y_; //! The real CP part for the particle std::unique_ptr xCP_; //! The imaginary CP part for the particle std::unique_ptr yCP_; //! The real CP part for the antiparticle std::unique_ptr xbarCP_; //! The imaginary CP part for the antiparticle std::unique_ptr ybarCP_; //! The nonCP part of the complex coefficient LauComplex nonCPPart_; //! The CP part of the complex coefficient for the particle LauComplex cpPart_; //! The CP part of the complex coefficient for the antiparticle LauComplex cpAntiPart_; //! The particle complex coefficient LauComplex particleCoeff_; //! The antiparticle complex coefficient LauComplex antiparticleCoeff_; //! The CP asymmetry LauParameter acp_; ClassDefOverride(LauRealImagGammaCPCoeffSet, 0) }; +//! \cond DOXYGEN_IGNORE +namespace nlohmann { + template <> + struct adl_serializer { + static LauRealImagGammaCPCoeffSet from_json(const json& j); + static void to_json(json& j, const LauRealImagGammaCPCoeffSet& t); + }; +} +//! \endcond DOXYGEN_IGNORE + #endif diff --git a/src/LauAbsCoeffSet.cc b/src/LauAbsCoeffSet.cc index b81ee05..093f552 100644 --- a/src/LauAbsCoeffSet.cc +++ b/src/LauAbsCoeffSet.cc @@ -1,188 +1,366 @@ /* 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 LauAbsCoeffSet.cc \brief File containing implementation of LauAbsCoeffSet class. */ +#include #include #include "TString.h" #include "LauAbsCoeffSet.hh" #include "LauConstants.hh" #include "LauParameter.hh" #include "LauRandom.hh" ClassImp(LauAbsCoeffSet); TRandom* LauAbsCoeffSet::randomiser_ = nullptr; Double_t LauAbsCoeffSet::minMagnitude_ = -10.0; Double_t LauAbsCoeffSet::maxMagnitude_ = 10.0; Double_t LauAbsCoeffSet::minPhase_ = -LauConstants::threePi; Double_t LauAbsCoeffSet::maxPhase_ = LauConstants::threePi; Double_t LauAbsCoeffSet::minRealImagPart_ = -10.0; Double_t LauAbsCoeffSet::maxRealImagPart_ = 10.0; Double_t LauAbsCoeffSet::minDelta_ = -2.0; Double_t LauAbsCoeffSet::maxDelta_ = 2.0; LauAbsCoeffSet::LauAbsCoeffSet(const TString& theName, const TString& theBaseName) : name_{theName}, basename_{theBaseName} { } TRandom* LauAbsCoeffSet::getRandomiser() { if ( randomiser_ == nullptr ) { randomiser_ = LauRandom::zeroSeedRandom(); } return randomiser_; } void LauAbsCoeffSet::index(const UInt_t newIndex) { index_ = newIndex; const TString oldBaseName{ this->baseName() }; TString basename{ oldBaseName }; basename += newIndex; basename += "_"; this->baseName(basename); std::vector pars { this->getParameters() }; for ( LauParameter* par : pars ) { this->adjustName( *par, oldBaseName ); } } void LauAbsCoeffSet::adjustName(LauParameter& par, const TString& oldBaseName) { TString theName{ par.name() }; if ( theName.BeginsWith( oldBaseName ) && theName != oldBaseName ) { theName.Remove(0,oldBaseName.Length()); } theName.Prepend(this->baseName()); par.name(theName); } void LauAbsCoeffSet::setParameterValue(const TString& parName, const Double_t value, const Bool_t init) { LauParameter* par { this->findParameter( parName ) }; if ( par == nullptr ) { std::cerr << "ERROR in LauAbsCoeffSet::setParameterValue : Unable to find parameter \"" << parName << "\"" << std::endl; return; } par->value( value ); if ( init ) { par->genValue( value ); par->initValue( value ); } } void LauAbsCoeffSet::setParameterError(const TString& parName, const Double_t error) { LauParameter* par { this->findParameter( parName ) }; if ( par == nullptr ) { std::cerr << "ERROR in LauAbsCoeffSet::setParameterError : Unable to find parameter \"" << parName << "\"" << std::endl; return; } par->error( error ); } void LauAbsCoeffSet::fixParameter(const TString& parName) { LauParameter* par { this->findParameter( parName ) }; if ( par == nullptr ) { std::cerr << "ERROR in LauAbsCoeffSet::fixParameter : Unable to find parameter \"" << parName << "\"" << std::endl; return; } par->fixed( kTRUE ); } void LauAbsCoeffSet::floatParameter(const TString& parName) { LauParameter* par { this->findParameter( parName ) }; if ( par == nullptr ) { std::cerr << "ERROR in LauAbsCoeffSet::floatParameter : Unable to find parameter \"" << parName << "\"" << std::endl; return; } par->fixed( kFALSE ); } void LauAbsCoeffSet::blindParameter(const TString& parName, const TString& blindingString, const Double_t width) { LauParameter* par { this->findParameter( parName ) }; if ( par == nullptr ) { std::cerr << "ERROR in LauAbsCoeffSet::blindParameter : Unable to find parameter \"" << parName << "\"" << std::endl; return; } par->blindParameter( blindingString, width ); } void LauAbsCoeffSet::addGaussianConstraint(const TString& parName, const Double_t mean, const Double_t width) { LauParameter* par { this->findParameter( parName ) }; if ( par == nullptr ) { std::cerr << "ERROR in LauAbsCoeffSet::addGaussianConstraint : Unable to find parameter \"" << parName << "\"" << std::endl; return; } par->addGaussianConstraint( mean, width ); } void LauAbsCoeffSet::addSuffixToParameterName(const TString& parName, const TString& suffix) { LauParameter* par { this->findParameter( parName ) }; if ( par == nullptr ) { std::cerr << "ERROR in LauAbsCoeffSet::addSuffixToParameterName : Unable to find parameter \"" << parName << "\"" << std::endl; return; } TString newName{ par->name() }; if ( ! suffix.BeginsWith('_') ) { newName += "_"; } newName += suffix; par->name( newName ); } LauParameter* LauAbsCoeffSet::findParameter(const TString& parName) { std::vector pars { this->getParameters() }; for ( LauParameter* par : pars ) { const TString& iName { par->name() }; if ( iName.EndsWith( parName ) ) { return par; } } return nullptr; } +#include "LauBelleCPCoeffSet.hh" +#include "LauCartesianCPCoeffSet.hh" +#include "LauCartesianGammaCPCoeffSet.hh" +#include "LauCleoCPCoeffSet.hh" +#include "LauMagPhaseCoeffSet.hh" +#include "LauMagPhaseCPCoeffSet.hh" +#include "LauNSCCartesianCPCoeffSet.hh" +#include "LauPolarGammaCPCoeffSet.hh" +#include "LauRealImagCoeffSet.hh" +#include "LauRealImagCPCoeffSet.hh" +#include "LauRealImagGammaCPCoeffSet.hh" + +void nlohmann::adl_serializer::to_json( json& j, const LauAbsCoeffSet& t ) +{ + switch ( t.type() ) { + case LauCoeffType::MagPhase : + nlohmann::adl_serializer::to_json( j, static_cast(t)); + break; + case LauCoeffType::RealImag : + nlohmann::adl_serializer::to_json( j, static_cast(t)); + break; + case LauCoeffType::BelleCP : + nlohmann::adl_serializer::to_json( j, static_cast(t)); + break; + case LauCoeffType::CartesianCP : + nlohmann::adl_serializer::to_json( j, static_cast(t)); + break; + case LauCoeffType::CartesianGammaCP : + nlohmann::adl_serializer::to_json( j, static_cast(t)); + break; + case LauCoeffType::CleoCP : + nlohmann::adl_serializer::to_json( j, static_cast(t)); + break; + case LauCoeffType::MagPhaseCP : + nlohmann::adl_serializer::to_json( j, static_cast(t)); + break; + case LauCoeffType::NSCCartesianCP : + nlohmann::adl_serializer::to_json( j, static_cast(t)); + break; + case LauCoeffType::PolarGammaCP : + nlohmann::adl_serializer::to_json( j, static_cast(t)); + break; + case LauCoeffType::RealImagCP : + nlohmann::adl_serializer::to_json( j, static_cast(t)); + break; + case LauCoeffType::RealImagGammaCP : + nlohmann::adl_serializer::to_json( j, static_cast(t)); + break; + } +} + +std::vector> LauAbsCoeffSet::readFromJson( const TString& fileName ) +{ + using nlohmann::json; + + std::ifstream in(fileName, std::ios_base::in); + if ( ! in ) { + std::cerr << "ERROR in LauAbsCoeffSet::readFromJson : couldn't open file \"" << fileName << "\"" << std::endl; + return {}; + } + + json j; + in >> j; + + const auto nCoeffs { j.at("nCoeffs").get() }; + std::vector> coeffs; + coeffs.reserve( nCoeffs ); + + for ( auto& coeff : j.at("coeffs") ) { + + const LauCoeffType type { coeff.at("type").get() }; + switch ( type ) { + case LauCoeffType::MagPhase : + coeffs.emplace_back( std::make_unique( coeff.get() ) ); + break; + case LauCoeffType::RealImag : + coeffs.emplace_back( std::make_unique( coeff.get() ) ); + break; + case LauCoeffType::BelleCP : + coeffs.emplace_back( std::make_unique( coeff.get() ) ); + break; + case LauCoeffType::CartesianCP : + coeffs.emplace_back( std::make_unique( coeff.get() ) ); + break; + case LauCoeffType::CartesianGammaCP : + coeffs.emplace_back( std::make_unique( coeff.get() ) ); + break; + case LauCoeffType::CleoCP : + coeffs.emplace_back( std::make_unique( coeff.get() ) ); + break; + case LauCoeffType::MagPhaseCP : + coeffs.emplace_back( std::make_unique( coeff.get() ) ); + break; + case LauCoeffType::NSCCartesianCP : + coeffs.emplace_back( std::make_unique( coeff.get() ) ); + break; + case LauCoeffType::PolarGammaCP : + coeffs.emplace_back( std::make_unique( coeff.get() ) ); + break; + case LauCoeffType::RealImagCP : + coeffs.emplace_back( std::make_unique( coeff.get() ) ); + break; + case LauCoeffType::RealImagGammaCP : + coeffs.emplace_back( std::make_unique( coeff.get() ) ); + break; + } + } + + return coeffs; +} + +void LauAbsCoeffSet::writeToJson( const TString& fileName, const std::vector>& coeffs ) +{ + using nlohmann::json; + + json j; + + j["nCoeffs"] = coeffs.size(); + + j["coeffs"] = json::array(); + + for ( auto& coeffset : coeffs ) { + + j["coeffs"].push_back( *coeffset ); + + } + + std::ofstream out{fileName, std::ios_base::out}; + if ( ! out ) { + std::cerr << "ERROR in LauAbsCoeffSet::writeToJson : couldn't open file \"" << fileName << "\" for writing. No file will be written!" << std::endl; + return; + } + + out << j.dump(4); + out << std::endl; +} + +std::ostream& operator<<( std::ostream& os, const LauCoeffType type ) +{ + switch ( type ) { + case LauCoeffType::MagPhase : + os << "MagPhase"; + break; + case LauCoeffType::RealImag : + os << "RealImag"; + break; + case LauCoeffType::BelleCP : + os << "BelleCP"; + break; + case LauCoeffType::CartesianCP : + os << "CartesianCP"; + break; + case LauCoeffType::CartesianGammaCP : + os << "CartesianGammaCP"; + break; + case LauCoeffType::CleoCP : + os << "CleoCP"; + break; + case LauCoeffType::MagPhaseCP : + os << "MagPhaseCP"; + break; + case LauCoeffType::NSCCartesianCP : + os << "NSCCartesianCP"; + break; + case LauCoeffType::PolarGammaCP : + os << "PolarGammaCP"; + break; + case LauCoeffType::RealImagCP : + os << "RealImagCP"; + break; + case LauCoeffType::RealImagGammaCP : + os << "RealImagGammaCP"; + break; + } + + return os; +} diff --git a/src/LauBelleCPCoeffSet.cc b/src/LauBelleCPCoeffSet.cc index 4110d92..8b0740f 100644 --- a/src/LauBelleCPCoeffSet.cc +++ b/src/LauBelleCPCoeffSet.cc @@ -1,340 +1,386 @@ /* 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 LauBelleCPCoeffSet.cc \brief File containing implementation of LauBelleCPCoeffSet class. */ #include #include #include #include "TMath.h" #include "TRandom.h" #include "LauComplex.hh" #include "LauConstants.hh" #include "LauBelleCPCoeffSet.hh" #include "LauParameter.hh" #include "LauPrint.hh" ClassImp(LauBelleCPCoeffSet) LauBelleCPCoeffSet::LauBelleCPCoeffSet(const TString& compName, const Double_t a, const Double_t delta, const Double_t b, const Double_t phi, const Bool_t aFixed, const Bool_t deltaFixed, const Bool_t bFixed, const Bool_t phiFixed, const Bool_t bSecondStage, const Bool_t phiSecondStage) : LauAbsCoeffSet{ compName }, a_{ std::make_unique("A", a, minMagnitude_, maxMagnitude_, aFixed) }, b_{ std::make_unique("B", b, minMagnitude_, maxMagnitude_, bFixed) }, delta_{ std::make_unique("Delta", delta, minPhase_, maxPhase_, deltaFixed) }, phi_{ std::make_unique("Phi", phi, minPhase_, maxPhase_, phiFixed) }, acp_{ "ACP", (-2.0*b*TMath::Cos(phi))/(1.0+b*b), -1.0, 1.0, bFixed&&phiFixed } { if (bSecondStage && !bFixed) { b_->secondStage(kTRUE); b_->initValue(0.0); } if (phiSecondStage && !phiFixed) { phi_->secondStage(kTRUE); phi_->initValue(0.0); } } LauBelleCPCoeffSet::LauBelleCPCoeffSet(const LauBelleCPCoeffSet& rhs, const CloneOption cloneOption, const Double_t constFactor) : LauAbsCoeffSet{ rhs.name() }, particleCoeff_{ rhs.particleCoeff_ }, antiparticleCoeff_{ rhs.antiparticleCoeff_ }, acp_{ rhs.acp_ } { if ( cloneOption == CloneOption::All || cloneOption == CloneOption::TieMagnitude ) { a_.reset( rhs.a_->createClone(constFactor) ); } else { a_ = std::make_unique("A", rhs.a_->value(), minMagnitude_, maxMagnitude_, rhs.a_->fixed()); if ( rhs.a_->blind() ) { const LauBlind* blinder { rhs.a_->blinder() }; a_->blindParameter( blinder->blindingString(), blinder->blindingWidth() ); } } if ( cloneOption == CloneOption::All || cloneOption == CloneOption::TieCPPars ) { b_.reset( rhs.b_->createClone(constFactor) ); } else { b_ = std::make_unique("B", rhs.b_->value(), minMagnitude_, maxMagnitude_, rhs.b_->fixed()); if ( rhs.b_->blind() ) { const LauBlind* blinder { rhs.b_->blinder() }; b_->blindParameter( blinder->blindingString(), blinder->blindingWidth() ); } } if ( cloneOption == CloneOption::All || cloneOption == CloneOption::TiePhase ) { delta_.reset( rhs.delta_->createClone(constFactor) ); } else { delta_ = std::make_unique("Delta", rhs.delta_->value(), minPhase_, maxPhase_, rhs.delta_->fixed()); if ( rhs.delta_->blind() ) { const LauBlind* blinder { rhs.delta_->blinder() }; delta_->blindParameter( blinder->blindingString(), blinder->blindingWidth() ); } } if ( cloneOption == CloneOption::All || cloneOption == CloneOption::TieCPPars ) { phi_.reset( rhs.phi_->createClone(constFactor) ); } else { phi_ = std::make_unique("Phi", rhs.phi_->value(), minPhase_, maxPhase_, rhs.phi_->fixed()); if ( rhs.phi_->blind() ) { const LauBlind* blinder { rhs.phi_->blinder() }; phi_->blindParameter( blinder->blindingString(), blinder->blindingWidth() ); } } } -std::vector LauBelleCPCoeffSet::getParameters() -{ - return { a_.get(), b_.get(), delta_.get(), phi_.get() }; -} - void LauBelleCPCoeffSet::printParValues() const { std::cout<<"INFO in LauBelleCPCoeffSet::printParValues : Component \""<name()<<"\" has "; std::cout<<"a-magnitude = "<value()<<",\t"; std::cout<<"delta = "<value()<<",\t"; std::cout<<"b-magnitude = "<value()<<",\t"; std::cout<<"phi = "<value()<<"."<name() }; resName = resName.ReplaceAll("_", "\\_"); stream<value()); stream<<" \\pm "; print.printFormat(stream, a_->error()); stream<<"$ & $"; print.printFormat(stream, delta_->value()); stream<<" \\pm "; print.printFormat(stream, delta_->error()); stream<<"$ & $"; print.printFormat(stream, b_->value()); stream<<" \\pm "; print.printFormat(stream, b_->error()); stream<<"$ & $"; print.printFormat(stream, phi_->value()); stream<<" \\pm "; print.printFormat(stream, phi_->error()); stream<<"$ \\\\"<fixed() == kFALSE) { // Choose an a-magnitude between 0.0 and 2.0 const Double_t mag { LauAbsCoeffSet::getRandomiser()->Rndm()*2.0 }; a_->initValue(mag); a_->value(mag); } if (b_->fixed() == kFALSE && b_->secondStage() == kFALSE) { // Choose a b-magnitude between 0.0 and 0.1 const Double_t mag { LauAbsCoeffSet::getRandomiser()->Rndm()*0.1 }; b_->initValue(mag); b_->value(mag); } if (delta_->fixed() == kFALSE) { // Choose a phase between +- pi const Double_t phase { LauAbsCoeffSet::getRandomiser()->Rndm()*LauConstants::twoPi - LauConstants::pi }; delta_->initValue(phase); delta_->value(phase); } if (phi_->fixed() == kFALSE && phi_->secondStage() == kFALSE) { // Choose a phase between +- pi const Double_t phase { LauAbsCoeffSet::getRandomiser()->Rndm()*LauConstants::twoPi - LauConstants::pi }; phi_->initValue(phase); phi_->value(phase); } } void LauBelleCPCoeffSet::finaliseValues() { // retrieve the current values from the parameters Double_t aVal { a_->value() }; Double_t bVal { b_->value() }; Double_t deltaVal { delta_->value() }; Double_t phiVal { phi_->value() }; // Check whether we have a negative "a" magnitude. // If so make it positive and add pi to the "delta" phase. if (aVal < 0.0) { aVal *= -1.0; deltaVal += LauConstants::pi; } // Check whether we have a negative "b" magnitude. // If so make it positive and add pi to the "phi" phase. if (bVal < 0.0) { bVal *= -1.0; phiVal += LauConstants::pi; } // Check now whether the phases lies in the right range (-pi to pi). Bool_t deltaWithinRange{kFALSE}; Bool_t phiWithinRange{kFALSE}; while (deltaWithinRange == kFALSE && phiWithinRange == kFALSE) { if (deltaVal > -LauConstants::pi && deltaVal < LauConstants::pi) { deltaWithinRange = kTRUE; } else { // Not within the specified range if (deltaVal > LauConstants::pi) { deltaVal -= LauConstants::twoPi; } else if (deltaVal < -LauConstants::pi) { deltaVal += LauConstants::twoPi; } } if (phiVal > -LauConstants::pi && phiVal < LauConstants::pi) { phiWithinRange = kTRUE; } else { // Not within the specified range if (phiVal > LauConstants::pi) { phiVal -= LauConstants::twoPi; } else if (phiVal < -LauConstants::pi) { phiVal += 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. const Double_t genDelta { delta_->genValue() }; const Double_t genPhi { phi_->genValue() }; Double_t diff { deltaVal - genDelta }; if (diff > LauConstants::pi) { deltaVal -= LauConstants::twoPi; } else if (diff < -LauConstants::pi) { deltaVal += LauConstants::twoPi; } diff = phiVal - genPhi; if (diff > LauConstants::pi) { phiVal -= LauConstants::twoPi; } else if (diff < -LauConstants::pi) { phiVal += LauConstants::twoPi; } // finally store the new values in the parameters // and update the pulls a_->value(aVal); a_->updatePull(); b_->value(bVal); b_->updatePull(); delta_->value(deltaVal); delta_->updatePull(); phi_->value(phiVal); phi_->updatePull(); } const LauComplex& LauBelleCPCoeffSet::particleCoeff() { const LauComplex aTerm{a_->unblindValue()*TMath::Cos(delta_->unblindValue()), a_->unblindValue()*TMath::Sin(delta_->unblindValue())}; const LauComplex bTerm{b_->unblindValue()*TMath::Cos(phi_->unblindValue()), b_->unblindValue()*TMath::Sin(phi_->unblindValue())}; particleCoeff_.setRealImagPart(1.0,0.0); particleCoeff_ += bTerm; particleCoeff_ *= aTerm; return particleCoeff_; } const LauComplex& LauBelleCPCoeffSet::antiparticleCoeff() { const LauComplex aTerm{a_->unblindValue()*TMath::Cos(delta_->unblindValue()), a_->unblindValue()*TMath::Sin(delta_->unblindValue())}; const LauComplex bTerm{b_->unblindValue()*TMath::Cos(phi_->unblindValue()), b_->unblindValue()*TMath::Sin(phi_->unblindValue())}; antiparticleCoeff_.setRealImagPart(1.0,0.0); antiparticleCoeff_ -= bTerm; antiparticleCoeff_ *= aTerm; return antiparticleCoeff_; } void LauBelleCPCoeffSet::setCoeffValues( const LauComplex& coeff, const LauComplex& coeffBar, const Bool_t init ) { const LauComplex sum { coeff + coeffBar }; const LauComplex diff { coeff - coeffBar }; const LauComplex ratio { diff / sum }; const Double_t aVal{ 0.5 * sum.abs() }; const Double_t deltaVal{ sum.arg() }; const Double_t bVal{ ratio.abs() }; const Double_t phiVal{ ratio.arg() }; a_->value( aVal ); delta_->value( deltaVal ); b_->value( bVal ); phi_->value( phiVal ); if ( init ) { a_->genValue( aVal ); delta_->genValue( deltaVal ); b_->genValue( bVal ); phi_->genValue( phiVal ); a_->initValue( aVal ); delta_->initValue( deltaVal ); b_->initValue( bVal ); phi_->initValue( phiVal ); } } LauParameter LauBelleCPCoeffSet::acp() { // set the name const TString parName{ this->baseName() + "_ACP" }; acp_.name(parName); // work out the ACP value const Double_t value { (-2.0*b_->value()*TMath::Cos(phi_->value()))/(1.0+b_->value()*b_->value()) }; // is it fixed? const Bool_t fixed { b_->fixed() && phi_->fixed() }; acp_.fixed(fixed); // we can't work out the error without the covariance matrix const Double_t error{0.0}; // set the value and error acp_.valueAndErrors(value,error); return acp_; } LauBelleCPCoeffSet* LauBelleCPCoeffSet::createClone_impl(const TString& newName, const CloneOption cloneOption, const Double_t constFactor) { if ( ! ( cloneOption == CloneOption::All || cloneOption == CloneOption::TiePhase || cloneOption == CloneOption::TieMagnitude || cloneOption == CloneOption::TieCPPars ) ) { std::cerr << "ERROR in LauBelleCPCoeffSet::createClone : Invalid clone option" << std::endl; return nullptr; } auto clone = new LauBelleCPCoeffSet{ *this, cloneOption, constFactor }; clone->name( newName ); return clone; } + +LauBelleCPCoeffSet nlohmann::adl_serializer::from_json(const json& j) +{ + const LauCoeffType type { j.at("type").get() }; + if ( type != LauCoeffType::BelleCP ) { + throw LauWrongCoeffType("Wrong coefficient type given to construct LauRealImagCoeffSet"); + } + + const TString name { j.at("name").get().c_str() }; + + // TODO - handle cloned coeffs + + const Double_t a { j.at("a").get() }; + const Double_t delta { j.at("delta").get() }; + const Double_t b { j.at("b").get() }; + const Double_t phi { j.at("phi").get() }; + + const Bool_t aFixed { j.at("aFixed").get() }; + const Bool_t deltaFixed { j.at("deltaFixed").get() }; + const Bool_t bFixed { j.at("bFixed").get() }; + const Bool_t phiFixed { j.at("phiFixed").get() }; + + // TODO - these should be optional? + const Bool_t bSecondStage { j.at("bSecondStage").get() }; + const Bool_t phiSecondStage { j.at("phiSecondStage").get() }; + + return { name, a, delta, b, phi, aFixed, deltaFixed, bFixed, phiFixed, bSecondStage, phiSecondStage }; +} + +void nlohmann::adl_serializer::to_json(json& j, const LauBelleCPCoeffSet& t) +{ + j["type"] = LauCoeffType::BelleCP; + j["name"] = t.name(); + + // TODO - handle cloned coeffs + + auto pars = t.getParameters(); + + j["a"] = pars[0]->value(); + j["delta"] = pars[1]->value(); + j["b"] = pars[2]->value(); + j["phi"] = pars[3]->value(); + + j["aFixed"] = pars[0]->fixed(); + j["deltaFixed"] = pars[1]->fixed(); + j["bFixed"] = pars[2]->fixed(); + j["phiFixed"] = pars[3]->fixed(); + + j["bSecondStage"] = pars[2]->secondStage(); + j["phiSecondStage"] = pars[3]->secondStage(); +} diff --git a/src/LauBsCPFitModel.cc b/src/LauBsCPFitModel.cc index 8f5cd41..6527437 100644 --- a/src/LauBsCPFitModel.cc +++ b/src/LauBsCPFitModel.cc @@ -1,2674 +1,2674 @@ /* Copyright 2015 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 LauBsCPFitModel.cc \brief File containing implementation of LauBsCPFitModel class. */ #include #include #include #include #include "TVirtualFitter.h" #include "TSystem.h" #include "TMinuit.h" #include "TRandom.h" #include "TFile.h" #include "TMath.h" #include "TH2.h" #include "LauAbsBkgndDPModel.hh" #include "LauAbsCoeffSet.hh" #include "LauIsobarDynamics.hh" #include "LauAbsPdf.hh" #include "LauAsymmCalc.hh" #include "LauComplex.hh" #include "LauConstants.hh" #include "LauBsCPFitModel.hh" #include "LauDaughters.hh" #include "LauEffModel.hh" #include "LauFitNtuple.hh" #include "LauKinematics.hh" #include "LauPrint.hh" #include "LauRandom.hh" #include "LauScfMap.hh" #include "LauDPPartialIntegralInfo.hh" ClassImp(LauBsCPFitModel) LauBsCPFitModel::LauBsCPFitModel(LauIsobarDynamics* negModel, LauIsobarDynamics* posModel, Double_t D) : LauAbsFitModel(), negSigModel_(negModel), posSigModel_(posModel), negKinematics_(negModel ? negModel->getKinematics() : 0), posKinematics_(posModel ? posModel->getKinematics() : 0), D_(D), usingBkgnd_(kFALSE), nSigComp_(0), nSigDPPar_(0), nExtraPdfPar_(0), nNormPar_(0), interTermReNorm_(0.0), normDP_(0.0), negMeanEff_("negMeanEff",0.0,0.0,1.0), posMeanEff_("posMeanEff",0.0,0.0,1.0), negDPRate_("negDPRate",0.0,0.0,100.0), posDPRate_("posDPRate",0.0,0.0,100.0), signalEvents_(0), useSCF_(kFALSE), useSCFHist_(kFALSE), scfFrac_("scfFrac",0.0,0.0,1.0), scfFracHist_(0), scfMap_(0), compareFitData_(kFALSE), negParent_("B_s0_bar"), posParent_("B_s0"), iterationsMax_(100000), nGenLoop_(0), ASq_(0.0), aSqMaxVar_(0.0), aSqMaxSet_(1.25), sigDPLike_(0.0), scfDPLike_(0.0), sigExtraLike_(0.0), scfExtraLike_(0.0), sigTotalLike_(0.0), scfTotalLike_(0.0) { const LauDaughters* negDaug = negSigModel_->getDaughters(); if (negDaug != 0) {negParent_ = negDaug->getNameParent();} const LauDaughters* posDaug = posSigModel_->getDaughters(); if (posDaug != 0) {posParent_ = posDaug->getNameParent();} } LauBsCPFitModel::~LauBsCPFitModel() { delete scfFracHist_; } void LauBsCPFitModel::setupBkgndVectors() { UInt_t nBkgnds = this->nBkgndClasses(); bkgndDPModels_.resize( nBkgnds ); bkgndPdfs_.resize( nBkgnds ); bkgndEvents_.resize( nBkgnds ); bkgndDPLike_.resize( nBkgnds ); bkgndExtraLike_.resize( nBkgnds ); bkgndTotalLike_.resize( nBkgnds ); } void LauBsCPFitModel::setNSigEvents(LauParameter* nSigEvents) { if ( nSigEvents == 0 ) { std::cerr << "ERROR in LauBsCPFitModel::setNSigEvents : The LauParameter pointer is null." << std::endl; gSystem->Exit(EXIT_FAILURE); } if ( signalEvents_ != 0 ) { std::cerr << "ERROR in LauBsCPFitModel::setNSigEvents : You are trying to overwrite the signal yield." << std::endl; return; } signalEvents_ = nSigEvents; TString name = signalEvents_->name(); if ( ! name.Contains("signalEvents") && !( name.BeginsWith("signal") && name.EndsWith("Events") ) ) { signalEvents_->name("signalEvents"); } Double_t value = nSigEvents->value(); signalEvents_->range(-2.0*(TMath::Abs(value)+1.0), 2.0*(TMath::Abs(value)+1.0)); } void LauBsCPFitModel::setNBkgndEvents( LauAbsRValue* nBkgndEvents ) { if ( nBkgndEvents == 0 ) { std::cerr << "ERROR in LauBsCPFitModel::setNBgkndEvents : The background yield LauParameter pointer is null." << std::endl; gSystem->Exit(EXIT_FAILURE); } if ( ! this->validBkgndClass( nBkgndEvents->name() ) ) { std::cerr << "ERROR in LauBsCPFitModel::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 LauBsCPFitModel::setNBkgndEvents : You are trying to overwrite the background yield." << 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; } void LauBsCPFitModel::splitSignalComponent( const TH2* dpHisto, const Bool_t upperHalf, const Bool_t fluctuateBins, LauScfMap* scfMap ) { if ( useSCF_ == kTRUE ) { std::cerr << "ERROR in LauBsCPFitModel::splitSignalComponent : Have already setup SCF." << std::endl; return; } if ( dpHisto == 0 ) { std::cerr << "ERROR in LauBsCPFitModel::splitSignalComponent : The histogram pointer is null." << std::endl; return; } const LauDaughters* daughters = negSigModel_->getDaughters(); scfFracHist_ = new LauEffModel( daughters, 0 ); scfFracHist_->setEffHisto( dpHisto, kTRUE, fluctuateBins, 0.0, 0.0, upperHalf, daughters->squareDP() ); scfMap_ = scfMap; useSCF_ = kTRUE; useSCFHist_ = kTRUE; } void LauBsCPFitModel::splitSignalComponent( const Double_t scfFrac, const Bool_t fixed ) { if ( useSCF_ == kTRUE ) { std::cerr << "ERROR in LauBsCPFitModel::splitSignalComponent : Have already setup SCF." << std::endl; return; } scfFrac_.range( 0.0, 1.0 ); scfFrac_.value( scfFrac ); scfFrac_.initValue( scfFrac ); scfFrac_.genValue( scfFrac ); scfFrac_.fixed( fixed ); useSCF_ = kTRUE; useSCFHist_ = kFALSE; } void LauBsCPFitModel::setBkgndDPModel(const TString& bkgndClass, LauAbsBkgndDPModel* model) { if (model==0){ std::cerr << "ERROR in LauBsCPFitModel::setBkgndDPModels : the model pointer is null." << std::endl; return; } // check that this background name is valid if ( ! this->validBkgndClass( bkgndClass) ) { std::cerr << "ERROR in LauBsCPFitModel::setBkgndDPModel : 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 ); bkgndDPModels_[bkgndID] = model; usingBkgnd_ = kTRUE; } void LauBsCPFitModel::setSignalPdf(LauAbsPdf* pdf) { // if we're doing an untagged analysis we will only use the negative PDFs if ( pdf==0 ) { std::cerr << "ERROR in LauBsCPFitModel::setSignalPdfs : The PDF pointer is null." << std::endl; return; } signalPdfs_.push_back(pdf); } void LauBsCPFitModel::setSCFPdf(LauAbsPdf* pdf) { // if we're doing an untagged analysis we will only use the negative PDFs if ( pdf==0 ) { std::cerr << "ERROR in LauBsCPFitModel::setSCFPdfs : The PDF pointer is null." << std::endl; return; } scfPdfs_.push_back(pdf); } void LauBsCPFitModel::setBkgndPdf(const TString& bkgndClass, LauAbsPdf* pdf) { // if we're doing an untagged analysis we will only use the negative PDFs if ( pdf==0 ) { std::cerr << "ERROR in LauBsCPFitModel::setBkgndPdfs : The PDF pointer is null." << std::endl; return; } // check that this background name is valid if ( ! this->validBkgndClass( bkgndClass ) ) { std::cerr << "ERROR in LauBsCPFitModel::setBkgndPdfs : 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 LauBsCPFitModel::setAmpCoeffSet(std::unique_ptr coeffSet) { // Is there a component called compName in the signal model? const TString compName{ coeffSet->name() }; const Bool_t negOK { negSigModel_->hasResonance(compName) }; const Bool_t posOK { posSigModel_->hasResonance(compName) }; if (!negOK) { std::cerr << "ERROR in LauBsCPFitModel::setMagPhase : " << negParent_ << " signal DP model doesn't contain component \"" << compName << "\"." << std::endl; return; } if (!posOK) { std::cerr << "ERROR in LauBsCPFitModel::setMagPhase : " << posParent_ << " signal DP model doesn't contain component \"" << compName << "\"." << std::endl; return; } // Do we already have it in our list of names? for ( const auto& coeff : coeffPars_ ) { if ( coeff->name() == compName ) { std::cerr << "ERROR in LauBsCPFitModel::setAmpCoeffSet : Have already set coefficients for \"" << compName << "\"." << std::endl; return; } } coeffSet->index(nSigComp_); const TString parName { coeffSet->baseName() + "FitFracAsym" }; fitFracAsymm_.emplace_back(parName, 0.0, -1.0, 1.0); acp_.push_back(coeffSet->acp()); ++nSigComp_; std::cout << "INFO in LauBsCPFitModel::setAmpCoeffSet : Added coefficients for component \"" << compName << "\" to the fit model." << std::endl; coeffSet->printParValues(); coeffPars_.push_back( std::move(coeffSet) ); } void LauBsCPFitModel::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(); } if (!this->useDP() && signalPdfs_.empty()) { std::cerr << "ERROR in LauBsCPFitModel::initialise : Signal model doesn't exist for any variable." << std::endl; gSystem->Exit(EXIT_FAILURE); } if ( this->useDP() ) { // Check that we have all the Dalitz-plot models if ((negSigModel_ == 0) || (posSigModel_ == 0)) { std::cerr << "ERROR in LauBsCPFitModel::initialise : the pointer to one (neg or pos) of the signal DP models is null.\n"; std::cerr << " : Removing the Dalitz Plot from the model." << std::endl; this->useDP(kFALSE); } if ( usingBkgnd_ ) { if ( bkgndDPModels_.empty() ) { std::cerr << "ERROR in LauBsCPFitModel::initialise : No background DP models found.\n"; std::cerr << " : Removing the Dalitz plot from the model." << std::endl; this->useDP(kFALSE); } for (LauBkgndDPModelList::const_iterator dpmodel_iter = bkgndDPModels_.begin(); dpmodel_iter != bkgndDPModels_.end(); ++dpmodel_iter ) { if ( (*dpmodel_iter) == 0 ) { std::cerr << "ERROR in LauBsCPFitModel::initialise : The pointer to one of the background DP models is null.\n"; std::cerr << " : Removing the Dalitz Plot from the model." << std::endl; this->useDP(kFALSE); break; } } } } // 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 = signalPdfs_.begin(); pdf_iter != signalPdfs_.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 (useSCF_) { UInt_t nscfpdfvars(0); for ( LauPdfPList::const_iterator pdf_iter = scfPdfs_.begin(); pdf_iter != scfPdfs_.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" ) { ++nscfpdfvars; } } } if (nscfpdfvars != nsigpdfvars) { std::cerr << "ERROR in LauBsCPFitModel::initialise : There are " << nsigpdfvars << " TM signal PDF variables but " << nscfpdfvars << " SCF signal PDF variables." << std::endl; gSystem->Exit(EXIT_FAILURE); } } if (usingBkgnd_) { for (LauBkgndPdfsList::const_iterator bgclass_iter = bkgndPdfs_.begin(); bgclass_iter != bkgndPdfs_.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 LauBsCPFitModel::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 various extra PDFs this->setExtraPdfParameters(); // Set the initial bg and signal events this->setFitNEvents(); // Check that we have the expected number of fit variables const LauParameterPList& fitVars = this->fitPars(); if (fitVars.size() != (nSigDPPar_ + nExtraPdfPar_ + nNormPar_)) { std::cerr << "ERROR in LauBsCPFitModel::initialise : Number of fit parameters not of expected size. Exiting" << std::endl; gSystem->Exit(EXIT_FAILURE); } this->setExtraNtupleVars(); } void LauBsCPFitModel::recalculateNormalisation() { //std::cout << "INFO in LauBsCPFitModel::recalculateNormalizationInDPModels : Recalc Norm in DP model" << std::endl; negSigModel_->recalculateNormalisation(); posSigModel_->recalculateNormalisation(); negSigModel_->modifyDataTree(); posSigModel_->modifyDataTree(); this->calcInterferenceTermIntegrals(); } void LauBsCPFitModel::initialiseDPModels() { // Need to check that the number of components we have and that the dynamics has matches up UInt_t nNegAmp = negSigModel_->getnTotAmp(); UInt_t nPosAmp = posSigModel_->getnTotAmp(); if ( nNegAmp != nPosAmp ) { std::cerr << "ERROR in LauBsCPFitModel::initialiseDPModels : Unequal number of signal DP components in the negative and positive models: " << nNegAmp << " != " << nPosAmp << std::endl; gSystem->Exit(EXIT_FAILURE); } if ( nNegAmp != nSigComp_ ) { std::cerr << "ERROR in LauBsCPFitModel::initialiseDPModels : Number of signal DP components in the model (" << nNegAmp << ") not equal to number of coefficients supplied (" << nSigComp_ << ")." << std::endl; gSystem->Exit(EXIT_FAILURE); } std::cout << "INFO in LauBsCPFitModel::initialiseDPModels : Initialising signal DP model" << std::endl; negSigModel_->initialise(negCoeffs_); posSigModel_->initialise(posCoeffs_); if (usingBkgnd_ == kTRUE) { for (LauBkgndDPModelList::iterator iter = bkgndDPModels_.begin(); iter != bkgndDPModels_.end(); ++iter) { (*iter)->initialise(); } } 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->calcInterTermNorm(); this->calculateAmplitudeNorm(); } void LauBsCPFitModel::calcInterferenceTermIntegrals() { const std::vector& integralInfoListB0bar = negSigModel_->getIntegralInfos(); const std::vector& integralInfoListB0 = posSigModel_->getIntegralInfos(); 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; // TODO - do we need to check that this point is within the DP or will the values stored for such points be appropriate? Or are they random junk? for (UInt_t iAmp = 0; iAmp < nSigComp_; ++iAmp) { A = integralInfoB0->getAmplitude(m13, m23, iAmp); // TODO - this loop over j perhaps needs only to be from jAmp = iAmp (we only need the upper half of the matrix) 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 LauBsCPFitModel::setSignalDPParameters() { // Set the fit parameters for the signal model. nSigDPPar_ = 0; if ( ! this->useDP() ) { return; } std::cout << "INFO in LauBsCPFitModel::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 container of resonance parameters LauParameterPList& negSigDPPars = negSigModel_->getFloatingParameters(); LauParameterPList& posSigDPPars = posSigModel_->getFloatingParameters(); nSigDPPar_ += this->addResonanceParameters( negSigDPPars ); nSigDPPar_ += this->addResonanceParameters( posSigDPPars ); } void LauBsCPFitModel::setExtraPdfParameters() { // Include all the parameters of the PDF 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; nExtraPdfPar_ += this->addFitParameters(signalPdfs_); if (useSCF_ == kTRUE) { nExtraPdfPar_ += this->addFitParameters(scfPdfs_); } if (usingBkgnd_ == kTRUE) { for (LauBkgndPdfsList::iterator iter = bkgndPdfs_.begin(); iter != bkgndPdfs_.end(); ++iter) { nExtraPdfPar_ += this->addFitParameters(*iter); } } } void LauBsCPFitModel::setFitNEvents() { if ( signalEvents_ == 0 ) { std::cerr << "ERROR in LauBsCPFitModel::setFitNEvents : Signal yield not defined." << std::endl; return; } nNormPar_ = 0; // initialise the total number of events to be the sum of all the hypotheses Double_t nTotEvts = signalEvents_->value(); for (LauBkgndYieldList::const_iterator iter = bkgndEvents_.begin(); iter != bkgndEvents_.end(); ++iter) { nTotEvts += (*iter)->value(); if ( (*iter) == 0 ) { std::cerr << "ERROR in LauBsCPFitModel::setFitNEvents : Background yield not defined." << std::endl; return; } } this->eventsPerExpt(TMath::FloorNint(nTotEvts)); // if doing an extended ML fit add the number of signal events into the fit parameters if (this->doEMLFit()) { std::cout << "INFO in LauBsCPFitModel::setFitNEvents : Initialising number of events for signal and background components..." << std::endl; // add the signal fraction to the list of fit parameters nNormPar_ += this->addFitParameters( signalEvents_ ); } else { std::cout << "INFO in LauBsCPFitModel::setFitNEvents : Initialising number of events for background components (and hence signal)..." << std::endl; } if (useSCF_ && !useSCFHist_) { nNormPar_ += this->addFitParameters( &scfFrac_ ); } if (usingBkgnd_ == kTRUE) { nNormPar_ += this->addFitParameters( bkgndEvents_ ); } } void LauBsCPFitModel::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 positive and negative fit fractions for each signal component negFitFrac_ = negSigModel_->getFitFractions(); if (negFitFrac_.size() != nSigComp_) { std::cerr << "ERROR in LauBsCPFitModel::setExtraNtupleVars : Initial Fit Fraction array of unexpected dimension: " << negFitFrac_.size() << std::endl; gSystem->Exit(EXIT_FAILURE); } for (UInt_t i(0); iExit(EXIT_FAILURE); } } posFitFrac_ = posSigModel_->getFitFractions(); if (posFitFrac_.size() != nSigComp_) { std::cerr << "ERROR in LauBsCPFitModel::setExtraNtupleVars : Initial Fit Fraction array of unexpected dimension: " << posFitFrac_.size() << std::endl; gSystem->Exit(EXIT_FAILURE); } for (UInt_t i(0); iExit(EXIT_FAILURE); } } // Add the positive and negative fit fractions that have not been corrected for the efficiency for each signal component negFitFracEffUnCorr_ = negSigModel_->getFitFractionsEfficiencyUncorrected(); if (negFitFracEffUnCorr_.size() != nSigComp_) { std::cerr << "ERROR in LauBsCPFitModel::setExtraNtupleVars : Initial Fit Fraction array of unexpected dimension: " << negFitFracEffUnCorr_.size() << std::endl; gSystem->Exit(EXIT_FAILURE); } for (UInt_t i(0); iExit(EXIT_FAILURE); } } posFitFracEffUnCorr_ = posSigModel_->getFitFractionsEfficiencyUncorrected(); if (posFitFracEffUnCorr_.size() != nSigComp_) { std::cerr << "ERROR in LauBsCPFitModel::setExtraNtupleVars : Initial Fit Fraction array of unexpected dimension: " << posFitFracEffUnCorr_.size() << std::endl; gSystem->Exit(EXIT_FAILURE); } for (UInt_t i(0); iExit(EXIT_FAILURE); } } for (UInt_t i(0); i negExtraPars = negSigModel_->getExtraParameters(); std::vector::iterator negExtraIter; for (negExtraIter = negExtraPars.begin(); negExtraIter != negExtraPars.end(); ++negExtraIter) { LauParameter negExtraParameter = (*negExtraIter); extraVars.push_back(negExtraParameter); } std::vector posExtraPars = posSigModel_->getExtraParameters(); std::vector::iterator posExtraIter; for (posExtraIter = posExtraPars.begin(); posExtraIter != posExtraPars.end(); ++posExtraIter) { LauParameter posExtraParameter = (*posExtraIter); extraVars.push_back(posExtraParameter); } // Now add in the DP efficiency value Double_t initMeanEff = negSigModel_->getMeanEff().initValue(); negMeanEff_.value(initMeanEff); negMeanEff_.genValue(initMeanEff); negMeanEff_.initValue(initMeanEff); extraVars.push_back(negMeanEff_); initMeanEff = posSigModel_->getMeanEff().initValue(); posMeanEff_.value(initMeanEff); posMeanEff_.genValue(initMeanEff); posMeanEff_.initValue(initMeanEff); extraVars.push_back(posMeanEff_); // Also add in the DP rates Double_t initDPRate = negSigModel_->getDPRate().initValue(); negDPRate_.value(initDPRate); negDPRate_.genValue(initDPRate); negDPRate_.initValue(initDPRate); extraVars.push_back(negDPRate_); initDPRate = posSigModel_->getDPRate().initValue(); posDPRate_.value(initDPRate); posDPRate_.genValue(initDPRate); posDPRate_.initValue(initDPRate); extraVars.push_back(posDPRate_); // Calculate the CPC and CPV Fit Fractions, ACPs and FitFrac asymmetries this->calcExtraFractions(kTRUE); this->calcAsymmetries(kTRUE); // Add the CP violating and CP conserving fit fractions for each signal component for (UInt_t i = 0; i < nSigComp_; i++) { for (UInt_t j = i; j < nSigComp_; j++) { extraVars.push_back(CPVFitFrac_[i][j]); } } for (UInt_t i = 0; i < nSigComp_; i++) { for (UInt_t j = i; j < nSigComp_; j++) { extraVars.push_back(CPCFitFrac_[i][j]); } } // 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]); } } void LauBsCPFitModel::calcExtraFractions(Bool_t initValues) { // Calculate the CP-conserving and CP-violating fit fractions if (initValues) { // create the structure CPCFitFrac_.clear(); CPVFitFrac_.clear(); CPCFitFrac_.resize(nSigComp_); CPVFitFrac_.resize(nSigComp_); for (UInt_t i(0); iacp(); LauAsymmCalc asymmCalc(negFitFrac_[i][i].value(), posFitFrac_[i][i].value()); Double_t asym = asymmCalc.getAsymmetry(); fitFracAsymm_[i].value(asym); if (initValues) { fitFracAsymm_[i].genValue(asym); fitFracAsymm_[i].initValue(asym); } } } void LauBsCPFitModel::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/b > 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 (useSCF_ && !useSCFHist_) { scfFrac_.updatePull(); } if (usingBkgnd_ == kTRUE) { for (LauBkgndYieldList::iterator iter = bkgndEvents_.begin(); iter != bkgndEvents_.end(); ++iter) { std::vector parameters = (*iter)->getPars(); for ( LauParameter* parameter : parameters ) { parameter->updatePull(); } } } // Update the pulls on all the extra PDFs' parameters this->updateFitParameters(signalPdfs_); if (useSCF_ == kTRUE) { this->updateFitParameters(scfPdfs_); } if (usingBkgnd_ == kTRUE) { for (LauBkgndPdfsList::iterator iter = bkgndPdfs_.begin(); iter != bkgndPdfs_.end(); ++iter) { this->updateFitParameters(*iter); } } // 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(); negSigModel_->updateCoeffs(negCoeffs_); negSigModel_->calcExtraInfo(); posSigModel_->updateCoeffs(posCoeffs_); posSigModel_->calcExtraInfo(); LauParArray negFitFrac = negSigModel_->getFitFractions(); if (negFitFrac.size() != nSigComp_) { std::cerr << "ERROR in LauBsCPFitModel::finaliseFitResults : Fit Fraction array of unexpected dimension: " << negFitFrac.size() << std::endl; gSystem->Exit(EXIT_FAILURE); } for (UInt_t i(0); iExit(EXIT_FAILURE); } } LauParArray posFitFrac = posSigModel_->getFitFractions(); if (posFitFrac.size() != nSigComp_) { std::cerr << "ERROR in LauBsCPFitModel::finaliseFitResults : Fit Fraction array of unexpected dimension: " << posFitFrac.size() << std::endl; gSystem->Exit(EXIT_FAILURE); } for (UInt_t i(0); iExit(EXIT_FAILURE); } } LauParArray negFitFracEffUnCorr = negSigModel_->getFitFractionsEfficiencyUncorrected(); if (negFitFracEffUnCorr.size() != nSigComp_) { std::cerr << "ERROR in LauBsCPFitModel::finaliseFitResults : Fit Fraction array of unexpected dimension: " << negFitFracEffUnCorr.size() << std::endl; gSystem->Exit(EXIT_FAILURE); } for (UInt_t i(0); iExit(EXIT_FAILURE); } } LauParArray posFitFracEffUnCorr = posSigModel_->getFitFractionsEfficiencyUncorrected(); if (posFitFracEffUnCorr.size() != nSigComp_) { std::cerr << "ERROR in LauBsCPFitModel::finaliseFitResults : Fit Fraction array of unexpected dimension: " << posFitFracEffUnCorr.size() << std::endl; gSystem->Exit(EXIT_FAILURE); } for (UInt_t i(0); iExit(EXIT_FAILURE); } } for (UInt_t i(0); igetMeanEff().value()); posMeanEff_.value(posSigModel_->getMeanEff().value()); negDPRate_.value(negSigModel_->getDPRate().value()); posDPRate_.value(posSigModel_->getDPRate().value()); this->calcExtraFractions(); 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(); // Add the positive and negative fit fractions for each signal component for (UInt_t i(0); i negExtraPars = negSigModel_->getExtraParameters(); std::vector::iterator negExtraIter; for (negExtraIter = negExtraPars.begin(); negExtraIter != negExtraPars.end(); ++negExtraIter) { LauParameter negExtraParameter = (*negExtraIter); extraVars.push_back(negExtraParameter); } std::vector posExtraPars = posSigModel_->getExtraParameters(); std::vector::iterator posExtraIter; for (posExtraIter = posExtraPars.begin(); posExtraIter != posExtraPars.end(); ++posExtraIter) { LauParameter posExtraParameter = (*posExtraIter); extraVars.push_back(posExtraParameter); } extraVars.push_back(negMeanEff_); extraVars.push_back(posMeanEff_); extraVars.push_back(negDPRate_); extraVars.push_back(posDPRate_); for (UInt_t i = 0; i < nSigComp_; i++) { for (UInt_t j(i); jprintFitFractions(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 LauBsCPFitModel::printFitFractions(std::ostream& output) { // Print out Fit Fractions, total DP rate and mean efficiency // First for the B- events for (UInt_t i = 0; i < nSigComp_; i++) { const TString compName(coeffPars_[i]->name()); - output << negParent_ << " FitFraction for component " << i << " (" << compName << ") = " << negFitFrac_[i][i] << std::endl; + output << negParent_ << " FitFraction for component " << i << " (" << compName << ") = " << negFitFrac_[i][i].value() << std::endl; } - output << negParent_ << " overall DP rate (integral of matrix element squared) = " << negDPRate_ << std::endl; - output << negParent_ << " average efficiency weighted by whole DP dynamics = " << negMeanEff_ << std::endl; + output << negParent_ << " overall DP rate (integral of matrix element squared) = " << negDPRate_.value() << std::endl; + output << negParent_ << " average efficiency weighted by whole DP dynamics = " << negMeanEff_.value() << std::endl; // Then for the positive sample for (UInt_t i = 0; i < nSigComp_; i++) { const TString compName(coeffPars_[i]->name()); //const TString conjName(negSigModel_->getConjResName(compName)); - output << posParent_ << " FitFraction for component " << i << " (" << compName << ") = " << posFitFrac_[i][i] << std::endl; + output << posParent_ << " FitFraction for component " << i << " (" << compName << ") = " << posFitFrac_[i][i].value() << std::endl; } - output << posParent_ << " overall DP rate (integral of matrix element squared) = " << posDPRate_ << std::endl; - output << posParent_ << " average efficiency weighted by whole DP dynamics = " << posMeanEff_ << std::endl; + output << posParent_ << " overall DP rate (integral of matrix element squared) = " << posDPRate_.value() << std::endl; + output << posParent_ << " average efficiency weighted by whole DP dynamics = " << posMeanEff_.value() << std::endl; } void LauBsCPFitModel::printAsymmetries(std::ostream& output) { for (UInt_t i = 0; i < nSigComp_; i++) { const TString compName(coeffPars_[i]->name()); - output << "Fit Fraction asymmetry for component " << i << " (" << compName << ") = " << fitFracAsymm_[i] << std::endl; + output << "Fit Fraction asymmetry for component " << i << " (" << compName << ") = " << fitFracAsymm_[i].value() << std::endl; } for (UInt_t i = 0; i < nSigComp_; i++) { const TString compName(coeffPars_[i]->name()); - output << "ACP for component " << i << " (" << compName << ") = " << acp_[i] << std::endl; + output << "ACP for component " << i << " (" << compName << ") = " << acp_[i].value() << std::endl; } } void LauBsCPFitModel::writeOutTable(const TString& outputFile) { // Write out the results of the fit to a tex-readable table // TODO - need to include the yields in this table std::ofstream fout(outputFile); LauPrint print; std::cout << "INFO in LauBsCPFitModel::writeOutTable : Writing out results of the fit to the tex file " << outputFile << std::endl; if (this->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" << std::endl; fout << "\\end{tabular}" << std::endl << std::endl; // print the fit fractions and asymmetries in another fout << "\\begin{tabular}{|l|c|c|c|c|}" << std::endl; fout << "\\hline" << std::endl; fout << "Component & " << negParent_ << " Fit Fraction & " << posParent_ << " Fit Fraction & Fit Fraction Asymmetry & ACP \\\\" << std::endl; fout << "\\hline" << std::endl; Double_t negFitFracSum(0.0); Double_t posFitFracSum(0.0); for (UInt_t i = 0; i < nSigComp_; i++) { TString resName = coeffPars_[i]->name(); resName = resName.ReplaceAll("_", "\\_"); Double_t negFitFrac = negFitFrac_[i][i].value(); Double_t posFitFrac = posFitFrac_[i][i].value(); negFitFracSum += negFitFrac; posFitFracSum += posFitFrac; Double_t fitFracAsymm = fitFracAsymm_[i].value(); Double_t acp = acp_[i].value(); Double_t acpErr = acp_[i].error(); fout << resName << " & $"; print.printFormat(fout, negFitFrac); fout << "$ & $"; print.printFormat(fout, posFitFrac); fout << "$ & $"; print.printFormat(fout, fitFracAsymm); fout << "$ & $"; print.printFormat(fout, acp); fout << " \\pm "; print.printFormat(fout, acpErr); fout << "$ \\\\" << std::endl; } fout << "\\hline" << std::endl; // Also print out sum of fit fractions fout << "Fit Fraction Sum & $"; print.printFormat(fout, negFitFracSum); fout << "$ & $"; print.printFormat(fout, posFitFracSum); fout << "$ & & \\\\" << std::endl; fout << "\\hline" << std::endl; fout << "DP rate & $"; print.printFormat(fout, negDPRate_.value()); fout << "$ & $"; print.printFormat(fout, posDPRate_.value()); fout << "$ & & \\\\" << std::endl; fout << "$< \\varepsilon > $ & $"; print.printFormat(fout, negMeanEff_.value()); fout << "$ & $"; print.printFormat(fout, posMeanEff_.value()); fout << "$ & & \\\\" << std::endl; fout << "\\hline" << std::endl; fout << "\\end{tabular}" << std::endl << std::endl; } if (!signalPdfs_.empty()) { fout << "\\begin{tabular}{|l|c|}" << std::endl; fout << "\\hline" << std::endl; if (useSCF_ == kTRUE) { fout << "\\Extra TM Signal PDFs' Parameters: & \\\\" << std::endl; } else { fout << "\\Extra Signal PDFs' Parameters: & \\\\" << std::endl; } this->printFitParameters(signalPdfs_, fout); if (useSCF_ == kTRUE && !scfPdfs_.empty()) { fout << "\\hline" << std::endl; fout << "\\Extra SCF Signal PDFs' Parameters: & \\\\" << std::endl; this->printFitParameters(scfPdfs_, fout); } if (usingBkgnd_ == kTRUE && !bkgndPdfs_.empty()) { fout << "\\hline" << std::endl; fout << "\\Extra Background PDFs' Parameters: & \\\\" << std::endl; for (LauBkgndPdfsList::const_iterator iter = bkgndPdfs_.begin(); iter != bkgndPdfs_.end(); ++iter) { this->printFitParameters(*iter, fout); } } fout << "\\hline \n\\end{tabular}" << std::endl << std::endl; } } void LauBsCPFitModel::checkInitFitParams() { // Update the number of signal events to be total-sum(background events) this->updateSigEvents(); // Check whether we want to have randomised initial fit parameters for the signal model if (this->useRandomInitFitPars() == kTRUE) { std::cout << "INFO in LauBsCPFitModel::checkInitFitParams : Setting random parameters for the signal model" << std::endl; this->randomiseInitFitPars(); } } void LauBsCPFitModel::randomiseInitFitPars() { // Only randomise those parameters that are not fixed! std::cout << "INFO in LauBsCPFitModel::randomiseInitFitPars : Randomising the initial fit magnitudes and phases of the components..." << std::endl; for (UInt_t i = 0; i < nSigComp_; i++) { coeffPars_[i]->randomiseInitValues(); } } LauBsCPFitModel::LauGenInfo LauBsCPFitModel::eventsToGenerate() { // Determine the number of events to generate for each hypothesis // If we're smearing then smear each one individually LauGenInfo nEvtsGen; // Keep track of whether any yield or asymmetry parameters are blinded Bool_t blind = kFALSE; // Signal Double_t evtWeight(1.0); Double_t nEvts = signalEvents_->genValue(); if ( nEvts < 0.0 ) { evtWeight = -1.0; nEvts = TMath::Abs( nEvts ); } if ( signalEvents_->blind() ) { blind = kTRUE; } Double_t asym(0.0); Double_t sigAsym(0.0); Double_t negRate = negSigModel_->getDPNorm(); Double_t posRate = posSigModel_->getDPNorm(); if (negRate+posRate>1e-30) { sigAsym = (negRate-posRate)/(negRate+posRate); } asym = sigAsym; Int_t nPosEvts = static_cast((nEvts/2.0 * (1.0 - asym)) + 0.5); Int_t nNegEvts = static_cast((nEvts/2.0 * (1.0 + asym)) + 0.5); if (this->doPoissonSmearing()) { nNegEvts = LauRandom::randomFun()->Poisson(nNegEvts); nPosEvts = LauRandom::randomFun()->Poisson(nPosEvts); } nEvtsGen[std::make_pair("signal",-1)] = std::make_pair(nNegEvts,evtWeight); nEvtsGen[std::make_pair("signal",+1)] = std::make_pair(nPosEvts,evtWeight); // backgrounds const UInt_t nBkgnds = this->nBkgndClasses(); for ( UInt_t bkgndID(0); bkgndID < nBkgnds; ++bkgndID ) { const TString& bkgndClass = this->bkgndClassName(bkgndID); const LauAbsRValue* evtsPar = bkgndEvents_[bkgndID]; if ( evtsPar->blind() ) { blind = kTRUE; } evtWeight = 1.0; nEvts = TMath::FloorNint( evtsPar->genValue() ); if ( nEvts < 0 ) { evtWeight = -1.0; nEvts = TMath::Abs( nEvts ); } Int_t nBkgEvts = nEvts; if (this->doPoissonSmearing()) { nBkgEvts = LauRandom::randomFun()->Poisson(nBkgEvts); } nEvtsGen[std::make_pair(bkgndClass,+1)] = std::make_pair(nBkgEvts,evtWeight); } // Print out the information on what we're generating, but only if none of the parameters are blind (otherwise we risk unblinding them!) if ( !blind ) { std::cout << "INFO in LauBsCPFitModel::eventsToGenerate : Generating toy MC with:" << std::endl; std::cout << " : Signal asymmetry = " << sigAsym << " and number of signal events = " << signalEvents_->genValue() << std::endl; for ( UInt_t bkgndID(0); bkgndID < nBkgnds; ++bkgndID ) { const TString& bkgndClass = this->bkgndClassName(bkgndID); const LauAbsRValue* evtsPar = bkgndEvents_[bkgndID]; std::cout << " : Number of " << bkgndClass << " events = " << evtsPar->genValue() << std::endl; } } return nEvtsGen; } Bool_t LauBsCPFitModel::genExpt() { // Routine to generate toy Monte Carlo events according to the various models we have defined. // Determine the number of events to generate for each hypothesis LauGenInfo nEvts = this->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; } const Bool_t storeSCFTruthInfo = useSCF_; // Loop over the hypotheses and generate the requested number of events for each one for (LauGenInfo::const_iterator iter = nEvts.begin(); iter != nEvts.end(); ++iter) { const TString& type(iter->first.first); Double_t evtWeight( iter->second.second ); Int_t nEvtsGen( iter->second.first ); for (Int_t iEvt(0); iEvtsetGenNtupleDoubleBranchValue( "evtWeight", evtWeight ); this->setGenNtupleDoubleBranchValue( "efficiency", 1.0 ); if (type == "signal") { this->setGenNtupleIntegerBranchValue("genSig",1); for ( UInt_t iBkgnd(0); iBkgnd < nBkgnds; ++iBkgnd ) { this->setGenNtupleIntegerBranchValue( bkgndClassNamesGen[iBkgnd], 0 ); } genOK = this->generateSignalEvent(); this->setGenNtupleDoubleBranchValue( "efficiency", negSigModel_->getEvtEff() ); } else { this->setGenNtupleIntegerBranchValue("genSig",0); if ( storeSCFTruthInfo ) { this->setGenNtupleIntegerBranchValue("genTMSig",0); this->setGenNtupleIntegerBranchValue("genSCFSig",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->setDPBranchValues(); } // Store the event number (within this experiment) // and then increment it this->setGenNtupleIntegerBranchValue("iEvtWithinExpt",evtNum); ++evtNum; this->fillGenNtupleBranches(); if (iEvt%500 == 0) {std::cout << "INFO in LauBsCPFitModel::genExpt : Generated event number " << iEvt << " out of " << nEvtsGen << " " << type << " events." << std::endl;} } if (!genOK) { break; } } if (this->useDP() && genOK) { negSigModel_->checkToyMC(kTRUE,kTRUE); posSigModel_->checkToyMC(kTRUE,kTRUE); // Get the fit fractions if they're to be written into the latex table if (this->writeLatexTable()) { LauParArray negFitFrac = negSigModel_->getFitFractions(); if (negFitFrac.size() != nSigComp_) { std::cerr << "ERROR in LauBsCPFitModel::genExpt : Fit Fraction array of unexpected dimension: " << negFitFrac.size() << std::endl; gSystem->Exit(EXIT_FAILURE); } for (UInt_t i(0); iExit(EXIT_FAILURE); } } LauParArray posFitFrac = posSigModel_->getFitFractions(); if (posFitFrac.size() != nSigComp_) { std::cerr << "ERROR in LauBsCPFitModel::genExpt : Fit Fraction array of unexpected dimension: " << posFitFrac.size() << std::endl; gSystem->Exit(EXIT_FAILURE); } for (UInt_t i(0); iExit(EXIT_FAILURE); } } for (UInt_t i(0); igetMeanEff().value()); posMeanEff_.value(posSigModel_->getMeanEff().value()); negDPRate_.value(negSigModel_->getDPRate().value()); posDPRate_.value(posSigModel_->getDPRate().value()); } } return genOK; } Bool_t LauBsCPFitModel::generateSignalEvent() { // Generate signal event Bool_t genOK(kTRUE); Bool_t genSCF(kFALSE); Bool_t generatedEvent(kFALSE); //LauPdfPList* sigPdfs(0); //LauPdfPList* scfPdfs(0); if (this->useDP()) { nGenLoop_ = 0; while (generatedEvent == kFALSE && nGenLoop_ < iterationsMax_) { // DP variables Double_t m13Sq(0.0), m23Sq(0.0); // Generate DP position negKinematics_->genFlatPhaseSpace(m13Sq, m23Sq); posKinematics_->updateKinematics(m13Sq, m23Sq); // Calculate the total A and Abar for the given DP position negSigModel_->calcLikelihoodInfo(m13Sq, m23Sq); posSigModel_->calcLikelihoodInfo(m13Sq, m23Sq); // Calculate DP terms this->calculateDPterms(); //Finally we throw the dice to see whether this event should be generated Double_t randNo = LauRandom::randomFun()->Rndm(); if (randNo <= ASq_/aSqMaxSet_ ) { generatedEvent = kTRUE; nGenLoop_ = 0; if (ASq_ > aSqMaxVar_) {aSqMaxVar_ = ASq_;} } else { nGenLoop_++; } } // Check whether we have generated the toy MC OK. if (nGenLoop_ >= iterationsMax_) { aSqMaxSet_ = 1.01 * aSqMaxVar_; genOK = kFALSE; std::cerr<<"WARNING in LauTimeDepNonFlavModel::generateSignalEvent : Hit max iterations: setting aSqMaxSet_ to "< aSqMaxSet_) { aSqMaxSet_ = 1.01 * aSqMaxVar_; genOK = kFALSE; std::cerr<<"WARNING in LauTimeDepNonFlavModel::generateSignalEvent : Found a larger ASq value: setting aSqMaxSet_ to "<calcEfficiency( negKinematics_ ); } else { frac = scfFrac_.genValue(); } if ( frac < LauRandom::randomFun()->Rndm() ) { this->setGenNtupleIntegerBranchValue("genTMSig",1); this->setGenNtupleIntegerBranchValue("genSCFSig",0); genSCF = kFALSE; } else { this->setGenNtupleIntegerBranchValue("genTMSig",0); this->setGenNtupleIntegerBranchValue("genSCFSig",1); genSCF = kTRUE; // Optionally smear the DP position // of the SCF event if ( scfMap_ != 0 ) { Double_t xCoord(0.0), yCoord(0.0); if ( negKinematics_->squareDP() ) { xCoord = negKinematics_->getmPrime(); yCoord = negKinematics_->getThetaPrime(); } else { xCoord = negKinematics_->getm13Sq(); yCoord = negKinematics_->getm23Sq(); } // Find the bin number where this event is generated Int_t binNo = scfMap_->binNumber( xCoord, yCoord ); // Retrieve the migration histogram TH2* histo = scfMap_->trueHist( binNo ); const LauAbsEffModel * effModel = negSigModel_->getEffModel(); do { // Get a random point from the histogram histo->GetRandom2( xCoord, yCoord ); // Update the kinematics if ( negKinematics_->squareDP() ) { negKinematics_->updateSqDPKinematics( xCoord, yCoord ); } else { negKinematics_->updateKinematics( xCoord, yCoord ); } } while ( ! effModel->passVeto( negKinematics_ ) ); } } } } else { if ( useSCF_ ) { Double_t frac = scfFrac_.genValue(); if ( frac < LauRandom::randomFun()->Rndm() ) { this->setGenNtupleIntegerBranchValue("genTMSig",1); this->setGenNtupleIntegerBranchValue("genSCFSig",0); genSCF = kFALSE; } else { this->setGenNtupleIntegerBranchValue("genTMSig",0); this->setGenNtupleIntegerBranchValue("genSCFSig",1); genSCF = kTRUE; } } } if (genOK) { // TODO! Check if the removal is right //sigPdfs = &signalPdfs_; //scfPdfs = &scfPdfs_; if ( useSCF_ ) { if ( genSCF ) { this->generateExtraPdfValues(&scfPdfs_); } else { this->generateExtraPdfValues(&signalPdfs_); } } else { this->generateExtraPdfValues(&signalPdfs_); } } return genOK; } void LauBsCPFitModel::calculateDPterms() { // Retrieve the amplitudes and efficiency from the dynamics const LauComplex& Abar = negSigModel_->getEvtDPAmp(); const LauComplex& A = posSigModel_->getEvtDPAmp(); Double_t eff = negSigModel_->getEvtEff(); // Calculate the DP terms Double_t aSqSum = A.abs2() + Abar.abs2(); LauComplex inter = Abar * A.conj(); Double_t interTermRe = inter.re(); // Total amplitude and multiply by the efficiency ASq_ = aSqSum - 2.0 * D_ * interTermRe; ASq_ *= eff; } Bool_t LauBsCPFitModel::generateBkgndEvent(UInt_t bkgndID) { // Generate Bkgnd event Bool_t genOK(kTRUE); LauAbsBkgndDPModel* model(0); LauPdfPList* extraPdfs(0); //LauKinematics* kinematics(0); // TODO: Check charge again /* if (curEvtCharge_<0) { model = negBkgndDPModels_[bkgndID]; if (this->enableEmbedding()) { embeddedData = negBkgndTree_[bkgndID]; } extraPdfs = &negBkgndPdfs_[bkgndID]; kinematics = negKinematics_; } else { model = posBkgndDPModels_[bkgndID]; if (this->enableEmbedding()) { embeddedData = posBkgndTree_[bkgndID]; } if ( tagged_ ) { extraPdfs = &posBkgndPdfs_[bkgndID]; } else { extraPdfs = &negBkgndPdfs_[bkgndID]; } kinematics = posKinematics_; } */ model = bkgndDPModels_[bkgndID]; //if (this->enableEmbedding()) { // embeddedData = bkgndTree_[bkgndID]; //} extraPdfs = &bkgndPdfs_[bkgndID]; //kinematics = negKinematics_; // Finishing here if (this->useDP()) { // TODO! Check! /*if (embeddedData) { embeddedData->getEmbeddedEvent(kinematics); } else {*/ if (model == 0) { const TString& bkgndClass = this->bkgndClassName(bkgndID); std::cerr << "ERROR in LauBsCPFitModel::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); } return genOK; } void LauBsCPFitModel::setupGenNtupleBranches() { // Setup the required ntuple branches this->addGenNtupleDoubleBranch("evtWeight"); this->addGenNtupleIntegerBranch("genSig"); this->addGenNtupleDoubleBranch("efficiency"); if ( useSCF_ ) { this->addGenNtupleIntegerBranch("genTMSig"); this->addGenNtupleIntegerBranch("genSCFSig"); } const UInt_t nBkgnds = this->nBkgndClasses(); for ( UInt_t iBkgnd(0); iBkgnd < nBkgnds; ++iBkgnd ) { TString name( this->bkgndClassName(iBkgnd) ); name.Prepend("gen"); this->addGenNtupleIntegerBranch(name); } if (this->useDP() == kTRUE) { 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 (negKinematics_->squareDP() && posKinematics_->squareDP()) { this->addGenNtupleDoubleBranch("mPrime"); this->addGenNtupleDoubleBranch("thPrime"); } } for (LauPdfPList::const_iterator pdf_iter = signalPdfs_.begin(); pdf_iter != signalPdfs_.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" ) { this->addGenNtupleDoubleBranch( (*var_iter) ); } } } } void LauBsCPFitModel::setDPBranchValues() { // Store all the DP information this->setGenNtupleDoubleBranchValue("m12", negKinematics_->getm12()); this->setGenNtupleDoubleBranchValue("m23", negKinematics_->getm23()); this->setGenNtupleDoubleBranchValue("m13", negKinematics_->getm13()); this->setGenNtupleDoubleBranchValue("m12Sq", negKinematics_->getm12Sq()); this->setGenNtupleDoubleBranchValue("m23Sq", negKinematics_->getm23Sq()); this->setGenNtupleDoubleBranchValue("m13Sq", negKinematics_->getm13Sq()); this->setGenNtupleDoubleBranchValue("cosHel12", negKinematics_->getc12()); this->setGenNtupleDoubleBranchValue("cosHel23", negKinematics_->getc23()); this->setGenNtupleDoubleBranchValue("cosHel13", negKinematics_->getc13()); if (negKinematics_->squareDP()) { this->setGenNtupleDoubleBranchValue("mPrime", negKinematics_->getmPrime()); this->setGenNtupleDoubleBranchValue("thPrime", negKinematics_->getThetaPrime()); } } void LauBsCPFitModel::generateExtraPdfValues(LauPdfPList* extraPdfs) { if (!extraPdfs) { std::cerr << "ERROR in LauBsCPFitModel::generateExtraPdfValues : Null pointer to PDF list." << std::endl; gSystem->Exit(EXIT_FAILURE); } if (extraPdfs->empty()) { //std::cerr << "WARNING in LauBsCPFitModel::generateExtraPdfValues : PDF list is empty." << std::endl; return; } // Generate from the extra PDFs for (LauPdfPList::iterator pdf_iter = extraPdfs->begin(); pdf_iter != extraPdfs->end(); ++pdf_iter) { LauFitData genValues; genValues = (*pdf_iter)->generate(negKinematics_); for ( LauFitData::const_iterator var_iter = genValues.begin(); var_iter != genValues.end(); ++var_iter ) { TString varName = var_iter->first; if ( varName != "m13Sq" && varName != "m23Sq" ) { Double_t value = var_iter->second; this->setGenNtupleDoubleBranchValue(varName,value); } } } } void LauBsCPFitModel::propagateParUpdates() { // Update the signal parameters and then the total normalisation for the signal likelihood if (this->useDP() == kTRUE) { this->updateCoeffs(); negSigModel_->updateCoeffs(negCoeffs_); posSigModel_->updateCoeffs(posCoeffs_); this->calcInterTermNorm(); this->calculateAmplitudeNorm(); } // Update the signal fraction from the background fractions if not doing an extended fit if ( !this->doEMLFit() && !signalEvents_->fixed() ) { this->updateSigEvents(); } } void LauBsCPFitModel::updateSigEvents() { // The background parameters will have been set from Minuit. // We need to update the signal events using these. Double_t nTotEvts = this->eventsPerExpt(); signalEvents_->range(-2.0*nTotEvts,2.0*nTotEvts); for (LauBkgndYieldList::iterator iter = bkgndEvents_.begin(); iter != bkgndEvents_.end(); ++iter) { LauAbsRValue* nBkgndEvents = (*iter); if ( nBkgndEvents->isLValue() ) { LauParameter* yield = dynamic_cast( nBkgndEvents ); yield->range(-2.0*nTotEvts,2.0*nTotEvts); } } if (signalEvents_->fixed()) { return; } // Subtract background events (if any) from signal. Double_t signalEvents = nTotEvts; if (usingBkgnd_ == kTRUE) { for (LauBkgndYieldList::const_iterator iter = bkgndEvents_.begin(); iter != bkgndEvents_.end(); ++iter) { signalEvents -= (*iter)->value(); } } signalEvents_->value(signalEvents); } void LauBsCPFitModel::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(); // First the Dalitz plot variables (m_ij^2) if (this->useDP() == kTRUE) { // need to append SCF smearing bins before caching DP amplitudes if ( scfMap_ != 0 ) { this->appendBinCentres( inputFitData ); } negSigModel_->fillDataTree(*inputFitData); posSigModel_->fillDataTree(*inputFitData); if (usingBkgnd_ == kTRUE) { for (LauBkgndDPModelList::iterator iter = bkgndDPModels_.begin(); iter != bkgndDPModels_.end(); ++iter) { (*iter)->fillDataTree(*inputFitData); } } } // ...and then the extra PDFs this->cacheInfo(signalPdfs_, *inputFitData); this->cacheInfo(scfPdfs_, *inputFitData); for (LauBkgndPdfsList::iterator iter = bkgndPdfs_.begin(); iter != bkgndPdfs_.end(); ++iter) { this->cacheInfo((*iter), *inputFitData); } // the SCF fractions and jacobians if ( useSCF_ && useSCFHist_ ) { if ( !inputFitData->haveBranch( "m13Sq" ) || !inputFitData->haveBranch( "m23Sq" ) ) { std::cerr << "ERROR in LauBsCPFitModel::cacheInputFitVars : Input data does not contain DP branches and so can't cache the SCF fraction." << std::endl; gSystem->Exit(EXIT_FAILURE); } UInt_t nEvents = inputFitData->nEvents(); recoSCFFracs_.clear(); recoSCFFracs_.reserve( nEvents ); if ( negKinematics_->squareDP() ) { recoJacobians_.clear(); recoJacobians_.reserve( nEvents ); } for (UInt_t iEvt = 0; iEvt < nEvents; iEvt++) { const LauFitData& dataValues = inputFitData->getData(iEvt); LauFitData::const_iterator m13_iter = dataValues.find("m13Sq"); LauFitData::const_iterator m23_iter = dataValues.find("m23Sq"); negKinematics_->updateKinematics( m13_iter->second, m23_iter->second ); Double_t scfFrac = scfFracHist_->calcEfficiency( negKinematics_ ); recoSCFFracs_.push_back( scfFrac ); if ( negKinematics_->squareDP() ) { recoJacobians_.push_back( negKinematics_->calcSqDPJacobian() ); } } } } void LauBsCPFitModel::appendBinCentres( LauFitDataTree* inputData ) { // We'll be caching the DP amplitudes and efficiencies of the centres of the true bins. // To do so, we attach some fake points at the end of inputData, the number of the entry // minus the total number of events corresponding to the number of the histogram for that // given true bin in the LauScfMap object. (What this means is that when Laura is provided with // the LauScfMap object by the user, it's the latter who has to make sure that it contains the // right number of histograms and in exactly the right order!) // Get the x and y co-ordinates of the bin centres std::vector binCentresXCoords; std::vector binCentresYCoords; scfMap_->listBinCentres(binCentresXCoords, binCentresYCoords); // The SCF histograms could be in square Dalitz plot histograms. // The dynamics takes normal Dalitz plot coords, so we might have to convert them back. Bool_t sqDP = negKinematics_->squareDP(); UInt_t nBins = binCentresXCoords.size(); fakeSCFFracs_.clear(); fakeSCFFracs_.reserve( nBins ); if ( sqDP ) { fakeJacobians_.clear(); fakeJacobians_.reserve( nBins ); } for (UInt_t iBin = 0; iBin < nBins; ++iBin) { if ( sqDP ) { negKinematics_->updateSqDPKinematics(binCentresXCoords[iBin],binCentresYCoords[iBin]); binCentresXCoords[iBin] = negKinematics_->getm13Sq(); binCentresYCoords[iBin] = negKinematics_->getm23Sq(); fakeJacobians_.push_back( negKinematics_->calcSqDPJacobian() ); } else { negKinematics_->updateKinematics(binCentresXCoords[iBin],binCentresYCoords[iBin]); } fakeSCFFracs_.push_back( scfFracHist_->calcEfficiency( negKinematics_ ) ); } // Set up inputFitVars_ object to hold the fake events inputData->appendFakePoints(binCentresXCoords,binCentresYCoords); } Double_t LauBsCPFitModel::getTotEvtLikelihood(UInt_t iEvt) { // Find out whether we have B- or B+ // Get the DP likelihood for signal and backgrounds this->getEvtDPLikelihood(iEvt); // Get the combined extra PDFs likelihood for signal and backgrounds this->getEvtExtraLikelihoods(iEvt); // If appropriate, combine the TM and SCF likelihoods Double_t sigLike = sigDPLike_ * sigExtraLike_; if ( useSCF_ ) { Double_t scfFrac(0.0); if (useSCFHist_) { scfFrac = recoSCFFracs_[iEvt]; } else { scfFrac = scfFrac_.unblindValue(); } sigLike *= (1.0 - scfFrac); if ( (scfMap_ != 0) && (this->useDP() == kTRUE) ) { // if we're smearing the SCF DP PDF then the SCF frac // is already included in the SCF DP likelihood sigLike += (scfDPLike_ * scfExtraLike_); } else { sigLike += (scfFrac * scfDPLike_ * scfExtraLike_); } } // Signal asymmetry is built into the DP model... Double_t signalEvents = signalEvents_->unblindValue(); // Construct the total event likelihood Double_t likelihood(0.0); if (usingBkgnd_) { likelihood = sigLike*signalEvents; const UInt_t nBkgnds = this->nBkgndClasses(); for ( UInt_t bkgndID(0); bkgndID < nBkgnds; ++bkgndID ) { Double_t bkgndEvents = bkgndEvents_[bkgndID]->unblindValue(); likelihood += bkgndEvents*bkgndDPLike_[bkgndID]*bkgndExtraLike_[bkgndID]; } } else { // TODO: receives this 1/2 term? //likelihood = sigLike*0.5; likelihood = sigLike; } return likelihood; } Double_t LauBsCPFitModel::getEventSum() const { Double_t eventSum(0.0); eventSum += signalEvents_->unblindValue(); if (usingBkgnd_) { for (LauBkgndYieldList::const_iterator iter = bkgndEvents_.begin(); iter != bkgndEvents_.end(); ++iter) { eventSum += (*iter)->unblindValue(); } } return eventSum; } void LauBsCPFitModel::getEvtDPLikelihood(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; scfDPLike_ = 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; } const UInt_t nBkgnds = this->nBkgndClasses(); // Completely revised posSigModel_->calcLikelihoodInfo(iEvt); negSigModel_->calcLikelihoodInfo(iEvt); this->calculateDPterms(); sigDPLike_ = ASq_; for ( UInt_t bkgndID(0); bkgndID < nBkgnds; ++bkgndID ) { if (usingBkgnd_ == kTRUE) { bkgndDPLike_[bkgndID] = bkgndDPModels_[bkgndID]->getLikelihood(iEvt); } else { bkgndDPLike_[bkgndID] = 0.0; } } if ( useSCF_ == kTRUE ) { if ( scfMap_ == 0 ) { // we're not smearing the SCF DP position // so the likelihood is the same as the TM scfDPLike_ = sigDPLike_; } else { // calculate the smeared SCF DP likelihood scfDPLike_ = this->getEvtSCFDPLikelihood(iEvt); } } // Calculate the signal normalisation // NB the 2.0 is there so that the 0.5 factor is applied to // signal and background in the same place otherwise you get // normalisation problems when you switch off the DP in the fit // TODO: need to fix this sigDPLike_ *= 1.0/normDP_; scfDPLike_ *= 1.0/normDP_; } void LauBsCPFitModel::calculateAmplitudeNorm() { // Integrals of the sum of the ampltudes to the f(fbar) integral( |A|^2 + |Abar|^2 ) dP Double_t normASq = posSigModel_->getDPNorm(); Double_t normAbarSq = negSigModel_->getDPNorm(); // Integrals of cross terms Abar*Aconj Double_t normInterTerm = interTermReNorm_; // Complete DP normalisation terms normDP_ = normASq + normAbarSq - 2.0 * D_ * normInterTerm; } void LauBsCPFitModel::calcInterTermNorm() { const std::vector fNormB0 = posSigModel_->getFNorm(); const std::vector fNormB0bar = negSigModel_->getFNorm(); // TODO - compare this implementation with that of LauIsobarDynamics::calcSigDPNorm LauComplex norm; for (UInt_t iAmp = 0; iAmp < nSigComp_; ++iAmp) { for (UInt_t jAmp = 0; jAmp < nSigComp_; ++jAmp) { LauComplex coeffTerm = negCoeffs_[jAmp]*posCoeffs_[iAmp].conj(); coeffTerm *= fifjEffSum_[iAmp][jAmp]; coeffTerm.rescale(fNormB0bar[jAmp] * fNormB0[iAmp]); norm += coeffTerm; } } interTermReNorm_ = norm.re(); //interTermImNorm_f_ = norm_f.im(); } Double_t LauBsCPFitModel::getEvtSCFDPLikelihood(UInt_t iEvt) { Double_t scfDPLike(0.0); Double_t recoJacobian(1.0); Double_t xCoord(0.0); Double_t yCoord(0.0); Bool_t squareDP = negKinematics_->squareDP(); if ( squareDP ) { xCoord = negSigModel_->getEvtmPrime(); yCoord = negSigModel_->getEvtthPrime(); recoJacobian = recoJacobians_[iEvt]; } else { xCoord = negSigModel_->getEvtm13Sq(); yCoord = negSigModel_->getEvtm23Sq(); } // Find the bin that our reco event falls in Int_t recoBin = scfMap_->binNumber( xCoord, yCoord ); // Find out which true Bins contribute to the given reco bin const std::vector* trueBins = scfMap_->trueBins(recoBin); const Int_t nDataEvents = this->eventsPerExpt(); // Loop over the true bins for (std::vector::const_iterator iter = trueBins->begin(); iter != trueBins->end(); ++iter) { Int_t trueBin = (*iter); // prob of a true event in the given true bin migrating to the reco bin Double_t pRecoGivenTrue = scfMap_->prob( recoBin, trueBin ); Double_t pTrue(0.0); // We've cached the DP amplitudes and the efficiency for the // true bin centres, just after the data points // TODO: Check this!! /*if ( tagged_ ) { LauIsobarDynamics* sigModel(0); if (curEvtCharge_<0) { sigModel = negSigModel_; } else { sigModel = posSigModel_; } sigModel->calcLikelihoodInfo( nDataEvents + trueBin ); pTrue = sigModel->getEvtDPAmp().abs2() * sigModel->getEvtEff(); } else {*/ posSigModel_->calcLikelihoodInfo( nDataEvents + trueBin ); negSigModel_->calcLikelihoodInfo( nDataEvents + trueBin ); //pTrue = 0.5 * ( posSigModel_->getEvtDPAmp().abs2() * posSigModel_->getEvtEff() + // negSigModel_->getEvtDPAmp().abs2() * negSigModel_->getEvtEff() ); const LauComplex& A = posSigModel_->getEvtDPAmp(); const LauComplex& Abar = negSigModel_->getEvtDPAmp(); const LauComplex AstAbar = A.conj() * Abar; pTrue = A.abs2() * posSigModel_->getEvtEff() + Abar.abs2() * negSigModel_->getEvtEff() - 2.0 * D_ * AstAbar.re(); //} // Get the cached SCF fraction (and jacobian if we're using the square DP) Double_t scfFraction = fakeSCFFracs_[ trueBin ]; Double_t jacobian(1.0); if ( squareDP ) { jacobian = fakeJacobians_[ trueBin ]; } scfDPLike += pTrue * jacobian * scfFraction * pRecoGivenTrue; } // Divide by the reco jacobian scfDPLike /= recoJacobian; return scfDPLike; } void LauBsCPFitModel::getEvtExtraLikelihoods(UInt_t iEvt) { // Function to return the signal and background likelihoods for the // extra variables for the given event evtNo. sigExtraLike_ = 1.0; const UInt_t nBkgnds = this->nBkgndClasses(); // TODO: Not sure here about this! // I will comment out the minimum I can /*if ( ! tagged_ || curEvtCharge_ < 0 ) { sigExtraLike_ = this->prodPdfValue( negSignalPdfs_, iEvt ); if (useSCF_) { scfExtraLike_ = this->prodPdfValue( negScfPdfs_, iEvt ); } for ( UInt_t bkgndID(0); bkgndID < nBkgnds; ++bkgndID ) { if (usingBkgnd_) { bkgndExtraLike_[bkgndID] = this->prodPdfValue( negBkgndPdfs_[bkgndID], iEvt ); } else { bkgndExtraLike_[bkgndID] = 0.0; } } } else { sigExtraLike_ = this->prodPdfValue( posSignalPdfs_, iEvt ); if (useSCF_) { scfExtraLike_ = this->prodPdfValue( posScfPdfs_, iEvt ); } for ( UInt_t bkgndID(0); bkgndID < nBkgnds; ++bkgndID ) { if (usingBkgnd_) { bkgndExtraLike_[bkgndID] = this->prodPdfValue( posBkgndPdfs_[bkgndID], iEvt ); } else { bkgndExtraLike_[bkgndID] = 0.0; } } } */ sigExtraLike_ = this->prodPdfValue( signalPdfs_, iEvt ); if (useSCF_) { scfExtraLike_ = this->prodPdfValue( scfPdfs_, iEvt ); } for ( UInt_t bkgndID(0); bkgndID < nBkgnds; ++bkgndID ) { if (usingBkgnd_) { bkgndExtraLike_[bkgndID] = this->prodPdfValue( bkgndPdfs_[bkgndID], iEvt ); } else { bkgndExtraLike_[bkgndID] = 0.0; } } } void LauBsCPFitModel::updateCoeffs() { negCoeffs_.clear(); posCoeffs_.clear(); negCoeffs_.reserve(nSigComp_); posCoeffs_.reserve(nSigComp_); for (UInt_t i = 0; i < nSigComp_; i++) { negCoeffs_.push_back(coeffPars_[i]->antiparticleCoeff()); posCoeffs_.push_back(coeffPars_[i]->particleCoeff()); } } void LauBsCPFitModel::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"); if ( negSigModel_->usingScfModel() && posSigModel_->usingScfModel() ) { this->addSPlotNtupleDoubleBranch("scffraction"); } } // Store the total event likelihood for each species. if (useSCF_) { this->addSPlotNtupleDoubleBranch("sigTMTotalLike"); this->addSPlotNtupleDoubleBranch("sigSCFTotalLike"); this->addSPlotNtupleDoubleBranch("sigSCFFrac"); } else { 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()) { if (useSCF_) { this->addSPlotNtupleDoubleBranch("sigTMDPLike"); this->addSPlotNtupleDoubleBranch("sigSCFDPLike"); } else { 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 if (useSCF_) { this->addSPlotNtupleBranches(&signalPdfs_, "sigTM"); this->addSPlotNtupleBranches(&scfPdfs_, "sigSCF"); } else { this->addSPlotNtupleBranches(&signalPdfs_, "sig"); } if (usingBkgnd_) { const UInt_t nBkgnds = this->nBkgndClasses(); for ( UInt_t iBkgnd(0); iBkgnd < nBkgnds; ++iBkgnd ) { const TString& bkgndClass = this->bkgndClassName(iBkgnd); const LauPdfPList* pdfList = &(bkgndPdfs_[iBkgnd]); this->addSPlotNtupleBranches(pdfList, bkgndClass); } } } void LauBsCPFitModel::addSPlotNtupleBranches(const LauPdfPList* extraPdfs, const TString& prefix) { if (extraPdfs) { // Loop through each of the PDFs for (LauPdfPList::const_iterator pdf_iter = extraPdfs->begin(); pdf_iter != extraPdfs->end(); ++pdf_iter) { // 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); 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" ) { ++nVars; } } if ( nVars == 1 ) { // If the PDF only has one variable then // simply add one branch for that variable TString varName = (*pdf_iter)->varName(); TString name(prefix); name += 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 ( std::vector::const_iterator var_iter = varNames.begin(); var_iter != varNames.end(); ++var_iter ) { allVars += (*var_iter); TString name(prefix); name += (*var_iter); name += "Like"; this->addSPlotNtupleDoubleBranch(name); } TString name(prefix); name += allVars; name += "Like"; this->addSPlotNtupleDoubleBranch(name); } else { std::cerr << "WARNING in LauBsCPFitModel::addSPlotNtupleBranches : Can't yet deal with 3D PDFs." << std::endl; } } } } Double_t LauBsCPFitModel::setSPlotNtupleBranchValues(LauPdfPList* extraPdfs, const TString& prefix, UInt_t iEvt) { // Store the PDF value for each variable in the list Double_t totalLike(1.0); Double_t extraLike(0.0); if (extraPdfs) { for (LauPdfPList::iterator pdf_iter = extraPdfs->begin(); pdf_iter != extraPdfs->end(); ++pdf_iter) { // calculate the likelihood for this event (*pdf_iter)->calcLikelihoodInfo(iEvt); extraLike = (*pdf_iter)->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); 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" ) { ++nVars; } } if ( nVars == 1 ) { // If the PDF only has one variable then // simply store the value for that variable TString varName = (*pdf_iter)->varName(); TString name(prefix); name += 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 ( std::vector::const_iterator var_iter = varNames.begin(); var_iter != varNames.end(); ++var_iter ) { allVars += (*var_iter); TString name(prefix); name += (*var_iter); name += "Like"; Double_t indivLike = (*pdf_iter)->getLikelihood( (*var_iter) ); this->setSPlotNtupleDoubleBranchValue(name, indivLike); } TString name(prefix); name += allVars; name += "Like"; this->setSPlotNtupleDoubleBranchValue(name, extraLike); } else { std::cerr << "WARNING in LauBsCPFitModel::setSPlotNtupleBranchValues : Can't yet deal with 3D PDFs." << std::endl; } } } return totalLike; } LauSPlot::NameSet LauBsCPFitModel::variableNames() const { LauSPlot::NameSet nameSet; if (this->useDP()) { nameSet.insert("DP"); } // Loop through all the signal PDFs for (LauPdfPList::const_iterator pdf_iter = signalPdfs_.begin(); pdf_iter != signalPdfs_.end(); ++pdf_iter) { // Loop over the variables involved in each PDF std::vector varNames = (*pdf_iter)->varNames(); for ( std::vector::const_iterator var_iter = varNames.begin(); var_iter != varNames.end(); ++var_iter ) { // If they are not DP coordinates then add them if ( (*var_iter) != "m13Sq" && (*var_iter) != "m23Sq" ) { nameSet.insert( (*var_iter) ); } } } return nameSet; } LauSPlot::NumbMap LauBsCPFitModel::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(); } } } return numbMap; } LauSPlot::NumbMap LauBsCPFitModel::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 LauBsCPFitModel::twodimPDFs() const { // This makes the assumption that the form of the positive and // negative PDFs are the same, which seems reasonable to me LauSPlot::TwoDMap twodimMap; for (LauPdfPList::const_iterator pdf_iter = signalPdfs_.begin(); pdf_iter != signalPdfs_.end(); ++pdf_iter) { // Count the number of input variables that are not DP variables UInt_t nVars(0); 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" ) { ++nVars; } } if ( nVars == 2 ) { if (useSCF_) { twodimMap.insert( std::make_pair( "sigTM", std::make_pair( varNames[0], varNames[1] ) ) ); } else { twodimMap.insert( std::make_pair( "sig", std::make_pair( varNames[0], varNames[1] ) ) ); } } } if ( useSCF_ ) { for (LauPdfPList::const_iterator pdf_iter = scfPdfs_.begin(); pdf_iter != scfPdfs_.end(); ++pdf_iter) { // Count the number of input variables that are not DP variables UInt_t nVars(0); 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" ) { ++nVars; } } if ( nVars == 2 ) { twodimMap.insert( std::make_pair( "sigSCF", 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); const LauPdfPList& pdfList = bkgndPdfs_[iBkgnd]; for (LauPdfPList::const_iterator pdf_iter = pdfList.begin(); pdf_iter != pdfList.end(); ++pdf_iter) { // Count the number of input variables that are not DP variables UInt_t nVars(0); 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" ) { ++nVars; } } if ( nVars == 2 ) { twodimMap.insert( std::make_pair( bkgndClass, std::make_pair( varNames[0], varNames[1] ) ) ); } } } } return twodimMap; } void LauBsCPFitModel::storePerEvtLlhds() { std::cout << "INFO in LauBsCPFitModel::storePerEvtLlhds : Storing per-event likelihood values..." << std::endl; // 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 LauFitDataTree* inputFitData = this->fitData(); if (!this->useDP() && this->storeDPEff()) { negSigModel_->initialise(negCoeffs_); posSigModel_->initialise(posCoeffs_); negSigModel_->fillDataTree(*inputFitData); posSigModel_->fillDataTree(*inputFitData); } UInt_t evtsPerExpt(this->eventsPerExpt()); //LauIsobarDynamics* sigModel(0); LauPdfPList* sigPdfs(0); LauPdfPList* scfPdfs(0); LauBkgndPdfsList* bkgndPdfs(0); for (UInt_t iEvt = 0; iEvt < evtsPerExpt; ++iEvt) { this->setSPlotNtupleIntegerBranchValue("iExpt",this->iExpt()); this->setSPlotNtupleIntegerBranchValue("iEvtWithinExpt",iEvt); // Find out whether we have B- or B+ // TODO: Check this (Commented out for the time being) /*if ( tagged_ ) { const LauFitData& dataValues = inputFitData->getData(iEvt); LauFitData::const_iterator iter = dataValues.find("charge"); curEvtCharge_ = static_cast(iter->second); if (curEvtCharge_==+1) { sigModel = posSigModel_; sigPdfs = &posSignalPdfs_; scfPdfs = &posScfPdfs_; bkgndPdfs = &posBkgndPdfs_; } else { sigModel = negSigModel_; sigPdfs = &negSignalPdfs_; scfPdfs = &negScfPdfs_; bkgndPdfs = &negBkgndPdfs_; } } else { sigPdfs = &negSignalPdfs_; scfPdfs = &negScfPdfs_; bkgndPdfs = &negBkgndPdfs_; } */ //sigModel = negSigModel_; sigPdfs = &signalPdfs_; scfPdfs = &scfPdfs_; bkgndPdfs = &bkgndPdfs_; // the DP information this->getEvtDPLikelihood(iEvt); if (this->storeDPEff()) { if (!this->useDP()) { posSigModel_->calcLikelihoodInfo(iEvt); negSigModel_->calcLikelihoodInfo(iEvt); } /*if ( tagged_ ) { this->setSPlotNtupleDoubleBranchValue("efficiency",sigModel->getEvtEff()); if ( negSigModel_->usingScfModel() && posSigModel_->usingScfModel() ) { this->setSPlotNtupleDoubleBranchValue("scffraction",sigModel->getEvtScfFraction()); } } else {*/ // TODO: Does it matter? this->setSPlotNtupleDoubleBranchValue("efficiency",0.5*(posSigModel_->getEvtEff() + negSigModel_->getEvtEff()) ); if ( negSigModel_->usingScfModel() && posSigModel_->usingScfModel() ) { this->setSPlotNtupleDoubleBranchValue("scffraction",0.5*(posSigModel_->getEvtScfFraction() + negSigModel_->getEvtScfFraction())); } //} } if (this->useDP()) { sigTotalLike_ = sigDPLike_; if (useSCF_) { scfTotalLike_ = scfDPLike_; this->setSPlotNtupleDoubleBranchValue("sigTMDPLike",sigDPLike_); this->setSPlotNtupleDoubleBranchValue("sigSCFDPLike",scfDPLike_); } else { 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; if (useSCF_) { scfTotalLike_ = 1.0; } if (usingBkgnd_) { const UInt_t nBkgnds = this->nBkgndClasses(); for ( UInt_t iBkgnd(0); iBkgnd < nBkgnds; ++iBkgnd ) { bkgndTotalLike_[iBkgnd] = 1.0; } } } // the signal PDF values if ( useSCF_ ) { sigTotalLike_ *= this->setSPlotNtupleBranchValues(sigPdfs, "sigTM", iEvt); scfTotalLike_ *= this->setSPlotNtupleBranchValues(scfPdfs, "sigSCF", iEvt); } else { sigTotalLike_ *= this->setSPlotNtupleBranchValues(sigPdfs, "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 if (useSCF_) { Double_t scfFrac(0.0); if ( useSCFHist_ ) { scfFrac = recoSCFFracs_[iEvt]; } else { scfFrac = scfFrac_.unblindValue(); } this->setSPlotNtupleDoubleBranchValue("sigSCFFrac",scfFrac); sigTotalLike_ *= ( 1.0 - scfFrac ); if ( scfMap_ == 0 ) { scfTotalLike_ *= scfFrac; } this->setSPlotNtupleDoubleBranchValue("sigTMTotalLike",sigTotalLike_); this->setSPlotNtupleDoubleBranchValue("sigSCFTotalLike",scfTotalLike_); } else { 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 LauBsCPFitModel::storePerEvtLlhds : Finished storing per-event likelihood values." << std::endl; } /* void LauBsCPFitModel::embedNegSignal(const TString& fileName, const TString& treeName, Bool_t reuseEventsWithinEnsemble, Bool_t reuseEventsWithinExperiment, Bool_t useReweighting) { if (negSignalTree_) { std::cerr << "ERROR in LauBsCPFitModel::embedNegSignal : Already embedding signal from a file." << std::endl; return; } if (!reuseEventsWithinEnsemble && reuseEventsWithinExperiment) { std::cerr << "WARNING in LauBsCPFitModel::embedNegSignal : Conflicting options provided, will not reuse events at all." << std::endl; reuseEventsWithinExperiment = kFALSE; } negSignalTree_ = new LauEmbeddedData(fileName,treeName,reuseEventsWithinExperiment); Bool_t dataOK = negSignalTree_->findBranches(); if (!dataOK) { delete negSignalTree_; negSignalTree_ = 0; std::cerr << "ERROR in LauBsCPFitModel::embedNegSignal : Problem creating data tree for embedding." << std::endl; return; } reuseSignal_ = reuseEventsWithinEnsemble; useNegReweighting_ = useReweighting; if (this->enableEmbedding() == kFALSE) {this->enableEmbedding(kTRUE);} } void LauBsCPFitModel::embedBkgnd(const TString& bkgndClass, const TString& fileName, const TString& treeName, Bool_t reuseEventsWithinEnsemble, Bool_t reuseEventsWithinExperiment) { if ( ! this->validBkgndClass( bkgndClass ) ) { std::cerr << "ERROR in LauBsCPFitModel::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 ); if (bkgndTree_[bkgndID]) { std::cerr << "ERROR in LauBsCPFitModel::embedBkgnd : Already embedding background from a file." << std::endl; return; } if (!reuseEventsWithinEnsemble && reuseEventsWithinExperiment) { std::cerr << "WARNING in LauBsCPFitModel::embedBkgnd : Conflicting options provided, will not reuse events at all." << std::endl; reuseEventsWithinExperiment = kFALSE; } bkgndTree_[bkgndID] = new LauEmbeddedData(fileName,treeName,reuseEventsWithinExperiment); Bool_t dataOK = bkgndTree_[bkgndID]->findBranches(); if (!dataOK) { delete bkgndTree_[bkgndID]; bkgndTree_[bkgndID] = 0; std::cerr << "ERROR in LauBsCPFitModel::embedBkgnd : Problem creating data tree for embedding." << std::endl; return; } reuseBkgnd_[bkgndID] = reuseEventsWithinEnsemble; if (this->enableEmbedding() == kFALSE) {this->enableEmbedding(kTRUE);} } void LauBsCPFitModel::embedPosSignal(const TString& fileName, const TString& treeName, Bool_t reuseEventsWithinEnsemble, Bool_t reuseEventsWithinExperiment, Bool_t useReweighting) { if (posSignalTree_) { std::cerr << "ERROR in LauBsCPFitModel::embedPosSignal : Already embedding signal from a file." << std::endl; return; } if (!reuseEventsWithinEnsemble && reuseEventsWithinExperiment) { std::cerr << "WARNING in LauBsCPFitModel::embedPosSignal : Conflicting options provided, will not reuse events at all." << std::endl; reuseEventsWithinExperiment = kFALSE; } posSignalTree_ = new LauEmbeddedData(fileName,treeName,reuseEventsWithinExperiment); Bool_t dataOK = posSignalTree_->findBranches(); if (!dataOK) { delete posSignalTree_; posSignalTree_ = 0; std::cerr << "ERROR in LauBsCPFitModel::embedPosSignal : Problem creating data tree for embedding." << std::endl; return; } reuseSignal_ = reuseEventsWithinEnsemble; usePosReweighting_ = useReweighting; if (this->enableEmbedding() == kFALSE) {this->enableEmbedding(kTRUE);} } */ void LauBsCPFitModel::weightEvents( const TString& /*dataFileName*/, const TString& /*dataTreeName*/ ) { std::cerr << "ERROR in LauBsCPFitModel::weightEvents : Method not available for this fit model." << std::endl; return; } void LauBsCPFitModel::savePDFPlots(const TString& /*label*/) { } void LauBsCPFitModel::savePDFPlotsWave(const TString& /*label*/, const Int_t& /*spin*/) { } diff --git a/src/LauCPFitModel.cc b/src/LauCPFitModel.cc index 57e2c6f..cf38955 100644 --- a/src/LauCPFitModel.cc +++ b/src/LauCPFitModel.cc @@ -1,3437 +1,3437 @@ /* Copyright 2004 University of Warwick Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Laura++ package authors: John Back Paul Harrison Thomas Latham */ /*! \file LauCPFitModel.cc \brief File containing implementation of LauCPFitModel class. */ #include #include #include #include #include "TVirtualFitter.h" #include "TSystem.h" #include "TMinuit.h" #include "TRandom.h" #include "TFile.h" #include "TTree.h" #include "TBranch.h" #include "TLeaf.h" #include "TMath.h" #include "TH2.h" #include "TGraph2D.h" #include "TGraph.h" #include "TStyle.h" #include "TCanvas.h" #include "LauAbsBkgndDPModel.hh" #include "LauAbsCoeffSet.hh" #include "LauIsobarDynamics.hh" #include "LauAbsPdf.hh" #include "LauAsymmCalc.hh" #include "LauComplex.hh" #include "LauConstants.hh" #include "LauCPFitModel.hh" #include "LauDaughters.hh" #include "LauEffModel.hh" #include "LauEmbeddedData.hh" #include "LauFitNtuple.hh" #include "LauGenNtuple.hh" #include "LauKinematics.hh" #include "LauPrint.hh" #include "LauRandom.hh" #include "LauScfMap.hh" ClassImp(LauCPFitModel) LauCPFitModel::LauCPFitModel(LauIsobarDynamics* negModel, LauIsobarDynamics* posModel, Bool_t tagged, const TString& tagVarName) : LauAbsFitModel(), negSigModel_(negModel), posSigModel_(posModel), negKinematics_(negModel ? negModel->getKinematics() : 0), posKinematics_(posModel ? posModel->getKinematics() : 0), usingBkgnd_(kFALSE), nSigComp_(0), nSigDPPar_(0), nExtraPdfPar_(0), nNormPar_(0), negMeanEff_("negMeanEff",0.0,0.0,1.0), posMeanEff_("posMeanEff",0.0,0.0,1.0), negDPRate_("negDPRate",0.0,0.0,100.0), posDPRate_("posDPRate",0.0,0.0,100.0), signalEvents_(0), signalAsym_(0), forceAsym_(kFALSE), tagged_(tagged), tagVarName_(tagVarName), curEvtCharge_(0), useSCF_(kFALSE), useSCFHist_(kFALSE), scfFrac_("scfFrac",0.0,0.0,1.0), scfFracHist_(0), scfMap_(0), compareFitData_(kFALSE), negParent_("B-"), posParent_("B+"), negSignalTree_(0), posSignalTree_(0), reuseSignal_(kFALSE), useNegReweighting_(kFALSE), usePosReweighting_(kFALSE), sigDPLike_(0.0), scfDPLike_(0.0), sigExtraLike_(0.0), scfExtraLike_(0.0), sigTotalLike_(0.0), scfTotalLike_(0.0) { const LauDaughters* negDaug = negSigModel_->getDaughters(); if (negDaug != 0) {negParent_ = negDaug->getNameParent();} const LauDaughters* posDaug = posSigModel_->getDaughters(); if (posDaug != 0) {posParent_ = posDaug->getNameParent();} } LauCPFitModel::~LauCPFitModel() { delete negSignalTree_; delete posSignalTree_; for (LauBkgndEmbDataList::iterator iter = negBkgndTree_.begin(); iter != negBkgndTree_.end(); ++iter) { delete (*iter); } for (LauBkgndEmbDataList::iterator iter = posBkgndTree_.begin(); iter != posBkgndTree_.end(); ++iter) { delete (*iter); } delete scfFracHist_; } void LauCPFitModel::setupBkgndVectors() { UInt_t nBkgnds = this->nBkgndClasses(); negBkgndDPModels_.resize( nBkgnds ); posBkgndDPModels_.resize( nBkgnds ); negBkgndPdfs_.resize( nBkgnds ); posBkgndPdfs_.resize( nBkgnds ); bkgndEvents_.resize( nBkgnds ); bkgndAsym_.resize( nBkgnds ); negBkgndTree_.resize( nBkgnds ); posBkgndTree_.resize( nBkgnds ); reuseBkgnd_.resize( nBkgnds ); bkgndDPLike_.resize( nBkgnds ); bkgndExtraLike_.resize( nBkgnds ); bkgndTotalLike_.resize( nBkgnds ); } void LauCPFitModel::setNSigEvents(LauParameter* nSigEvents) { if ( nSigEvents == 0 ) { std::cerr << "ERROR in LauCPFitModel::setNSigEvents : The LauParameter pointer is null." << std::endl; gSystem->Exit(EXIT_FAILURE); } if ( signalEvents_ != 0 ) { std::cerr << "ERROR in LauCPFitModel::setNSigEvents : You are trying to overwrite the signal yield." << std::endl; return; } if ( signalAsym_ != 0 ) { std::cerr << "ERROR in LauCPFitModel::setNSigEvents : You are trying to overwrite the signal asymmetry." << std::endl; return; } signalEvents_ = nSigEvents; TString yieldName = signalEvents_->name(); if ( ! yieldName.BeginsWith("signalEvents") ) { std::cerr << "ERROR in LauCPFitModel::setNSigEvents : The signal yield parameter name should start with \"signalEvents\" (plus any optional suffix)." << std::endl; gSystem->Exit(EXIT_FAILURE); } Double_t value = nSigEvents->value(); signalEvents_->range(-2.0*(TMath::Abs(value)+1.0), 2.0*(TMath::Abs(value)+1.0)); TString asymName = yieldName; asymName.ReplaceAll( "Events", "Asym" ); signalAsym_ = new LauParameter(asymName,0.0,-1.0,1.0,kTRUE); } void LauCPFitModel::setNSigEvents( LauParameter* nSigEvents, LauParameter* sigAsym, Bool_t forceAsym ) { if ( nSigEvents == 0 ) { std::cerr << "ERROR in LauCPFitModel::setNSigEvents : The event LauParameter pointer is null." << std::endl; gSystem->Exit(EXIT_FAILURE); } if ( sigAsym == 0 ) { std::cerr << "ERROR in LauCPFitModel::setNSigEvents : The asym LauParameter pointer is null." << std::endl; gSystem->Exit(EXIT_FAILURE); } if ( signalEvents_ != 0 ) { std::cerr << "ERROR in LauCPFitModel::setNSigEvents : You are trying to overwrite the signal yield." << std::endl; return; } if ( signalAsym_ != 0 ) { std::cerr << "ERROR in LauCPFitModel::setNSigEvents : You are trying to overwrite the signal asymmetry." << std::endl; return; } signalEvents_ = nSigEvents; signalAsym_ = sigAsym; TString yieldName = signalEvents_->name(); if ( ! yieldName.BeginsWith("signalEvents") ) { std::cerr << "ERROR in LauCPFitModel::setNSigEvents : The signal yield parameter name should start with \"signalEvents\" (plus any optional suffix)." << std::endl; gSystem->Exit(EXIT_FAILURE); } Double_t value = nSigEvents->value(); signalEvents_->range(-2.0*(TMath::Abs(value)+1.0), 2.0*(TMath::Abs(value)+1.0)); TString asymName = yieldName; asymName.ReplaceAll( "Events", "Asym" ); signalAsym_->name(asymName); signalAsym_->range(-1.0,1.0); forceAsym_ = forceAsym; } void LauCPFitModel::setNBkgndEvents( LauAbsRValue* nBkgndEvents ) { if ( nBkgndEvents == 0 ) { std::cerr << "ERROR in LauCPFitModel::setNBgkndEvents : The background yield LauParameter pointer is null." << std::endl; gSystem->Exit(EXIT_FAILURE); } TString yieldName = nBkgndEvents->name(); TString bkgndClassName = yieldName; if ( bkgndClassName.Contains("Events") ) { bkgndClassName.Remove( bkgndClassName.Index("Events") ); } else { yieldName += "Events"; nBkgndEvents->name( yieldName ); } if ( ! this->validBkgndClass( bkgndClassName ) ) { std::cerr << "ERROR in LauCPFitModel::setNBkgndEvents : Invalid background class \"" << bkgndClassName << "\"." << 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( bkgndClassName ); if ( bkgndEvents_[bkgndID] != 0 ) { std::cerr << "ERROR in LauCPFitModel::setNBkgndEvents : You are trying to overwrite the background yield." << std::endl; return; } if ( bkgndAsym_[bkgndID] != 0 ) { std::cerr << "ERROR in LauCPFitModel::setNBkgndEvents : You are trying to overwrite the background asymmetry." << std::endl; return; } 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; TString asymName = yieldName; asymName.ReplaceAll( "Events", "Asym" ); bkgndAsym_[bkgndID] = new LauParameter(asymName,0.0,-1.0,1.0,kTRUE); } void LauCPFitModel::setNBkgndEvents(LauAbsRValue* nBkgndEvents, LauAbsRValue* bkgndAsym) { if ( nBkgndEvents == 0 ) { std::cerr << "ERROR in LauCPFitModel::setNBkgndEvents : The background yield LauParameter pointer is null." << std::endl; gSystem->Exit(EXIT_FAILURE); } if ( bkgndAsym == 0 ) { std::cerr << "ERROR in LauCPFitModel::setNBkgndEvents : The background asym LauParameter pointer is null." << std::endl; gSystem->Exit(EXIT_FAILURE); } TString yieldName = nBkgndEvents->name(); TString bkgndClassName = yieldName; if ( bkgndClassName.Contains("Events") ) { bkgndClassName.Remove( bkgndClassName.Index("Events") ); } else { yieldName += "Events"; nBkgndEvents->name( yieldName ); } TString asymName = yieldName; asymName.ReplaceAll( "Events", "Asym" ); bkgndAsym->name( asymName ); if ( ! this->validBkgndClass( bkgndClassName ) ) { std::cerr << "ERROR in LauCPFitModel::setNBkgndEvents : Invalid background class \"" << bkgndClassName << "\"." << 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( bkgndClassName ); if ( bkgndEvents_[bkgndID] != 0 ) { std::cerr << "ERROR in LauCPFitModel::setNBkgndEvents : You are trying to overwrite the background yield." << std::endl; return; } if ( bkgndAsym_[bkgndID] != 0 ) { std::cerr << "ERROR in LauCPFitModel::setNBkgndEvents : You are trying to overwrite the background asymmetry." << std::endl; return; } 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; if ( bkgndAsym->isLValue() ) { LauParameter* asym = dynamic_cast( bkgndAsym ); asym->range(-1.0, 1.0); } bkgndAsym_[bkgndID] = bkgndAsym; } void LauCPFitModel::splitSignalComponent( const TH2* dpHisto, const Bool_t upperHalf, const Bool_t fluctuateBins, LauScfMap* scfMap ) { if ( useSCF_ == kTRUE ) { std::cerr << "ERROR in LauCPFitModel::splitSignalComponent : Have already setup SCF." << std::endl; return; } if ( dpHisto == 0 ) { std::cerr << "ERROR in LauCPFitModel::splitSignalComponent : The histogram pointer is null." << std::endl; return; } const LauDaughters* daughters = negSigModel_->getDaughters(); scfFracHist_ = new LauEffModel( daughters, 0 ); scfFracHist_->setEffHisto( dpHisto, kTRUE, fluctuateBins, 0.0, 0.0, upperHalf, daughters->squareDP() ); scfMap_ = scfMap; useSCF_ = kTRUE; useSCFHist_ = kTRUE; } void LauCPFitModel::splitSignalComponent( const Double_t scfFrac, const Bool_t fixed ) { if ( useSCF_ == kTRUE ) { std::cerr << "ERROR in LauCPFitModel::splitSignalComponent : Have already setup SCF." << std::endl; return; } scfFrac_.range( 0.0, 1.0 ); scfFrac_.value( scfFrac ); scfFrac_.initValue( scfFrac ); scfFrac_.genValue( scfFrac ); scfFrac_.fixed( fixed ); useSCF_ = kTRUE; useSCFHist_ = kFALSE; } void LauCPFitModel::setBkgndDPModels(const TString& bkgndClass, LauAbsBkgndDPModel* negModel, LauAbsBkgndDPModel* posModel) { if ((negModel==0) || (posModel==0)) { std::cerr << "ERROR in LauCPFitModel::setBkgndDPModels : One or both of the model pointers is null." << std::endl; return; } // check that this background name is valid if ( ! this->validBkgndClass( bkgndClass) ) { std::cerr << "ERROR in LauCPFitModel::setBkgndDPModel : 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 ); negBkgndDPModels_[bkgndID] = negModel; posBkgndDPModels_[bkgndID] = posModel; usingBkgnd_ = kTRUE; } void LauCPFitModel::setSignalPdfs(LauAbsPdf* negPdf, LauAbsPdf* posPdf) { if ( tagged_ ) { if (negPdf==0 || posPdf==0) { std::cerr << "ERROR in LauCPFitModel::setSignalPdfs : One or both of the PDF pointers is null." << std::endl; return; } } else { // if we're doing an untagged analysis we will only use the negative PDFs if ( negPdf==0 ) { std::cerr << "ERROR in LauCPFitModel::setSignalPdfs : The negative PDF pointer is null." << std::endl; return; } if ( posPdf!=0 ) { std::cerr << "WARNING in LauCPFitModel::setSignalPdfs : Doing an untagged fit so will not use the positive PDF." << std::endl; } } negSignalPdfs_.push_back(negPdf); posSignalPdfs_.push_back(posPdf); } void LauCPFitModel::setSCFPdfs(LauAbsPdf* negPdf, LauAbsPdf* posPdf) { if ( tagged_ ) { if (negPdf==0 || posPdf==0) { std::cerr << "ERROR in LauCPFitModel::setSCFPdfs : One or both of the PDF pointers is null." << std::endl; return; } } else { // if we're doing an untagged analysis we will only use the negative PDFs if ( negPdf==0 ) { std::cerr << "ERROR in LauCPFitModel::setSCFPdfs : The negative PDF pointer is null." << std::endl; return; } if ( posPdf!=0 ) { std::cerr << "WARNING in LauCPFitModel::setSCFPdfs : Doing an untagged fit so will not use the positive PDF." << std::endl; } } negScfPdfs_.push_back(negPdf); posScfPdfs_.push_back(posPdf); } void LauCPFitModel::setBkgndPdfs(const TString& bkgndClass, LauAbsPdf* negPdf, LauAbsPdf* posPdf) { if ( tagged_ ) { if (negPdf==0 || posPdf==0) { std::cerr << "ERROR in LauCPFitModel::setBkgndPdfs : One or both of the PDF pointers is null." << std::endl; return; } } else { // if we're doing an untagged analysis we will only use the negative PDFs if ( negPdf==0 ) { std::cerr << "ERROR in LauCPFitModel::setBkgndPdfs : The negative PDF pointer is null." << std::endl; return; } if ( posPdf!=0 ) { std::cerr << "WARNING in LauCPFitModel::setBkgndPdfs : Doing an untagged fit so will not use the positive PDF." << std::endl; } } // check that this background name is valid if ( ! this->validBkgndClass( bkgndClass ) ) { std::cerr << "ERROR in LauCPFitModel::setBkgndPdfs : 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 ); negBkgndPdfs_[bkgndID].push_back(negPdf); posBkgndPdfs_[bkgndID].push_back(posPdf); usingBkgnd_ = kTRUE; } void LauCPFitModel::setAmpCoeffSet(std::unique_ptr coeffSet) { // Resize the coeffPars vector if not already done if ( coeffPars_.empty() ) { const UInt_t nNegAmp { negSigModel_->getnTotAmp() }; const UInt_t nPosAmp { posSigModel_->getnTotAmp() }; if ( nNegAmp != nPosAmp ) { std::cerr << "ERROR in LauCPFitModel::setAmpCoeffSet : Unequal number of signal DP components in the negative and positive models: " << nNegAmp << " != " << nPosAmp << std::endl; gSystem->Exit(EXIT_FAILURE); } coeffPars_.resize( nNegAmp ); fitFracAsymm_.resize( nNegAmp ); acp_.resize( nNegAmp ); } // Is there a component called compName in the signal model? const TString compName { coeffSet->name()}; const TString conjName { negSigModel_->getConjResName(compName) }; const Int_t negIndex { negSigModel_->resonanceIndex(compName) }; const Int_t posIndex { posSigModel_->resonanceIndex(conjName) }; if ( negIndex < 0 ) { std::cerr << "ERROR in LauCPFitModel::setAmpCoeffSet : " << negParent_ << " signal DP model doesn't contain component \"" << compName << "\"." << std::endl; return; } if ( posIndex < 0 ) { std::cerr << "ERROR in LauCPFitModel::setAmpCoeffSet : " << posParent_ << " signal DP model doesn't contain component \"" << conjName << "\"." << std::endl; return; } if ( posIndex != negIndex ) { std::cerr << "ERROR in LauCPFitModel::setAmpCoeffSet : " << negParent_ << " signal DP model and " << posParent_ << " signal DP model have different indices for components \"" << compName << "\" and \"" << conjName << "\"." << std::endl; return; } // Do we already have it in our list of names? if ( coeffPars_[negIndex] != nullptr && coeffPars_[negIndex]->name() == compName) { std::cerr << "ERROR in LauCPFitModel::setAmpCoeffSet : Have already set coefficients for \"" << compName << "\"." << std::endl; return; } coeffSet->index(negIndex); std::cout << "INFO in LauCPFitModel::setAmpCoeffSet : Added coefficients for component \"" << compName << "\" to the fit model." << std::endl; coeffSet->printParValues(); const TString parName { coeffSet->baseName() + "FitFracAsym" }; fitFracAsymm_[negIndex] = LauParameter{parName, 0.0, -1.0, 1.0}; acp_[negIndex] = coeffSet->acp(); coeffPars_[negIndex] = std::move(coeffSet); ++nSigComp_; } void LauCPFitModel::initialise() { // Initialisation if (!this->useDP() && negSignalPdfs_.empty()) { std::cerr << "ERROR in LauCPFitModel::initialise : Signal model doesn't exist for any variable." << std::endl; gSystem->Exit(EXIT_FAILURE); } if ( this->useDP() ) { // Check that we have all the Dalitz-plot models if ((negSigModel_ == 0) || (posSigModel_ == 0)) { std::cerr << "ERROR in LauCPFitModel::initialise : the pointer to one (neg or pos) of the signal DP models is null.\n"; std::cerr << " : Removing the Dalitz Plot from the model." << std::endl; this->useDP(kFALSE); } if ( usingBkgnd_ ) { if ( negBkgndDPModels_.empty() || posBkgndDPModels_.empty() ) { std::cerr << "ERROR in LauCPFitModel::initialise : No background DP models found.\n"; std::cerr << " : Removing the Dalitz plot from the model." << std::endl; this->useDP(kFALSE); } for (LauBkgndDPModelList::const_iterator dpmodel_iter = negBkgndDPModels_.begin(); dpmodel_iter != negBkgndDPModels_.end(); ++dpmodel_iter ) { if ( (*dpmodel_iter) == 0 ) { std::cerr << "ERROR in LauCPFitModel::initialise : The pointer to one of the background DP models is null.\n"; std::cerr << " : Removing the Dalitz Plot from the model." << std::endl; this->useDP(kFALSE); break; } } for (LauBkgndDPModelList::const_iterator dpmodel_iter = posBkgndDPModels_.begin(); dpmodel_iter != posBkgndDPModels_.end(); ++dpmodel_iter ) { if ( (*dpmodel_iter) == 0 ) { std::cerr << "ERROR in LauCPFitModel::initialise : The pointer to one of the background DP models is null.\n"; std::cerr << " : Removing the Dalitz Plot from the model." << std::endl; this->useDP(kFALSE); break; } } } // Need to check that the number of components we have and that the dynamics has matches up const UInt_t nNegAmp = negSigModel_->getnTotAmp(); const UInt_t nPosAmp = posSigModel_->getnTotAmp(); if ( nNegAmp != nPosAmp ) { std::cerr << "ERROR in LauCPFitModel::initialise : Unequal number of signal DP components in the negative and positive models: " << nNegAmp << " != " << nPosAmp << std::endl; gSystem->Exit(EXIT_FAILURE); } if ( nNegAmp != nSigComp_ ) { std::cerr << "ERROR in LauCPFitModel::initialise : Number of signal DP components in the model (" << nNegAmp << ") not equal to number of coefficients supplied (" << nSigComp_ << ")." << std::endl; gSystem->Exit(EXIT_FAILURE); } if ( !fixParamFileName_.IsNull() || !fixParamMap_.empty() ) { // Set coefficients std::vector params; for ( auto itr = coeffPars_.begin(); itr != coeffPars_.end(); ++itr ) { std::vector p = (*itr)->getParameters(); params.insert(params.end(), p.begin(), p.end()); } this->fixParams(params); // Set resonance parameters (if they exist) negSigModel_->collateResonanceParameters(); posSigModel_->collateResonanceParameters(); this->fixParams(negSigModel_->getFloatingParameters()); this->fixParams(posSigModel_->getFloatingParameters()); } // From the initial parameter values calculate the coefficients // so they can be passed to the signal model this->updateCoeffs(); // If all is well, go ahead and initialise them this->initialiseDPModels(); } // 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 = negSignalPdfs_.begin(); pdf_iter != negSignalPdfs_.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 (useSCF_) { UInt_t nscfpdfvars(0); for ( LauPdfPList::const_iterator pdf_iter = negScfPdfs_.begin(); pdf_iter != negScfPdfs_.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" ) { ++nscfpdfvars; } } } if (nscfpdfvars != nsigpdfvars) { std::cerr << "ERROR in LauCPFitModel::initialise : There are " << nsigpdfvars << " TM signal PDF variables but " << nscfpdfvars << " SCF signal PDF variables." << std::endl; gSystem->Exit(EXIT_FAILURE); } } if (usingBkgnd_) { for (LauBkgndPdfsList::const_iterator bgclass_iter = negBkgndPdfs_.begin(); bgclass_iter != negBkgndPdfs_.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 LauCPFitModel::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 various extra PDFs this->setExtraPdfParameters(); // Set the initial bg and signal events this->setFitNEvents(); // Check that we have the expected number of fit variables const LauParameterPList& fitVars = this->fitPars(); if (fitVars.size() != (nSigDPPar_ + nExtraPdfPar_ + nNormPar_)) { std::cerr << "ERROR in LauCPFitModel::initialise : Number of fit parameters not of expected size. Exiting" << std::endl; gSystem->Exit(EXIT_FAILURE); } this->setExtraNtupleVars(); } void LauCPFitModel::recalculateNormalisation() { //std::cout << "INFO in LauCPFitModel::recalculateNormalizationInDPModels : Recalc Norm in DP model" << std::endl; negSigModel_->recalculateNormalisation(); posSigModel_->recalculateNormalisation(); negSigModel_->modifyDataTree(); posSigModel_->modifyDataTree(); } void LauCPFitModel::initialiseDPModels() { std::cout << "INFO in LauCPFitModel::initialiseDPModels : Initialising signal DP model" << std::endl; negSigModel_->initialise(negCoeffs_); posSigModel_->initialise(posCoeffs_); if (usingBkgnd_ == kTRUE) { for (LauBkgndDPModelList::iterator iter = negBkgndDPModels_.begin(); iter != negBkgndDPModels_.end(); ++iter) { (*iter)->initialise(); } for (LauBkgndDPModelList::iterator iter = posBkgndDPModels_.begin(); iter != posBkgndDPModels_.end(); ++iter) { (*iter)->initialise(); } } } void LauCPFitModel::setSignalDPParameters() { // Set the fit parameters for the signal model. nSigDPPar_ = 0; if ( ! this->useDP() ) { return; } std::cout << "INFO in LauCPFitModel::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& negSigDPPars = negSigModel_->getFloatingParameters(); LauParameterPList& posSigDPPars = posSigModel_->getFloatingParameters(); nSigDPPar_ += this->addResonanceParameters( negSigDPPars ); nSigDPPar_ += this->addResonanceParameters( posSigDPPars ); } void LauCPFitModel::setExtraPdfParameters() { // Include all the parameters of the PDF 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; nExtraPdfPar_ += this->addFitParameters(negSignalPdfs_); if ( tagged_ ) { nExtraPdfPar_ += this->addFitParameters(posSignalPdfs_); } if (useSCF_ == kTRUE) { nExtraPdfPar_ += this->addFitParameters(negScfPdfs_); if ( tagged_ ) { nExtraPdfPar_ += this->addFitParameters(posScfPdfs_); } } if (usingBkgnd_ == kTRUE) { for (LauBkgndPdfsList::iterator iter = negBkgndPdfs_.begin(); iter != negBkgndPdfs_.end(); ++iter) { nExtraPdfPar_ += this->addFitParameters(*iter); } if ( tagged_ ) { for (LauBkgndPdfsList::iterator iter = posBkgndPdfs_.begin(); iter != posBkgndPdfs_.end(); ++iter) { nExtraPdfPar_ += this->addFitParameters(*iter); } } } } void LauCPFitModel::setFitNEvents() { if ( signalEvents_ == 0 ) { std::cerr << "ERROR in LauCPFitModel::setFitNEvents : Signal yield not defined." << std::endl; return; } nNormPar_ = 0; // initialise the total number of events to be the sum of all the hypotheses Double_t nTotEvts = signalEvents_->value(); for (LauBkgndYieldList::const_iterator iter = bkgndEvents_.begin(); iter != bkgndEvents_.end(); ++iter) { nTotEvts += (*iter)->value(); if ( (*iter) == 0 ) { std::cerr << "ERROR in LauCPFitModel::setFitNEvents : Background yield not defined." << std::endl; return; } } this->eventsPerExpt(TMath::FloorNint(nTotEvts)); // if doing an extended ML fit add the number of signal events into the fit parameters if (this->doEMLFit()) { std::cout << "INFO in LauCPFitModel::setFitNEvents : Initialising number of events for signal and background components..." << std::endl; // add the signal fraction to the list of fit parameters nNormPar_ += this->addFitParameters( signalEvents_ ); } else { std::cout << "INFO in LauCPFitModel::setFitNEvents : Initialising number of events for background components (and hence signal)..." << std::endl; } // if not using the DP in the model we need an explicit signal asymmetry parameter if (this->useDP() == kFALSE) { nNormPar_ += this->addFitParameters( signalAsym_ ); } if (useSCF_ && !useSCFHist_) { nNormPar_ += this->addFitParameters( &scfFrac_ ); } if (usingBkgnd_ == kTRUE) { nNormPar_ += this->addFitParameters( bkgndEvents_ ); nNormPar_ += this->addFitParameters( bkgndAsym_ ); } } void LauCPFitModel::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 positive and negative fit fractions for each signal component negFitFrac_ = negSigModel_->getFitFractions(); if (negFitFrac_.size() != nSigComp_) { std::cerr << "ERROR in LauCPFitModel::setExtraNtupleVars : Initial Fit Fraction array of unexpected dimension: " << negFitFrac_.size() << std::endl; gSystem->Exit(EXIT_FAILURE); } for (UInt_t i(0); iExit(EXIT_FAILURE); } } posFitFrac_ = posSigModel_->getFitFractions(); if (posFitFrac_.size() != nSigComp_) { std::cerr << "ERROR in LauCPFitModel::setExtraNtupleVars : Initial Fit Fraction array of unexpected dimension: " << posFitFrac_.size() << std::endl; gSystem->Exit(EXIT_FAILURE); } for (UInt_t i(0); iExit(EXIT_FAILURE); } } // Add the positive and negative fit fractions that have not been corrected for the efficiency for each signal component negFitFracEffUnCorr_ = negSigModel_->getFitFractionsEfficiencyUncorrected(); if (negFitFracEffUnCorr_.size() != nSigComp_) { std::cerr << "ERROR in LauCPFitModel::setExtraNtupleVars : Initial Fit Fraction array of unexpected dimension: " << negFitFracEffUnCorr_.size() << std::endl; gSystem->Exit(EXIT_FAILURE); } for (UInt_t i(0); iExit(EXIT_FAILURE); } } posFitFracEffUnCorr_ = posSigModel_->getFitFractionsEfficiencyUncorrected(); if (posFitFracEffUnCorr_.size() != nSigComp_) { std::cerr << "ERROR in LauCPFitModel::setExtraNtupleVars : Initial Fit Fraction array of unexpected dimension: " << posFitFracEffUnCorr_.size() << std::endl; gSystem->Exit(EXIT_FAILURE); } for (UInt_t i(0); iExit(EXIT_FAILURE); } } for (UInt_t i(0); i negExtraPars = negSigModel_->getExtraParameters(); std::vector::iterator negExtraIter; for (negExtraIter = negExtraPars.begin(); negExtraIter != negExtraPars.end(); ++negExtraIter) { LauParameter negExtraParameter = (*negExtraIter); extraVars.push_back(negExtraParameter); } std::vector posExtraPars = posSigModel_->getExtraParameters(); std::vector::iterator posExtraIter; for (posExtraIter = posExtraPars.begin(); posExtraIter != posExtraPars.end(); ++posExtraIter) { LauParameter posExtraParameter = (*posExtraIter); extraVars.push_back(posExtraParameter); } // Now add in the DP efficiency value Double_t initMeanEff = negSigModel_->getMeanEff().initValue(); negMeanEff_.value(initMeanEff); negMeanEff_.genValue(initMeanEff); negMeanEff_.initValue(initMeanEff); extraVars.push_back(negMeanEff_); initMeanEff = posSigModel_->getMeanEff().initValue(); posMeanEff_.value(initMeanEff); posMeanEff_.genValue(initMeanEff); posMeanEff_.initValue(initMeanEff); extraVars.push_back(posMeanEff_); // Also add in the DP rates Double_t initDPRate = negSigModel_->getDPRate().initValue(); negDPRate_.value(initDPRate); negDPRate_.genValue(initDPRate); negDPRate_.initValue(initDPRate); extraVars.push_back(negDPRate_); initDPRate = posSigModel_->getDPRate().initValue(); posDPRate_.value(initDPRate); posDPRate_.genValue(initDPRate); posDPRate_.initValue(initDPRate); extraVars.push_back(posDPRate_); // Calculate the CPC and CPV Fit Fractions, ACPs and FitFrac asymmetries this->calcExtraFractions(kTRUE); this->calcAsymmetries(kTRUE); // Add the CP violating and CP conserving fit fractions for each signal component for (UInt_t i = 0; i < nSigComp_; i++) { for (UInt_t j = i; j < nSigComp_; j++) { extraVars.push_back(CPVFitFrac_[i][j]); } } for (UInt_t i = 0; i < nSigComp_; i++) { for (UInt_t j = i; j < nSigComp_; j++) { extraVars.push_back(CPCFitFrac_[i][j]); } } // 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]); } } void LauCPFitModel::calcExtraFractions(Bool_t initValues) { // Calculate the CP-conserving and CP-violating fit fractions if (initValues) { // create the structure CPCFitFrac_.clear(); CPVFitFrac_.clear(); CPCFitFrac_.resize(nSigComp_); CPVFitFrac_.resize(nSigComp_); for (UInt_t i(0); iacp(); LauAsymmCalc asymmCalc(negFitFrac_[i][i].value(), posFitFrac_[i][i].value()); Double_t asym = asymmCalc.getAsymmetry(); fitFracAsymm_[i].value(asym); if (initValues) { fitFracAsymm_[i].genValue(asym); fitFracAsymm_[i].initValue(asym); } } } void LauCPFitModel::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/b > 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(); } if (useSCF_ && !useSCFHist_) { scfFrac_.updatePull(); } if (usingBkgnd_ == kTRUE) { for (LauBkgndYieldList::iterator iter = bkgndEvents_.begin(); iter != bkgndEvents_.end(); ++iter) { std::vector parameters = (*iter)->getPars(); for ( LauParameter* parameter : parameters ) { parameter->updatePull(); } } for (LauBkgndYieldList::iterator iter = bkgndAsym_.begin(); iter != bkgndAsym_.end(); ++iter) { std::vector parameters = (*iter)->getPars(); for ( LauParameter* parameter : parameters ) { parameter->updatePull(); } } } // Update the pulls on all the extra PDFs' parameters this->updateFitParameters(negSignalPdfs_); this->updateFitParameters(posSignalPdfs_); if (useSCF_ == kTRUE) { this->updateFitParameters(negScfPdfs_); this->updateFitParameters(posScfPdfs_); } if (usingBkgnd_ == kTRUE) { for (LauBkgndPdfsList::iterator iter = negBkgndPdfs_.begin(); iter != negBkgndPdfs_.end(); ++iter) { this->updateFitParameters(*iter); } for (LauBkgndPdfsList::iterator iter = posBkgndPdfs_.begin(); iter != posBkgndPdfs_.end(); ++iter) { this->updateFitParameters(*iter); } } // 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(); negSigModel_->updateCoeffs(negCoeffs_); negSigModel_->calcExtraInfo(); posSigModel_->updateCoeffs(posCoeffs_); posSigModel_->calcExtraInfo(); LauParArray negFitFrac = negSigModel_->getFitFractions(); if (negFitFrac.size() != nSigComp_) { std::cerr << "ERROR in LauCPFitModel::finaliseFitResults : Fit Fraction array of unexpected dimension: " << negFitFrac.size() << std::endl; gSystem->Exit(EXIT_FAILURE); } for (UInt_t i(0); iExit(EXIT_FAILURE); } } LauParArray posFitFrac = posSigModel_->getFitFractions(); if (posFitFrac.size() != nSigComp_) { std::cerr << "ERROR in LauCPFitModel::finaliseFitResults : Fit Fraction array of unexpected dimension: " << posFitFrac.size() << std::endl; gSystem->Exit(EXIT_FAILURE); } for (UInt_t i(0); iExit(EXIT_FAILURE); } } LauParArray negFitFracEffUnCorr = negSigModel_->getFitFractionsEfficiencyUncorrected(); if (negFitFracEffUnCorr.size() != nSigComp_) { std::cerr << "ERROR in LauCPFitModel::finaliseFitResults : Fit Fraction array of unexpected dimension: " << negFitFracEffUnCorr.size() << std::endl; gSystem->Exit(EXIT_FAILURE); } for (UInt_t i(0); iExit(EXIT_FAILURE); } } LauParArray posFitFracEffUnCorr = posSigModel_->getFitFractionsEfficiencyUncorrected(); if (posFitFracEffUnCorr.size() != nSigComp_) { std::cerr << "ERROR in LauCPFitModel::finaliseFitResults : Fit Fraction array of unexpected dimension: " << posFitFracEffUnCorr.size() << std::endl; gSystem->Exit(EXIT_FAILURE); } for (UInt_t i(0); iExit(EXIT_FAILURE); } } for (UInt_t i(0); igetMeanEff().value()); posMeanEff_.value(posSigModel_->getMeanEff().value()); negDPRate_.value(negSigModel_->getDPRate().value()); posDPRate_.value(posSigModel_->getDPRate().value()); this->calcExtraFractions(); 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(); // Add the positive and negative fit fractions for each signal component for (UInt_t i(0); i negExtraPars = negSigModel_->getExtraParameters(); std::vector::iterator negExtraIter; for (negExtraIter = negExtraPars.begin(); negExtraIter != negExtraPars.end(); ++negExtraIter) { LauParameter negExtraParameter = (*negExtraIter); extraVars.push_back(negExtraParameter); } std::vector posExtraPars = posSigModel_->getExtraParameters(); std::vector::iterator posExtraIter; for (posExtraIter = posExtraPars.begin(); posExtraIter != posExtraPars.end(); ++posExtraIter) { LauParameter posExtraParameter = (*posExtraIter); extraVars.push_back(posExtraParameter); } extraVars.push_back(negMeanEff_); extraVars.push_back(posMeanEff_); extraVars.push_back(negDPRate_); extraVars.push_back(posDPRate_); for (UInt_t i = 0; i < nSigComp_; i++) { for (UInt_t j(i); jprintFitFractions(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 LauCPFitModel::printFitFractions(std::ostream& output) { // Print out Fit Fractions, total DP rate and mean efficiency // First for the B- events for (UInt_t i = 0; i < nSigComp_; i++) { const TString compName(coeffPars_[i]->name()); - output << negParent_ << " FitFraction for component " << i << " (" << compName << ") = " << negFitFrac_[i][i] << std::endl; + output << negParent_ << " FitFraction for component " << i << " (" << compName << ") = " << negFitFrac_[i][i].value() << std::endl; } - output << negParent_ << " overall DP rate (integral of matrix element squared) = " << negDPRate_ << std::endl; - output << negParent_ << " average efficiency weighted by whole DP dynamics = " << negMeanEff_ << std::endl; + output << negParent_ << " overall DP rate (integral of matrix element squared) = " << negDPRate_.value() << std::endl; + output << negParent_ << " average efficiency weighted by whole DP dynamics = " << negMeanEff_.value() << std::endl; // Then for the positive sample for (UInt_t i = 0; i < nSigComp_; i++) { const TString compName(coeffPars_[i]->name()); const TString conjName(negSigModel_->getConjResName(compName)); - output << posParent_ << " FitFraction for component " << i << " (" << conjName << ") = " << posFitFrac_[i][i] << std::endl; + output << posParent_ << " FitFraction for component " << i << " (" << conjName << ") = " << posFitFrac_[i][i].value() << std::endl; } - output << posParent_ << " overall DP rate (integral of matrix element squared) = " << posDPRate_ << std::endl; - output << posParent_ << " average efficiency weighted by whole DP dynamics = " << posMeanEff_ << std::endl; + output << posParent_ << " overall DP rate (integral of matrix element squared) = " << posDPRate_.value() << std::endl; + output << posParent_ << " average efficiency weighted by whole DP dynamics = " << posMeanEff_.value() << std::endl; } void LauCPFitModel::printAsymmetries(std::ostream& output) { for (UInt_t i = 0; i < nSigComp_; i++) { const TString compName(coeffPars_[i]->name()); - output << "Fit Fraction asymmetry for component " << i << " (" << compName << ") = " << fitFracAsymm_[i] << std::endl; + output << "Fit Fraction asymmetry for component " << i << " (" << compName << ") = " << fitFracAsymm_[i].value() << std::endl; } for (UInt_t i = 0; i < nSigComp_; i++) { const TString compName(coeffPars_[i]->name()); - output << "ACP for component " << i << " (" << compName << ") = " << acp_[i] << std::endl; + output << "ACP for component " << i << " (" << compName << ") = " << acp_[i].value() << std::endl; } } void LauCPFitModel::writeOutTable(const TString& outputFile) { // Write out the results of the fit to a tex-readable table // TODO - need to include the yields in this table std::ofstream fout(outputFile); LauPrint print; std::cout << "INFO in LauCPFitModel::writeOutTable : Writing out results of the fit to the tex file " << outputFile << std::endl; if (this->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" << std::endl; fout << "\\end{tabular}" << std::endl << std::endl; // print the fit fractions and asymmetries in another fout << "\\begin{tabular}{|l|c|c|c|c|}" << std::endl; fout << "\\hline" << std::endl; fout << "Component & " << negParent_ << " Fit Fraction & " << posParent_ << " Fit Fraction & Fit Fraction Asymmetry & ACP \\\\" << std::endl; fout << "\\hline" << std::endl; Double_t negFitFracSum(0.0); Double_t posFitFracSum(0.0); for (UInt_t i = 0; i < nSigComp_; i++) { TString resName = coeffPars_[i]->name(); resName = resName.ReplaceAll("_", "\\_"); Double_t negFitFrac = negFitFrac_[i][i].value(); Double_t posFitFrac = posFitFrac_[i][i].value(); negFitFracSum += negFitFrac; posFitFracSum += posFitFrac; Double_t fitFracAsymm = fitFracAsymm_[i].value(); Double_t acp = acp_[i].value(); Double_t acpErr = acp_[i].error(); fout << resName << " & $"; print.printFormat(fout, negFitFrac); fout << "$ & $"; print.printFormat(fout, posFitFrac); fout << "$ & $"; print.printFormat(fout, fitFracAsymm); fout << "$ & $"; print.printFormat(fout, acp); fout << " \\pm "; print.printFormat(fout, acpErr); fout << "$ \\\\" << std::endl; } fout << "\\hline" << std::endl; // Also print out sum of fit fractions fout << "Fit Fraction Sum & $"; print.printFormat(fout, negFitFracSum); fout << "$ & $"; print.printFormat(fout, posFitFracSum); fout << "$ & & \\\\" << std::endl; fout << "\\hline" << std::endl; fout << "DP rate & $"; print.printFormat(fout, negDPRate_.value()); fout << "$ & $"; print.printFormat(fout, posDPRate_.value()); fout << "$ & & \\\\" << std::endl; fout << "$< \\varepsilon > $ & $"; print.printFormat(fout, negMeanEff_.value()); fout << "$ & $"; print.printFormat(fout, posMeanEff_.value()); fout << "$ & & \\\\" << std::endl; fout << "\\hline" << std::endl; fout << "\\end{tabular}" << std::endl << std::endl; } if (!negSignalPdfs_.empty()) { fout << "\\begin{tabular}{|l|c|}" << std::endl; fout << "\\hline" << std::endl; if (useSCF_ == kTRUE) { fout << "\\Extra TM Signal PDFs' Parameters: & \\\\" << std::endl; } else { fout << "\\Extra Signal PDFs' Parameters: & \\\\" << std::endl; } this->printFitParameters(negSignalPdfs_, fout); if ( tagged_ ) { this->printFitParameters(posSignalPdfs_, fout); } if (useSCF_ == kTRUE && !negScfPdfs_.empty()) { fout << "\\hline" << std::endl; fout << "\\Extra SCF Signal PDFs' Parameters: & \\\\" << std::endl; this->printFitParameters(negScfPdfs_, fout); if ( tagged_ ) { this->printFitParameters(posScfPdfs_, fout); } } if (usingBkgnd_ == kTRUE && !negBkgndPdfs_.empty()) { fout << "\\hline" << std::endl; fout << "\\Extra Background PDFs' Parameters: & \\\\" << std::endl; for (LauBkgndPdfsList::const_iterator iter = negBkgndPdfs_.begin(); iter != negBkgndPdfs_.end(); ++iter) { this->printFitParameters(*iter, fout); } if ( tagged_ ) { for (LauBkgndPdfsList::const_iterator iter = posBkgndPdfs_.begin(); iter != posBkgndPdfs_.end(); ++iter) { this->printFitParameters(*iter, fout); } } } fout << "\\hline \n\\end{tabular}" << std::endl << std::endl; } } void LauCPFitModel::checkInitFitParams() { // Update the number of signal events to be total-sum(background events) this->updateSigEvents(); // Check whether we want to have randomised initial fit parameters for the signal model if (this->useRandomInitFitPars() == kTRUE) { std::cout << "INFO in LauCPFitModel::checkInitFitParams : Setting random parameters for the signal model" << std::endl; this->randomiseInitFitPars(); } } void LauCPFitModel::randomiseInitFitPars() { // Only randomise those parameters that are not fixed! std::cout << "INFO in LauCPFitModel::randomiseInitFitPars : Randomising the initial fit magnitudes and phases of the components..." << std::endl; if ( fixParamFileName_.IsNull() && fixParamMap_.empty() ) { // No params are imported - randomise as normal for (UInt_t i = 0; i < nSigComp_; i++) { coeffPars_[i]->randomiseInitValues(); } } else { // Only randomise those that are not imported (i.e., not found in allImportedFreeParams_) // by temporarily fixing all imported parameters, and then freeing those not set to be fixed when imported, // except those that are previously set to be fixed anyhow. // Convoluted, but beats changing the behaviour of functions that call checkInitFitParams or the coeffSet // itself. for (auto p : allImportedFreeParams_) { p->fixed(kTRUE); } for (UInt_t i = 0; i < nSigComp_; i++) { coeffPars_[i]->randomiseInitValues(); } for (auto p : allImportedFreeParams_) { p->fixed(kFALSE); } } } std::pair LauCPFitModel::eventsToGenerate() { // Determine the number of events to generate for each hypothesis // If we're smearing then smear each one individually LauGenInfo nEvtsGen; // Keep track of whether any yield or asymmetry parameters are blinded Bool_t blind = kFALSE; // Signal if ( signalEvents_->blind() ) { blind = kTRUE; } Double_t evtWeight(1.0); Double_t nEvts = signalEvents_->genValue(); if ( nEvts < 0.0 ) { evtWeight = -1.0; nEvts = TMath::Abs( nEvts ); } Double_t sigAsym(0.0); // need to include this as an alternative in case the DP isn't in the model if ( !this->useDP() || forceAsym_ ) { sigAsym = signalAsym_->genValue(); if ( signalAsym_->blind() ) { blind = kTRUE; } } else { Double_t negRate = negSigModel_->getDPNorm(); Double_t posRate = posSigModel_->getDPNorm(); if (negRate+posRate>1e-30) { sigAsym = (negRate-posRate)/(negRate+posRate); } } Double_t nPosEvts = (nEvts/2.0 * (1.0 - sigAsym)); Double_t nNegEvts = (nEvts/2.0 * (1.0 + sigAsym)); Int_t nPosEvtsToGen { static_cast(nPosEvts) }; Int_t nNegEvtsToGen { static_cast(nNegEvts) }; if (this->doPoissonSmearing()) { nPosEvtsToGen = LauRandom::randomFun()->Poisson(nPosEvts); nNegEvtsToGen = LauRandom::randomFun()->Poisson(nNegEvts); } nEvtsGen[std::make_pair("signal",+1)] = std::make_pair(nPosEvtsToGen,evtWeight); nEvtsGen[std::make_pair("signal",-1)] = std::make_pair(nNegEvtsToGen,evtWeight); // backgrounds const UInt_t nBkgnds = this->nBkgndClasses(); for ( UInt_t bkgndID(0); bkgndID < nBkgnds; ++bkgndID ) { const LauAbsRValue* evtsPar = bkgndEvents_[bkgndID]; const LauAbsRValue* asymPar = bkgndAsym_[bkgndID]; if ( evtsPar->blind() || asymPar->blind() ) { blind = kTRUE; } evtWeight = 1.0; nEvts = evtsPar->genValue(); if ( nEvts < 0 ) { evtWeight = -1.0; nEvts = TMath::Abs( nEvts ); } const Double_t asym = asymPar->genValue(); nPosEvts = (nEvts/2.0 * (1.0 - asym)); nNegEvts = (nEvts/2.0 * (1.0 + asym)); nPosEvtsToGen = static_cast(nPosEvts); nNegEvtsToGen = static_cast(nNegEvts); if (this->doPoissonSmearing()) { nPosEvtsToGen = LauRandom::randomFun()->Poisson(nPosEvts); nNegEvtsToGen = LauRandom::randomFun()->Poisson(nNegEvts); } const TString& bkgndClass = this->bkgndClassName(bkgndID); nEvtsGen[std::make_pair(bkgndClass,+1)] = std::make_pair(nPosEvtsToGen,evtWeight); nEvtsGen[std::make_pair(bkgndClass,-1)] = std::make_pair(nNegEvtsToGen,evtWeight); } // Print out the information on what we're generating, but only if none of the parameters are blind (otherwise we risk unblinding them!) if ( !blind ) { std::cout << "INFO in LauCPFitModel::eventsToGenerate : Generating toy MC with:" << std::endl; std::cout << " : Signal asymmetry = " << sigAsym << " and number of signal events = " << signalEvents_->genValue() << std::endl; for ( UInt_t bkgndID(0); bkgndID < nBkgnds; ++bkgndID ) { const TString& bkgndClass = this->bkgndClassName(bkgndID); const LauAbsRValue* evtsPar = bkgndEvents_[bkgndID]; const LauAbsRValue* asymPar = bkgndAsym_[bkgndID]; std::cout << " : " << bkgndClass << " asymmetry = " << asymPar->genValue() << " and number of " << bkgndClass << " events = " << evtsPar->genValue() << std::endl; } } return std::make_pair( nEvtsGen, blind ); } Bool_t LauCPFitModel::genExpt() { // Routine to generate toy Monte Carlo events according to the various models we have defined. // Determine the number of events to generate for each hypothesis std::pair info = this->eventsToGenerate(); LauGenInfo nEvts = info.first; const Bool_t blind = info.second; 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; } const Bool_t storeSCFTruthInfo = ( useSCF_ || ( this->enableEmbedding() && negSignalTree_ != 0 && negSignalTree_->haveBranch("mcMatch") && posSignalTree_ != 0 && posSignalTree_->haveBranch("mcMatch") ) ); // Loop over the hypotheses and generate the requested number of events for each one for (LauGenInfo::const_iterator iter = nEvts.begin(); iter != nEvts.end(); ++iter) { const TString& type(iter->first.first); curEvtCharge_ = iter->first.second; Double_t evtWeight( iter->second.second ); Int_t nEvtsGen( iter->second.first ); for (Int_t iEvt(0); iEvtsetGenNtupleDoubleBranchValue( "evtWeight", evtWeight ); this->setGenNtupleDoubleBranchValue( "efficiency", 1.0 ); if (type == "signal") { this->setGenNtupleIntegerBranchValue("genSig",1); for ( UInt_t iBkgnd(0); iBkgnd < nBkgnds; ++iBkgnd ) { this->setGenNtupleIntegerBranchValue( bkgndClassNamesGen[iBkgnd], 0 ); } genOK = this->generateSignalEvent(); if ( curEvtCharge_ > 0 ){ this->setGenNtupleDoubleBranchValue( "efficiency", posSigModel_->getEvtEff() ); } else { this->setGenNtupleDoubleBranchValue( "efficiency", negSigModel_->getEvtEff() ); } } else { this->setGenNtupleIntegerBranchValue("genSig",0); if ( storeSCFTruthInfo ) { this->setGenNtupleIntegerBranchValue("genTMSig",0); this->setGenNtupleIntegerBranchValue("genSCFSig",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->setDPBranchValues(); } // Store the event charge this->setGenNtupleIntegerBranchValue(tagVarName_,curEvtCharge_); // Store the event number (within this experiment) // and then increment it this->setGenNtupleIntegerBranchValue("iEvtWithinExpt",evtNum); ++evtNum; this->fillGenNtupleBranches(); if ( !blind && (iEvt%500 == 0) ) { std::cout << "INFO in LauCPFitModel::genExpt : Generated event number " << iEvt << " out of " << nEvtsGen << " " << type << " events." << std::endl; } } if (!genOK) { break; } } if (this->useDP() && genOK) { negSigModel_->checkToyMC(kTRUE,kTRUE); posSigModel_->checkToyMC(kTRUE,kTRUE); // Get the fit fractions if they're to be written into the latex table if (this->writeLatexTable()) { LauParArray negFitFrac = negSigModel_->getFitFractions(); if (negFitFrac.size() != nSigComp_) { std::cerr << "ERROR in LauCPFitModel::genExpt : Fit Fraction array of unexpected dimension: " << negFitFrac.size() << std::endl; gSystem->Exit(EXIT_FAILURE); } for (UInt_t i(0); iExit(EXIT_FAILURE); } } LauParArray posFitFrac = posSigModel_->getFitFractions(); if (posFitFrac.size() != nSigComp_) { std::cerr << "ERROR in LauCPFitModel::genExpt : Fit Fraction array of unexpected dimension: " << posFitFrac.size() << std::endl; gSystem->Exit(EXIT_FAILURE); } for (UInt_t i(0); iExit(EXIT_FAILURE); } } for (UInt_t i(0); igetMeanEff().value()); posMeanEff_.value(posSigModel_->getMeanEff().value()); negDPRate_.value(negSigModel_->getDPRate().value()); posDPRate_.value(posSigModel_->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 (negSignalTree_) { negSignalTree_->clearUsedList(); } if (posSignalTree_) { posSignalTree_->clearUsedList(); } } for ( UInt_t bkgndID(0); bkgndID < nBkgnds; ++bkgndID ) { LauEmbeddedData* data = negBkgndTree_[bkgndID]; if (reuseBkgnd_[bkgndID] || !genOK) { if (data) { data->clearUsedList(); } } } for ( UInt_t bkgndID(0); bkgndID < nBkgnds; ++bkgndID ) { LauEmbeddedData* data = posBkgndTree_[bkgndID]; if (reuseBkgnd_[bkgndID] || !genOK) { if (data) { data->clearUsedList(); } } } return genOK; } Bool_t LauCPFitModel::generateSignalEvent() { // Generate signal event Bool_t genOK(kTRUE); Bool_t genSCF(kFALSE); LauIsobarDynamics* model(0); LauKinematics* kinematics(0); LauEmbeddedData* embeddedData(0); LauPdfPList* sigPdfs(0); LauPdfPList* scfPdfs(0); Bool_t doReweighting(kFALSE); if (curEvtCharge_<0) { model = negSigModel_; kinematics = negKinematics_; sigPdfs = &negSignalPdfs_; scfPdfs = &negScfPdfs_; if (this->enableEmbedding()) { embeddedData = negSignalTree_; doReweighting = useNegReweighting_; } } else { model = posSigModel_; kinematics = posKinematics_; if ( tagged_ ) { sigPdfs = &posSignalPdfs_; scfPdfs = &posScfPdfs_; } else { sigPdfs = &negSignalPdfs_; scfPdfs = &negScfPdfs_; } if (this->enableEmbedding()) { embeddedData = posSignalTree_; doReweighting = usePosReweighting_; } } if (this->useDP()) { if (embeddedData) { if (doReweighting) { // Select a (random) event from the generated data. Then store the // reconstructed DP co-ords, together with other pdf information, // as the embedded data. genOK = embeddedData->getReweightedEvent(model); } else { // Just get the information of a (randomly) selected event in the // embedded data embeddedData->getEmbeddedEvent(kinematics); } genSCF = this->storeSignalMCMatch( embeddedData ); } else { genOK = model->generate(); if ( genOK && useSCF_ ) { Double_t frac(0.0); if ( useSCFHist_ ) { frac = scfFracHist_->calcEfficiency( kinematics ); } else { frac = scfFrac_.genValue(); } if ( frac < LauRandom::randomFun()->Rndm() ) { this->setGenNtupleIntegerBranchValue("genTMSig",1); this->setGenNtupleIntegerBranchValue("genSCFSig",0); genSCF = kFALSE; } else { this->setGenNtupleIntegerBranchValue("genTMSig",0); this->setGenNtupleIntegerBranchValue("genSCFSig",1); genSCF = kTRUE; // Optionally smear the DP position // of the SCF event if ( scfMap_ != 0 ) { Double_t xCoord(0.0), yCoord(0.0); if ( kinematics->squareDP() ) { xCoord = kinematics->getmPrime(); yCoord = kinematics->getThetaPrime(); } else { xCoord = kinematics->getm13Sq(); yCoord = kinematics->getm23Sq(); } // Find the bin number where this event is generated Int_t binNo = scfMap_->binNumber( xCoord, yCoord ); // Retrieve the migration histogram TH2* histo = scfMap_->trueHist( binNo ); const LauAbsEffModel * effModel = model->getEffModel(); do { // Get a random point from the histogram histo->GetRandom2( xCoord, yCoord ); // Update the kinematics if ( kinematics->squareDP() ) { kinematics->updateSqDPKinematics( xCoord, yCoord ); } else { kinematics->updateKinematics( xCoord, yCoord ); } } while ( ! effModel->passVeto( kinematics ) ); } } } } } else { if (embeddedData) { embeddedData->getEmbeddedEvent(0); genSCF = this->storeSignalMCMatch( embeddedData ); } else if ( useSCF_ ) { Double_t frac = scfFrac_.genValue(); if ( frac < LauRandom::randomFun()->Rndm() ) { this->setGenNtupleIntegerBranchValue("genTMSig",1); this->setGenNtupleIntegerBranchValue("genSCFSig",0); genSCF = kFALSE; } else { this->setGenNtupleIntegerBranchValue("genTMSig",0); this->setGenNtupleIntegerBranchValue("genSCFSig",1); genSCF = kTRUE; } } } if (genOK) { if ( useSCF_ ) { if ( genSCF ) { this->generateExtraPdfValues(scfPdfs, embeddedData); } else { this->generateExtraPdfValues(sigPdfs, embeddedData); } } else { this->generateExtraPdfValues(sigPdfs, embeddedData); } } // Check for problems with the embedding if (embeddedData && (embeddedData->nEvents() == embeddedData->nUsedEvents())) { std::cerr << "WARNING in LauCPFitModel::generateSignalEvent : Source of embedded signal events used up, clearing the list of used events." << std::endl; embeddedData->clearUsedList(); } return genOK; } Bool_t LauCPFitModel::generateBkgndEvent(UInt_t bkgndID) { // Generate Bkgnd event Bool_t genOK(kTRUE); LauAbsBkgndDPModel* model(0); LauEmbeddedData* embeddedData(0); LauPdfPList* extraPdfs(0); LauKinematics* kinematics(0); if (curEvtCharge_<0) { model = negBkgndDPModels_[bkgndID]; if (this->enableEmbedding()) { embeddedData = negBkgndTree_[bkgndID]; } extraPdfs = &negBkgndPdfs_[bkgndID]; kinematics = negKinematics_; } else { model = posBkgndDPModels_[bkgndID]; if (this->enableEmbedding()) { embeddedData = posBkgndTree_[bkgndID]; } if ( tagged_ ) { extraPdfs = &posBkgndPdfs_[bkgndID]; } else { extraPdfs = &negBkgndPdfs_[bkgndID]; } kinematics = posKinematics_; } 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(); } return genOK; } void LauCPFitModel::setupGenNtupleBranches() { // Setup the required ntuple branches this->addGenNtupleDoubleBranch("evtWeight"); this->addGenNtupleIntegerBranch("genSig"); this->addGenNtupleDoubleBranch("efficiency"); if ( useSCF_ || ( this->enableEmbedding() && negSignalTree_ != 0 && negSignalTree_->haveBranch("mcMatch") && posSignalTree_ != 0 && posSignalTree_->haveBranch("mcMatch") ) ) { this->addGenNtupleIntegerBranch("genTMSig"); this->addGenNtupleIntegerBranch("genSCFSig"); } const UInt_t nBkgnds = this->nBkgndClasses(); for ( UInt_t iBkgnd(0); iBkgnd < nBkgnds; ++iBkgnd ) { TString name( this->bkgndClassName(iBkgnd) ); name.Prepend("gen"); this->addGenNtupleIntegerBranch(name); } this->addGenNtupleIntegerBranch("charge"); if (this->useDP() == kTRUE) { 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 (negKinematics_->squareDP() && posKinematics_->squareDP()) { this->addGenNtupleDoubleBranch("mPrime"); this->addGenNtupleDoubleBranch("thPrime"); } } for (LauPdfPList::const_iterator pdf_iter = negSignalPdfs_.begin(); pdf_iter != negSignalPdfs_.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" ) { this->addGenNtupleDoubleBranch( (*var_iter) ); } } } } void LauCPFitModel::setDPBranchValues() { LauKinematics* kinematics(0); if (curEvtCharge_<0) { kinematics = negKinematics_; } else { kinematics = posKinematics_; } // 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()); } } void LauCPFitModel::generateExtraPdfValues(LauPdfPList* extraPdfs, LauEmbeddedData* embeddedData) { LauKinematics* kinematics(0); if (curEvtCharge_<0) { kinematics = negKinematics_; } else { kinematics = posKinematics_; } if (!extraPdfs) { std::cerr << "ERROR in LauCPFitModel::generateExtraPdfValues : Null pointer to PDF list." << std::endl; gSystem->Exit(EXIT_FAILURE); } if (extraPdfs->empty()) { //std::cerr << "WARNING in LauCPFitModel::generateExtraPdfValues : PDF list is empty." << std::endl; return; } // Generate from the extra PDFs for (LauPdfPList::iterator pdf_iter = extraPdfs->begin(); pdf_iter != extraPdfs->end(); ++pdf_iter) { LauFitData genValues; if (embeddedData) { genValues = embeddedData->getValues( (*pdf_iter)->varNames() ); } else { genValues = (*pdf_iter)->generate(kinematics); } for ( LauFitData::const_iterator var_iter = genValues.begin(); var_iter != genValues.end(); ++var_iter ) { TString varName = var_iter->first; if ( varName != "m13Sq" && varName != "m23Sq" ) { Double_t value = var_iter->second; this->setGenNtupleDoubleBranchValue(varName,value); } } } } Bool_t LauCPFitModel::storeSignalMCMatch(LauEmbeddedData* embeddedData) { // Default to TM Bool_t genSCF(kFALSE); Int_t match(1); // Check that we have a valid pointer and that embedded data has // the mcMatch branch. If so then get the match value. if ( embeddedData && embeddedData->haveBranch("mcMatch") ) { match = TMath::Nint( embeddedData->getValue("mcMatch") ); } // Set the variables accordingly. if (match) { this->setGenNtupleIntegerBranchValue("genTMSig",1); this->setGenNtupleIntegerBranchValue("genSCFSig",0); genSCF = kFALSE; } else { this->setGenNtupleIntegerBranchValue("genTMSig",0); this->setGenNtupleIntegerBranchValue("genSCFSig",1); genSCF = kTRUE; } return genSCF; } void LauCPFitModel::propagateParUpdates() { // Update the signal parameters and then the total normalisation for the signal likelihood if (this->useDP() == kTRUE) { this->updateCoeffs(); negSigModel_->updateCoeffs(negCoeffs_); posSigModel_->updateCoeffs(posCoeffs_); } // Update the signal fraction from the background fractions if not doing an extended fit if ( !this->doEMLFit() && !signalEvents_->fixed() ) { this->updateSigEvents(); } } void LauCPFitModel::updateSigEvents() { // The background parameters will have been set from Minuit. // We need to update the signal events using these. Double_t nTotEvts = this->eventsPerExpt(); signalEvents_->range(-2.0*nTotEvts,2.0*nTotEvts); for (LauBkgndYieldList::iterator iter = bkgndEvents_.begin(); iter != bkgndEvents_.end(); ++iter) { LauAbsRValue* nBkgndEvents = (*iter); if ( nBkgndEvents->isLValue() ) { LauParameter* yield = dynamic_cast( nBkgndEvents ); yield->range(-2.0*nTotEvts,2.0*nTotEvts); } } if (signalEvents_->fixed()) { return; } // Subtract background events (if any) from signal. Double_t signalEvents = nTotEvts; if (usingBkgnd_ == kTRUE) { for (LauBkgndYieldList::const_iterator iter = bkgndEvents_.begin(); iter != bkgndEvents_.end(); ++iter) { signalEvents -= (*iter)->value(); } } signalEvents_->value(signalEvents); } void LauCPFitModel::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(); // First the Dalitz plot variables (m_ij^2) if (this->useDP() == kTRUE) { // need to append SCF smearing bins before caching DP amplitudes if ( scfMap_ != 0 ) { this->appendBinCentres( inputFitData ); } negSigModel_->fillDataTree(*inputFitData); posSigModel_->fillDataTree(*inputFitData); if (usingBkgnd_ == kTRUE) { for (LauBkgndDPModelList::iterator iter = negBkgndDPModels_.begin(); iter != negBkgndDPModels_.end(); ++iter) { (*iter)->fillDataTree(*inputFitData); } for (LauBkgndDPModelList::iterator iter = posBkgndDPModels_.begin(); iter != posBkgndDPModels_.end(); ++iter) { (*iter)->fillDataTree(*inputFitData); } } } // ...and then the extra PDFs this->cacheInfo(negSignalPdfs_, *inputFitData); this->cacheInfo(negScfPdfs_, *inputFitData); for (LauBkgndPdfsList::iterator iter = negBkgndPdfs_.begin(); iter != negBkgndPdfs_.end(); ++iter) { this->cacheInfo((*iter), *inputFitData); } if ( tagged_ ) { this->cacheInfo(posSignalPdfs_, *inputFitData); this->cacheInfo(posScfPdfs_, *inputFitData); for (LauBkgndPdfsList::iterator iter = posBkgndPdfs_.begin(); iter != posBkgndPdfs_.end(); ++iter) { this->cacheInfo((*iter), *inputFitData); } } // the SCF fractions and jacobians if ( useSCF_ && useSCFHist_ ) { if ( !inputFitData->haveBranch( "m13Sq" ) || !inputFitData->haveBranch( "m23Sq" ) ) { std::cerr << "ERROR in LauCPFitModel::cacheInputFitVars : Input data does not contain DP branches and so can't cache the SCF fraction." << std::endl; gSystem->Exit(EXIT_FAILURE); } UInt_t nEvents = inputFitData->nEvents(); recoSCFFracs_.clear(); recoSCFFracs_.reserve( nEvents ); if ( negKinematics_->squareDP() ) { recoJacobians_.clear(); recoJacobians_.reserve( nEvents ); } for (UInt_t iEvt = 0; iEvt < nEvents; iEvt++) { const LauFitData& dataValues = inputFitData->getData(iEvt); LauFitData::const_iterator m13_iter = dataValues.find("m13Sq"); LauFitData::const_iterator m23_iter = dataValues.find("m23Sq"); negKinematics_->updateKinematics( m13_iter->second, m23_iter->second ); Double_t scfFrac = scfFracHist_->calcEfficiency( negKinematics_ ); recoSCFFracs_.push_back( scfFrac ); if ( negKinematics_->squareDP() ) { recoJacobians_.push_back( negKinematics_->calcSqDPJacobian() ); } } } // finally cache the event charge evtCharges_.clear(); if ( tagged_ ) { if ( !inputFitData->haveBranch( tagVarName_ ) ) { std::cerr << "ERROR in LauCPFitModel::cacheInputFitVars : Input data does not contain branch \"" << tagVarName_ << "\"." << std::endl; gSystem->Exit(EXIT_FAILURE); } UInt_t nEvents = inputFitData->nEvents(); evtCharges_.reserve( nEvents ); for (UInt_t iEvt = 0; iEvt < nEvents; iEvt++) { const LauFitData& dataValues = inputFitData->getData(iEvt); LauFitData::const_iterator iter = dataValues.find( tagVarName_ ); curEvtCharge_ = static_cast( iter->second ); evtCharges_.push_back( curEvtCharge_ ); } } } void LauCPFitModel::appendBinCentres( LauFitDataTree* inputData ) { // We'll be caching the DP amplitudes and efficiencies of the centres of the true bins. // To do so, we attach some fake points at the end of inputData, the number of the entry // minus the total number of events corresponding to the number of the histogram for that // given true bin in the LauScfMap object. (What this means is that when Laura is provided with // the LauScfMap object by the user, it's the latter who has to make sure that it contains the // right number of histograms and in exactly the right order!) // Get the x and y co-ordinates of the bin centres std::vector binCentresXCoords; std::vector binCentresYCoords; scfMap_->listBinCentres(binCentresXCoords, binCentresYCoords); // The SCF histograms could be in square Dalitz plot histograms. // The dynamics takes normal Dalitz plot coords, so we might have to convert them back. Bool_t sqDP = negKinematics_->squareDP(); UInt_t nBins = binCentresXCoords.size(); fakeSCFFracs_.clear(); fakeSCFFracs_.reserve( nBins ); if ( sqDP ) { fakeJacobians_.clear(); fakeJacobians_.reserve( nBins ); } for (UInt_t iBin = 0; iBin < nBins; ++iBin) { if ( sqDP ) { negKinematics_->updateSqDPKinematics(binCentresXCoords[iBin],binCentresYCoords[iBin]); binCentresXCoords[iBin] = negKinematics_->getm13Sq(); binCentresYCoords[iBin] = negKinematics_->getm23Sq(); fakeJacobians_.push_back( negKinematics_->calcSqDPJacobian() ); } else { negKinematics_->updateKinematics(binCentresXCoords[iBin],binCentresYCoords[iBin]); } fakeSCFFracs_.push_back( scfFracHist_->calcEfficiency( negKinematics_ ) ); } // Set up inputFitVars_ object to hold the fake events inputData->appendFakePoints(binCentresXCoords,binCentresYCoords); } Double_t LauCPFitModel::getTotEvtLikelihood(UInt_t iEvt) { // Find out whether we have B- or B+ if ( tagged_ ) { curEvtCharge_ = evtCharges_[iEvt]; // check that the charge is either +1 or -1 if (TMath::Abs(curEvtCharge_)!=1) { std::cerr << "ERROR in LauCPFitModel::getTotEvtLikelihood : Charge/tag not accepted value: " << curEvtCharge_ << std::endl; if (curEvtCharge_>0) { curEvtCharge_ = +1; } else { curEvtCharge_ = -1; } std::cerr << " : Making it: " << curEvtCharge_ << "." << std::endl; } } // Get the DP likelihood for signal and backgrounds this->getEvtDPLikelihood(iEvt); // Get the combined extra PDFs likelihood for signal and backgrounds this->getEvtExtraLikelihoods(iEvt); // If appropriate, combine the TM and SCF likelihoods Double_t sigLike = sigDPLike_ * sigExtraLike_; if ( useSCF_ ) { Double_t scfFrac(0.0); if (useSCFHist_) { scfFrac = recoSCFFracs_[iEvt]; } else { scfFrac = scfFrac_.unblindValue(); } sigLike *= (1.0 - scfFrac); if ( (scfMap_ != 0) && (this->useDP() == kTRUE) ) { // if we're smearing the SCF DP PDF then the SCF frac // is already included in the SCF DP likelihood sigLike += (scfDPLike_ * scfExtraLike_); } else { sigLike += (scfFrac * scfDPLike_ * scfExtraLike_); } } // Get the correct event fractions depending on the charge // Signal asymmetry is built into the DP model... but when the DP // isn't in the fit we need an explicit parameter Double_t signalEvents = signalEvents_->unblindValue() * 0.5; if (this->useDP() == kFALSE) { signalEvents *= (1.0 - curEvtCharge_ * signalAsym_->unblindValue()); } // Construct the total event likelihood Double_t likelihood(0.0); if (usingBkgnd_) { likelihood = sigLike*signalEvents; const UInt_t nBkgnds = this->nBkgndClasses(); for ( UInt_t bkgndID(0); bkgndID < nBkgnds; ++bkgndID ) { Double_t bkgndEvents = bkgndEvents_[bkgndID]->unblindValue() * 0.5 * (1.0 - curEvtCharge_ * bkgndAsym_[bkgndID]->unblindValue()); likelihood += bkgndEvents*bkgndDPLike_[bkgndID]*bkgndExtraLike_[bkgndID]; } } else { likelihood = sigLike*0.5; } return likelihood; } Double_t LauCPFitModel::getEventSum() const { Double_t eventSum(0.0); eventSum += signalEvents_->unblindValue(); if (usingBkgnd_) { for (LauBkgndYieldList::const_iterator iter = bkgndEvents_.begin(); iter != bkgndEvents_.end(); ++iter) { eventSum += (*iter)->unblindValue(); } } return eventSum; } void LauCPFitModel::getEvtDPLikelihood(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; scfDPLike_ = 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; } const UInt_t nBkgnds = this->nBkgndClasses(); if ( tagged_ ) { if (curEvtCharge_==+1) { posSigModel_->calcLikelihoodInfo(iEvt); sigDPLike_ = posSigModel_->getEvtIntensity(); for ( UInt_t bkgndID(0); bkgndID < nBkgnds; ++bkgndID ) { if (usingBkgnd_ == kTRUE) { bkgndDPLike_[bkgndID] = posBkgndDPModels_[bkgndID]->getLikelihood(iEvt); } else { bkgndDPLike_[bkgndID] = 0.0; } } } else { negSigModel_->calcLikelihoodInfo(iEvt); sigDPLike_ = negSigModel_->getEvtIntensity(); for ( UInt_t bkgndID(0); bkgndID < nBkgnds; ++bkgndID ) { if (usingBkgnd_ == kTRUE) { bkgndDPLike_[bkgndID] = negBkgndDPModels_[bkgndID]->getLikelihood(iEvt); } else { bkgndDPLike_[bkgndID] = 0.0; } } } } else { posSigModel_->calcLikelihoodInfo(iEvt); negSigModel_->calcLikelihoodInfo(iEvt); sigDPLike_ = 0.5 * ( posSigModel_->getEvtIntensity() + negSigModel_->getEvtIntensity() ); for ( UInt_t bkgndID(0); bkgndID < nBkgnds; ++bkgndID ) { if (usingBkgnd_ == kTRUE) { bkgndDPLike_[bkgndID] = 0.5 * ( posBkgndDPModels_[bkgndID]->getLikelihood(iEvt) + negBkgndDPModels_[bkgndID]->getLikelihood(iEvt) ); } else { bkgndDPLike_[bkgndID] = 0.0; } } } if ( useSCF_ == kTRUE ) { if ( scfMap_ == 0 ) { // we're not smearing the SCF DP position // so the likelihood is the same as the TM scfDPLike_ = sigDPLike_; } else { // calculate the smeared SCF DP likelihood scfDPLike_ = this->getEvtSCFDPLikelihood(iEvt); } } // Calculate the signal normalisation // NB the 2.0 is there so that the 0.5 factor is applied to // signal and background in the same place otherwise you get // normalisation problems when you switch off the DP in the fit Double_t norm = negSigModel_->getDPNorm() + posSigModel_->getDPNorm(); sigDPLike_ *= 2.0/norm; scfDPLike_ *= 2.0/norm; } Double_t LauCPFitModel::getEvtSCFDPLikelihood(UInt_t iEvt) { Double_t scfDPLike(0.0); Double_t recoJacobian(1.0); Double_t xCoord(0.0); Double_t yCoord(0.0); Bool_t squareDP = negKinematics_->squareDP(); if ( squareDP ) { xCoord = negSigModel_->getEvtmPrime(); yCoord = negSigModel_->getEvtthPrime(); recoJacobian = recoJacobians_[iEvt]; } else { xCoord = negSigModel_->getEvtm13Sq(); yCoord = negSigModel_->getEvtm23Sq(); } // Find the bin that our reco event falls in Int_t recoBin = scfMap_->binNumber( xCoord, yCoord ); // Find out which true Bins contribute to the given reco bin const std::vector* trueBins = scfMap_->trueBins(recoBin); const Int_t nDataEvents = this->eventsPerExpt(); // Loop over the true bins for (std::vector::const_iterator iter = trueBins->begin(); iter != trueBins->end(); ++iter) { Int_t trueBin = (*iter); // prob of a true event in the given true bin migrating to the reco bin Double_t pRecoGivenTrue = scfMap_->prob( recoBin, trueBin ); Double_t pTrue(0.0); // We've cached the DP amplitudes and the efficiency for the // true bin centres, just after the data points if ( tagged_ ) { LauIsobarDynamics* sigModel(0); if (curEvtCharge_<0) { sigModel = negSigModel_; } else { sigModel = posSigModel_; } sigModel->calcLikelihoodInfo( nDataEvents + trueBin ); pTrue = sigModel->getEvtIntensity(); } else { posSigModel_->calcLikelihoodInfo( nDataEvents + trueBin ); negSigModel_->calcLikelihoodInfo( nDataEvents + trueBin ); pTrue = 0.5 * ( posSigModel_->getEvtIntensity() + negSigModel_->getEvtIntensity() ); } // Get the cached SCF fraction (and jacobian if we're using the square DP) Double_t scfFraction = fakeSCFFracs_[ trueBin ]; Double_t jacobian(1.0); if ( squareDP ) { jacobian = fakeJacobians_[ trueBin ]; } scfDPLike += pTrue * jacobian * scfFraction * pRecoGivenTrue; } // Divide by the reco jacobian scfDPLike /= recoJacobian; return scfDPLike; } void LauCPFitModel::getEvtExtraLikelihoods(UInt_t iEvt) { // Function to return the signal and background likelihoods for the // extra variables for the given event evtNo. sigExtraLike_ = 1.0; const UInt_t nBkgnds = this->nBkgndClasses(); if ( ! tagged_ || curEvtCharge_ < 0 ) { sigExtraLike_ = this->prodPdfValue( negSignalPdfs_, iEvt ); if (useSCF_) { scfExtraLike_ = this->prodPdfValue( negScfPdfs_, iEvt ); } for ( UInt_t bkgndID(0); bkgndID < nBkgnds; ++bkgndID ) { if (usingBkgnd_) { bkgndExtraLike_[bkgndID] = this->prodPdfValue( negBkgndPdfs_[bkgndID], iEvt ); } else { bkgndExtraLike_[bkgndID] = 0.0; } } } else { sigExtraLike_ = this->prodPdfValue( posSignalPdfs_, iEvt ); if (useSCF_) { scfExtraLike_ = this->prodPdfValue( posScfPdfs_, iEvt ); } for ( UInt_t bkgndID(0); bkgndID < nBkgnds; ++bkgndID ) { if (usingBkgnd_) { bkgndExtraLike_[bkgndID] = this->prodPdfValue( posBkgndPdfs_[bkgndID], iEvt ); } else { bkgndExtraLike_[bkgndID] = 0.0; } } } } void LauCPFitModel::updateCoeffs() { negCoeffs_.clear(); posCoeffs_.clear(); negCoeffs_.reserve(nSigComp_); posCoeffs_.reserve(nSigComp_); for (UInt_t i = 0; i < nSigComp_; i++) { negCoeffs_.push_back(coeffPars_[i]->antiparticleCoeff()); posCoeffs_.push_back(coeffPars_[i]->particleCoeff()); } } void LauCPFitModel::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"); if ( negSigModel_->usingScfModel() && posSigModel_->usingScfModel() ) { this->addSPlotNtupleDoubleBranch("scffraction"); } } // Store the total event likelihood for each species. if (useSCF_) { this->addSPlotNtupleDoubleBranch("sigTMTotalLike"); this->addSPlotNtupleDoubleBranch("sigSCFTotalLike"); this->addSPlotNtupleDoubleBranch("sigSCFFrac"); } else { 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()) { if (useSCF_) { this->addSPlotNtupleDoubleBranch("sigTMDPLike"); this->addSPlotNtupleDoubleBranch("sigSCFDPLike"); } else { 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 if (useSCF_) { this->addSPlotNtupleBranches(&negSignalPdfs_, "sigTM"); this->addSPlotNtupleBranches(&negScfPdfs_, "sigSCF"); } else { this->addSPlotNtupleBranches(&negSignalPdfs_, "sig"); } if (usingBkgnd_) { const UInt_t nBkgnds = this->nBkgndClasses(); for ( UInt_t iBkgnd(0); iBkgnd < nBkgnds; ++iBkgnd ) { const TString& bkgndClass = this->bkgndClassName(iBkgnd); const LauPdfPList* pdfList = &(negBkgndPdfs_[iBkgnd]); this->addSPlotNtupleBranches(pdfList, bkgndClass); } } } void LauCPFitModel::addSPlotNtupleBranches(const LauPdfPList* extraPdfs, const TString& prefix) { if (extraPdfs) { // Loop through each of the PDFs for (LauPdfPList::const_iterator pdf_iter = extraPdfs->begin(); pdf_iter != extraPdfs->end(); ++pdf_iter) { // 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); 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" ) { ++nVars; } } if ( nVars == 1 ) { // If the PDF only has one variable then // simply add one branch for that variable TString varName = (*pdf_iter)->varName(); TString name(prefix); name += 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 ( std::vector::const_iterator var_iter = varNames.begin(); var_iter != varNames.end(); ++var_iter ) { allVars += (*var_iter); TString name(prefix); name += (*var_iter); name += "Like"; this->addSPlotNtupleDoubleBranch(name); } TString name(prefix); name += allVars; name += "Like"; this->addSPlotNtupleDoubleBranch(name); } else { std::cerr << "WARNING in LauCPFitModel::addSPlotNtupleBranches : Can't yet deal with 3D PDFs." << std::endl; } } } } Double_t LauCPFitModel::setSPlotNtupleBranchValues(LauPdfPList* extraPdfs, const TString& prefix, UInt_t iEvt) { // Store the PDF value for each variable in the list Double_t totalLike(1.0); Double_t extraLike(0.0); if (extraPdfs) { for (LauPdfPList::iterator pdf_iter = extraPdfs->begin(); pdf_iter != extraPdfs->end(); ++pdf_iter) { // calculate the likelihood for this event (*pdf_iter)->calcLikelihoodInfo(iEvt); extraLike = (*pdf_iter)->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); 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" ) { ++nVars; } } if ( nVars == 1 ) { // If the PDF only has one variable then // simply store the value for that variable TString varName = (*pdf_iter)->varName(); TString name(prefix); name += 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 ( std::vector::const_iterator var_iter = varNames.begin(); var_iter != varNames.end(); ++var_iter ) { allVars += (*var_iter); TString name(prefix); name += (*var_iter); name += "Like"; Double_t indivLike = (*pdf_iter)->getLikelihood( (*var_iter) ); this->setSPlotNtupleDoubleBranchValue(name, indivLike); } TString name(prefix); name += allVars; name += "Like"; this->setSPlotNtupleDoubleBranchValue(name, extraLike); } else { std::cerr << "WARNING in LauCPFitModel::setSPlotNtupleBranchValues : Can't yet deal with 3D PDFs." << std::endl; } } } return totalLike; } LauSPlot::NameSet LauCPFitModel::variableNames() const { LauSPlot::NameSet nameSet; if (this->useDP()) { nameSet.insert("DP"); } // Loop through all the signal PDFs for (LauPdfPList::const_iterator pdf_iter = negSignalPdfs_.begin(); pdf_iter != negSignalPdfs_.end(); ++pdf_iter) { // Loop over the variables involved in each PDF std::vector varNames = (*pdf_iter)->varNames(); for ( std::vector::const_iterator var_iter = varNames.begin(); var_iter != varNames.end(); ++var_iter ) { // If they are not DP coordinates then add them if ( (*var_iter) != "m13Sq" && (*var_iter) != "m23Sq" ) { nameSet.insert( (*var_iter) ); } } } return nameSet; } LauSPlot::NumbMap LauCPFitModel::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 LauCPFitModel::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 LauCPFitModel::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 LauCPFitModel::twodimPDFs() const { // This makes the assumption that the form of the positive and // negative PDFs are the same, which seems reasonable to me LauSPlot::TwoDMap twodimMap; for (LauPdfPList::const_iterator pdf_iter = negSignalPdfs_.begin(); pdf_iter != negSignalPdfs_.end(); ++pdf_iter) { // Count the number of input variables that are not DP variables UInt_t nVars(0); 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" ) { ++nVars; } } if ( nVars == 2 ) { if (useSCF_) { twodimMap.insert( std::make_pair( "sigTM", std::make_pair( varNames[0], varNames[1] ) ) ); } else { twodimMap.insert( std::make_pair( "sig", std::make_pair( varNames[0], varNames[1] ) ) ); } } } if ( useSCF_ ) { for (LauPdfPList::const_iterator pdf_iter = negScfPdfs_.begin(); pdf_iter != negScfPdfs_.end(); ++pdf_iter) { // Count the number of input variables that are not DP variables UInt_t nVars(0); 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" ) { ++nVars; } } if ( nVars == 2 ) { twodimMap.insert( std::make_pair( "sigSCF", 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); const LauPdfPList& pdfList = negBkgndPdfs_[iBkgnd]; for (LauPdfPList::const_iterator pdf_iter = pdfList.begin(); pdf_iter != pdfList.end(); ++pdf_iter) { // Count the number of input variables that are not DP variables UInt_t nVars(0); 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" ) { ++nVars; } } if ( nVars == 2 ) { twodimMap.insert( std::make_pair( bkgndClass, std::make_pair( varNames[0], varNames[1] ) ) ); } } } } return twodimMap; } void LauCPFitModel::storePerEvtLlhds() { std::cout << "INFO in LauCPFitModel::storePerEvtLlhds : Storing per-event likelihood values..." << std::endl; // 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 LauFitDataTree* inputFitData = this->fitData(); if (!this->useDP() && this->storeDPEff()) { negSigModel_->initialise(negCoeffs_); posSigModel_->initialise(posCoeffs_); negSigModel_->fillDataTree(*inputFitData); posSigModel_->fillDataTree(*inputFitData); } UInt_t evtsPerExpt(this->eventsPerExpt()); LauIsobarDynamics* sigModel(0); LauPdfPList* sigPdfs(0); LauPdfPList* scfPdfs(0); LauBkgndPdfsList* bkgndPdfs(0); for (UInt_t iEvt = 0; iEvt < evtsPerExpt; ++iEvt) { this->setSPlotNtupleIntegerBranchValue("iExpt",this->iExpt()); this->setSPlotNtupleIntegerBranchValue("iEvtWithinExpt",iEvt); // Find out whether we have B- or B+ if ( tagged_ ) { const LauFitData& dataValues = inputFitData->getData(iEvt); LauFitData::const_iterator iter = dataValues.find("charge"); curEvtCharge_ = static_cast(iter->second); if (curEvtCharge_==+1) { sigModel = posSigModel_; sigPdfs = &posSignalPdfs_; scfPdfs = &posScfPdfs_; bkgndPdfs = &posBkgndPdfs_; } else { sigModel = negSigModel_; sigPdfs = &negSignalPdfs_; scfPdfs = &negScfPdfs_; bkgndPdfs = &negBkgndPdfs_; } } else { sigPdfs = &negSignalPdfs_; scfPdfs = &negScfPdfs_; bkgndPdfs = &negBkgndPdfs_; } // the DP information this->getEvtDPLikelihood(iEvt); if (this->storeDPEff()) { if (!this->useDP()) { posSigModel_->calcLikelihoodInfo(iEvt); negSigModel_->calcLikelihoodInfo(iEvt); } if ( tagged_ ) { this->setSPlotNtupleDoubleBranchValue("efficiency",sigModel->getEvtEff()); if ( negSigModel_->usingScfModel() && posSigModel_->usingScfModel() ) { this->setSPlotNtupleDoubleBranchValue("scffraction",sigModel->getEvtScfFraction()); } } else { this->setSPlotNtupleDoubleBranchValue("efficiency",0.5*(posSigModel_->getEvtEff() + negSigModel_->getEvtEff()) ); if ( negSigModel_->usingScfModel() && posSigModel_->usingScfModel() ) { this->setSPlotNtupleDoubleBranchValue("scffraction",0.5*(posSigModel_->getEvtScfFraction() + negSigModel_->getEvtScfFraction())); } } } if (this->useDP()) { sigTotalLike_ = sigDPLike_; if (useSCF_) { scfTotalLike_ = scfDPLike_; this->setSPlotNtupleDoubleBranchValue("sigTMDPLike",sigDPLike_); this->setSPlotNtupleDoubleBranchValue("sigSCFDPLike",scfDPLike_); } else { 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; if (useSCF_) { scfTotalLike_ = 1.0; } if (usingBkgnd_) { const UInt_t nBkgnds = this->nBkgndClasses(); for ( UInt_t iBkgnd(0); iBkgnd < nBkgnds; ++iBkgnd ) { bkgndTotalLike_[iBkgnd] = 1.0; } } } // the signal PDF values if ( useSCF_ ) { sigTotalLike_ *= this->setSPlotNtupleBranchValues(sigPdfs, "sigTM", iEvt); scfTotalLike_ *= this->setSPlotNtupleBranchValues(scfPdfs, "sigSCF", iEvt); } else { sigTotalLike_ *= this->setSPlotNtupleBranchValues(sigPdfs, "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 if (useSCF_) { Double_t scfFrac(0.0); if ( useSCFHist_ ) { scfFrac = recoSCFFracs_[iEvt]; } else { scfFrac = scfFrac_.unblindValue(); } this->setSPlotNtupleDoubleBranchValue("sigSCFFrac",scfFrac); sigTotalLike_ *= ( 1.0 - scfFrac ); if ( scfMap_ == 0 ) { scfTotalLike_ *= scfFrac; } this->setSPlotNtupleDoubleBranchValue("sigTMTotalLike",sigTotalLike_); this->setSPlotNtupleDoubleBranchValue("sigSCFTotalLike",scfTotalLike_); } else { 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 LauCPFitModel::storePerEvtLlhds : Finished storing per-event likelihood values." << std::endl; } void LauCPFitModel::embedNegSignal(const TString& fileName, const TString& treeName, Bool_t reuseEventsWithinEnsemble, Bool_t reuseEventsWithinExperiment, Bool_t useReweighting) { if (negSignalTree_) { std::cerr << "ERROR in LauCPFitModel::embedNegSignal : Already embedding signal from a file." << std::endl; return; } negSignalTree_ = new LauEmbeddedData(fileName,treeName,reuseEventsWithinExperiment); Bool_t dataOK = negSignalTree_->findBranches(); if (!dataOK) { delete negSignalTree_; negSignalTree_ = 0; std::cerr << "ERROR in LauCPFitModel::embedNegSignal : Problem creating data tree for embedding." << std::endl; return; } reuseSignal_ = reuseEventsWithinEnsemble; useNegReweighting_ = useReweighting; if (this->enableEmbedding() == kFALSE) {this->enableEmbedding(kTRUE);} } void LauCPFitModel::embedNegBkgnd(const TString& bkgndClass, const TString& fileName, const TString& treeName, Bool_t reuseEventsWithinEnsemble, Bool_t reuseEventsWithinExperiment) { if ( ! this->validBkgndClass( bkgndClass ) ) { std::cerr << "ERROR in LauCPFitModel::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 ); if (negBkgndTree_[bkgndID]) { std::cerr << "ERROR in LauCPFitModel::embedNegBkgnd : Already embedding background from a file." << std::endl; return; } negBkgndTree_[bkgndID] = new LauEmbeddedData(fileName,treeName,reuseEventsWithinExperiment); Bool_t dataOK = negBkgndTree_[bkgndID]->findBranches(); if (!dataOK) { delete negBkgndTree_[bkgndID]; negBkgndTree_[bkgndID] = 0; std::cerr << "ERROR in LauCPFitModel::embedNegBkgnd : Problem creating data tree for embedding." << std::endl; return; } reuseBkgnd_[bkgndID] = reuseEventsWithinEnsemble; if (this->enableEmbedding() == kFALSE) {this->enableEmbedding(kTRUE);} } void LauCPFitModel::embedPosSignal(const TString& fileName, const TString& treeName, Bool_t reuseEventsWithinEnsemble, Bool_t reuseEventsWithinExperiment, Bool_t useReweighting) { if (posSignalTree_) { std::cerr << "ERROR in LauCPFitModel::embedPosSignal : Already embedding signal from a file." << std::endl; return; } posSignalTree_ = new LauEmbeddedData(fileName,treeName,reuseEventsWithinExperiment); Bool_t dataOK = posSignalTree_->findBranches(); if (!dataOK) { delete posSignalTree_; posSignalTree_ = 0; std::cerr << "ERROR in LauCPFitModel::embedPosSignal : Problem creating data tree for embedding." << std::endl; return; } reuseSignal_ = reuseEventsWithinEnsemble; usePosReweighting_ = useReweighting; if (this->enableEmbedding() == kFALSE) {this->enableEmbedding(kTRUE);} } void LauCPFitModel::embedPosBkgnd(const TString& bkgndClass, const TString& fileName, const TString& treeName, Bool_t reuseEventsWithinEnsemble, Bool_t reuseEventsWithinExperiment) { if ( ! this->validBkgndClass( bkgndClass ) ) { std::cerr << "ERROR in LauCPFitModel::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 ); if (posBkgndTree_[bkgndID]) { std::cerr << "ERROR in LauCPFitModel::embedPosBkgnd : Already embedding background from a file." << std::endl; return; } posBkgndTree_[bkgndID] = new LauEmbeddedData(fileName,treeName,reuseEventsWithinExperiment); Bool_t dataOK = posBkgndTree_[bkgndID]->findBranches(); if (!dataOK) { delete posBkgndTree_[bkgndID]; posBkgndTree_[bkgndID] = 0; std::cerr << "ERROR in LauCPFitModel::embedPosBkgnd : Problem creating data tree for embedding." << std::endl; return; } reuseBkgnd_[bkgndID] = reuseEventsWithinEnsemble; if (this->enableEmbedding() == kFALSE) {this->enableEmbedding(kTRUE);} } void LauCPFitModel::weightEvents( const TString& dataFileName, const TString& dataTreeName ) { // Routine to provide weights for events that are uniformly distributed // in the DP (or square DP) so as to reproduce the given DP model if ( posKinematics_->squareDP() ) { std::cout << "INFO in LauCPFitModel::weightEvents : will create weights assuming events were generated flat in the square DP" << std::endl; } else { std::cout << "INFO in LauCPFitModel::weightEvents : will create weights assuming events were generated flat in phase space" << std::endl; } // This reads in the given dataFile and creates an input // fit data tree that stores them for all events and experiments. Bool_t dataOK = this->verifyFitData(dataFileName,dataTreeName); if (!dataOK) { std::cerr << "ERROR in LauCPFitModel::weightEvents : Problem caching the data." << std::endl; return; } LauFitDataTree* inputFitData = this->fitData(); if ( ! inputFitData->haveBranch( "m13Sq_MC" ) || ! inputFitData->haveBranch( "m23Sq_MC" ) ) { std::cerr << "WARNING in LauCPFitModel::weightEvents : Cannot find MC truth DP coordinate branches in supplied data, aborting." << std::endl; return; } if ( ! inputFitData->haveBranch( "charge" ) ) { std::cerr << "WARNING in LauCPFitModel::weightEvents : Cannot find branch specifying event charge in supplied data, aborting." << std::endl; return; } // Create the ntuple to hold the DP weights TString weightsFileName( dataFileName ); Ssiz_t index = weightsFileName.Last('.'); weightsFileName.Insert( index, "_DPweights" ); LauGenNtuple * weightsTuple = new LauGenNtuple( weightsFileName, dataTreeName ); weightsTuple->addIntegerBranch("iExpt"); weightsTuple->addIntegerBranch("iEvtWithinExpt"); weightsTuple->addDoubleBranch("dpModelWeight"); UInt_t iExpmt = this->iExpt(); UInt_t nExpmt = this->nExpt(); UInt_t firstExpmt = this->firstExpt(); for (iExpmt = firstExpmt; iExpmt < (firstExpmt+nExpmt); ++iExpmt) { inputFitData->readExperimentData(iExpmt); UInt_t nEvents = inputFitData->nEvents(); if (nEvents < 1) { std::cerr << "WARNING in LauCPFitModel::weightEvents : Zero events in experiment " << iExpmt << ", skipping..." << std::endl; continue; } weightsTuple->setIntegerBranchValue( "iExpt", iExpmt ); // Calculate and store the weights for the events in this experiment for ( UInt_t iEvent(0); iEvent < nEvents; ++iEvent ) { weightsTuple->setIntegerBranchValue( "iEvtWithinExpt", iEvent ); const LauFitData& evtData = inputFitData->getData( iEvent ); Double_t m13Sq_MC = evtData.find("m13Sq_MC")->second; Double_t m23Sq_MC = evtData.find("m23Sq_MC")->second; Int_t charge = evtData.find("charge")->second; Double_t dpModelWeight(0.0); LauKinematics * kinematics; LauIsobarDynamics * dpModel; if (charge > 0) { kinematics = posKinematics_; dpModel = posSigModel_; } else { kinematics = negKinematics_; dpModel = negSigModel_; } if ( kinematics->withinDPLimits( m13Sq_MC, m23Sq_MC ) ) { kinematics->updateKinematics( m13Sq_MC, m23Sq_MC ); dpModelWeight = dpModel->getEventWeight(); if ( kinematics->squareDP() ) { dpModelWeight *= kinematics->calcSqDPJacobian(); } const Double_t norm = (negSigModel_->getDPNorm() + posSigModel_->getDPNorm())/2.0; dpModelWeight /= norm; } weightsTuple->setDoubleBranchValue( "dpModelWeight", dpModelWeight ); weightsTuple->fillBranches(); } } weightsTuple->buildIndex( "iExpt", "iEvtWithinExpt" ); weightsTuple->addFriendTree(dataFileName, dataTreeName); weightsTuple->writeOutGenResults(); delete weightsTuple; } void LauCPFitModel::savePDFPlots(const TString& label) { savePDFPlotsWave(label, 0); savePDFPlotsWave(label, 1); savePDFPlotsWave(label, 2); std::cout << "LauCPFitModel::plot" << std::endl; // ((LauIsobarDynamics*)negSigModel_)->plot(); //Double_t minm13 = negSigModel_->getKinematics()->getm13Min(); Double_t minm13 = 0.0; Double_t maxm13 = negSigModel_->getKinematics()->getm13Max(); //Double_t minm23 = negSigModel_->getKinematics()->getm23Min(); Double_t minm23 = 0.0; Double_t maxm23 = negSigModel_->getKinematics()->getm23Max(); Double_t mins13 = minm13*minm13; Double_t maxs13 = maxm13*maxm13; Double_t mins23 = minm23*minm23; Double_t maxs23 = maxm23*maxm23; Double_t s13, s23, posChPdf, negChPdf; TString xLabel = "s13"; TString yLabel = "s23"; if (negSigModel_->getDaughters()->gotSymmetricalDP()) { xLabel = "sHigh"; yLabel = "sLow";} Int_t n13=200.00, n23=200.00; Double_t delta13, delta23; delta13 = (maxs13 - mins13)/n13; delta23 = (maxs23 - mins23)/n23; UInt_t nAmp = negSigModel_->getnCohAmp(); for (UInt_t resID = 0; resID <= nAmp; ++resID) { TGraph2D *posDt = new TGraph2D(); TGraph2D *negDt = new TGraph2D(); TGraph2D *acpDt = new TGraph2D(); TString resName = "TotalAmp"; if (resID != nAmp){ TString tStrResID = Form("%d", resID); const LauIsobarDynamics* model = negSigModel_; const LauAbsResonance* resonance = model->getResonance(resID); resName = resonance->getResonanceName(); std::cout << "resName = " << resName << std::endl; } resName.ReplaceAll("(", ""); resName.ReplaceAll(")", ""); resName.ReplaceAll("*", "Star"); posDt->SetName(resName+label); posDt->SetTitle(resName+" ("+label+") Positive"); negDt->SetName(resName+label); negDt->SetTitle(resName+" ("+label+") Negative"); acpDt->SetName(resName+label); acpDt->SetTitle(resName+" ("+label+") Asymmetry"); Int_t count=0; for (Int_t i=0; igetKinematics()->withinDPLimits2(s23, s13)) { if (negSigModel_->getDaughters()->gotSymmetricalDP() && (s13>s23) ) continue; negSigModel_->calcLikelihoodInfo(s13, s23); posSigModel_->calcLikelihoodInfo(s13, s23); LauComplex negChAmp = negSigModel_->getEvtDPAmp(); LauComplex posChAmp = posSigModel_->getEvtDPAmp(); if (resID != nAmp){ negChAmp = negSigModel_->getFullAmplitude(resID); posChAmp = posSigModel_->getFullAmplitude(resID); } negChPdf = negChAmp.abs2(); posChPdf = posChAmp.abs2(); negDt->SetPoint(count,s23,s13,negChPdf); // s23=sHigh, s13 = sLow posDt->SetPoint(count,s23,s13,posChPdf); // s23=sHigh, s13 = sLow acpDt->SetPoint(count,s23,s13, negChPdf - posChPdf); // s23=sHigh, s13 = sLow count++; } } } gStyle->SetPalette(1); TCanvas *posC = new TCanvas("c"+resName+label + "Positive",resName+" ("+label+") Positive",0,0,600,400); posDt->GetXaxis()->SetTitle(xLabel); posDt->GetYaxis()->SetTitle(yLabel); posDt->Draw("SURF1"); posDt->GetXaxis()->SetTitle(xLabel); posDt->GetYaxis()->SetTitle(yLabel); posC->SaveAs("plot_2D_"+resName + "_"+label+"Positive.C"); TCanvas *negC = new TCanvas("c"+resName+label + "Negative",resName+" ("+label+") Negative",0,0,600,400); negDt->GetXaxis()->SetTitle(xLabel); negDt->GetYaxis()->SetTitle(yLabel); negDt->Draw("SURF1"); negDt->GetXaxis()->SetTitle(xLabel); negDt->GetYaxis()->SetTitle(yLabel); negC->SaveAs("plot_2D_"+resName + "_"+label+"Negative.C"); TCanvas *acpC = new TCanvas("c"+resName+label + "Asymmetry",resName+" ("+label+") Asymmetry",0,0,600,400); acpDt->GetXaxis()->SetTitle(xLabel); acpDt->GetYaxis()->SetTitle(yLabel); acpDt->Draw("SURF1"); acpDt->GetXaxis()->SetTitle(xLabel); acpDt->GetYaxis()->SetTitle(yLabel); acpC->SaveAs("plot_2D_"+resName + "_"+label+"Asymmetry.C"); } } void LauCPFitModel::savePDFPlotsWave(const TString& label, const Int_t& spin) { std::cout << "label = "<< label << ", spin = "<< spin << std::endl; TString tStrResID = "S_Wave"; if (spin == 1) tStrResID = "P_Wave"; if (spin == 2) tStrResID = "D_Wave"; TString xLabel = "s13"; TString yLabel = "s23"; std::cout << "LauCPFitModel::savePDFPlotsWave: "<< tStrResID << std::endl; Double_t minm13 = 0.0; Double_t maxm13 = negSigModel_->getKinematics()->getm13Max(); Double_t minm23 = 0.0; Double_t maxm23 = negSigModel_->getKinematics()->getm23Max(); Double_t mins13 = minm13*minm13; Double_t maxs13 = maxm13*maxm13; Double_t mins23 = minm23*minm23; Double_t maxs23 = maxm23*maxm23; Double_t s13, s23, posChPdf, negChPdf; TGraph2D *posDt = new TGraph2D(); TGraph2D *negDt = new TGraph2D(); TGraph2D *acpDt = new TGraph2D(); posDt->SetName(tStrResID+label); posDt->SetTitle(tStrResID+" ("+label+") Positive"); negDt->SetName(tStrResID+label); negDt->SetTitle(tStrResID+" ("+label+") Negative"); acpDt->SetName(tStrResID+label); acpDt->SetTitle(tStrResID+" ("+label+") Asymmetry"); Int_t n13=200.00, n23=200.00; Double_t delta13, delta23; delta13 = (maxs13 - mins13)/n13; delta23 = (maxs23 - mins23)/n23; UInt_t nAmp = negSigModel_->getnCohAmp(); Int_t count=0; for (Int_t i=0; igetKinematics()->withinDPLimits2(s23, s13)) { if (negSigModel_->getDaughters()->gotSymmetricalDP() && (s13>s23) ) continue; LauComplex negChAmp(0,0); LauComplex posChAmp(0,0); Bool_t noWaveRes = kTRUE; negSigModel_->calcLikelihoodInfo(s13, s23); for (UInt_t resID = 0; resID < nAmp; ++resID) { const LauIsobarDynamics* model = negSigModel_; const LauAbsResonance* resonance = model->getResonance(resID); Int_t spin_res = resonance->getSpin(); if (spin != spin_res) continue; noWaveRes = kFALSE; negChAmp += negSigModel_->getFullAmplitude(resID); posChAmp += posSigModel_->getFullAmplitude(resID); } if (noWaveRes) return; negChPdf = negChAmp.abs2(); posChPdf = posChAmp.abs2(); negDt->SetPoint(count,s23,s13,negChPdf); // s23=sHigh, s13 = sLow posDt->SetPoint(count,s23,s13,posChPdf); // s23=sHigh, s13 = sLow acpDt->SetPoint(count,s23,s13, negChPdf - posChPdf); // s23=sHigh, s13 = sLow count++; } } } gStyle->SetPalette(1); TCanvas *posC = new TCanvas("c"+tStrResID+label + "Positive",tStrResID+" ("+label+") Positive",0,0,600,400); posDt->GetXaxis()->SetTitle(xLabel); posDt->GetYaxis()->SetTitle(yLabel); posDt->Draw("SURF1"); posDt->GetXaxis()->SetTitle(xLabel); posDt->GetYaxis()->SetTitle(yLabel); posC->SaveAs("plot_2D_"+tStrResID + "_"+label+"Positive.C"); TCanvas *negC = new TCanvas("c"+tStrResID+label + "Negative",tStrResID+" ("+label+") Negative",0,0,600,400); negDt->GetXaxis()->SetTitle(xLabel); negDt->GetYaxis()->SetTitle(yLabel); negDt->Draw("SURF1"); negDt->GetXaxis()->SetTitle(xLabel); negDt->GetYaxis()->SetTitle(yLabel); negC->SaveAs("plot_2D_"+tStrResID + "_"+label+"Negative.C"); TCanvas *acpC = new TCanvas("c"+tStrResID+label + "Asymmetry",tStrResID+" ("+label+") Asymmetry",0,0,600,400); acpDt->GetXaxis()->SetTitle(xLabel); acpDt->GetYaxis()->SetTitle(yLabel); acpDt->Draw("SURF1"); acpDt->GetXaxis()->SetTitle(xLabel); acpDt->GetYaxis()->SetTitle(yLabel); acpC->SaveAs("plot_2D_"+tStrResID + "_"+label+"Asymmetry.C"); } Double_t LauCPFitModel::getParamFromTree( TTree& tree, const TString& name ) { TBranch* branch{tree.FindBranch( name )}; if ( branch ) { TLeaf* leaf{branch->GetLeaf( name )}; if ( leaf ) { tree.GetEntry(0); return leaf->GetValue(); } else { std::cerr << "ERROR in LauCPFitModel::getParamFromTree : Leaf name " + name + " not found in parameter file!" << std::endl; } } else { std::cerr << "ERROR in LauCPFitModel::getParamFromTree : Branch name " + name + " not found in parameter file!" << std::endl; } return -1.1; } void LauCPFitModel::fixParam( LauParameter* param, const Double_t val, const Bool_t fix) { std::cout << "INFO in LauCPFitModel::fixParam : Setting " << param->name() << " to " << val << std::endl; param->value(val); param->genValue(val); param->initValue(val); if (fix) { param->fixed(kTRUE); } else if (!param->fixed()){ // Add parameter name to list to indicate that this should not be randomised by randomiseInitFitPars // (otherwise only those that are fixed are not randomised). // This is only done to those that are not already fixed (see randomiseInitFitPars). allImportedFreeParams_.insert(param); } } void LauCPFitModel::fixParams( std::vector& params ) { const Bool_t fix{fixParams_}; // TODO: Allow some parameters to be fixed and some to remain floating (but initialised) if ( !fixParamFileName_.IsNull() ) { // Take param values from a file TFile * paramFile = TFile::Open(fixParamFileName_, "READ"); if (!paramFile) { std::cerr << "ERROR in LauCPFitModel::fixParams : File '" + fixParamFileName_ + "' could not be opened for reading!" << std::endl; return; } TTree * paramTree = dynamic_cast(paramFile->Get(fixParamTreeName_)); if (!paramTree) { std::cerr << "ERROR in LauCPFitModel::fixParams : Tree '" + fixParamTreeName_ + "' not found in parameter file!" << std::endl; return; } if ( !fixParamNames_.empty() ) { // Fix params from file, according to vector of names for( auto itr = params.begin(); itr != params.end(); ++itr ) { auto itrName = fixParamNames_.find( (*itr)->name() ); if ( itrName != fixParamNames_.end() ) { this->fixParam(*itr, this->getParamFromTree(*paramTree, *itrName), fix); } } } else { // Fix some (unspecified) parameters from file, prioritising the map (if it exists) for( auto itr = params.begin(); itr != params.end(); ++itr) { const TString& name = (*itr)->name(); if ( ! fixParamMap_.empty() ) { auto nameValItr = fixParamMap_.find(name); if ( nameValItr != fixParamMap_.end() ) { this->fixParam(*itr, nameValItr->second, fix); } } else { this->fixParam(*itr, this->getParamFromTree(*paramTree, name), fix); } } } // Vector of names? } else { // Fix param names fom map, leave others floating for( auto itr = params.begin(); itr != params.end(); ++itr ) { auto nameValItr = this->fixParamMap_.find( (*itr)->name() ); if ( nameValItr != this->fixParamMap_.end() ) { this->fixParam(*itr, nameValItr->second, fix); } } } } diff --git a/src/LauCartesianCPCoeffSet.cc b/src/LauCartesianCPCoeffSet.cc index 4bfc74c..f4acdb4 100644 --- a/src/LauCartesianCPCoeffSet.cc +++ b/src/LauCartesianCPCoeffSet.cc @@ -1,270 +1,325 @@ /* 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 LauCartesianCPCoeffSet.cc \brief File containing implementation of LauCartesianCPCoeffSet class. */ #include #include #include #include "TMath.h" #include "TRandom.h" #include "LauCartesianCPCoeffSet.hh" #include "LauComplex.hh" #include "LauConstants.hh" #include "LauParameter.hh" #include "LauPrint.hh" ClassImp(LauCartesianCPCoeffSet) LauCartesianCPCoeffSet::LauCartesianCPCoeffSet(const TString& compName, const Double_t x, const Double_t y, const Double_t deltaX, const Double_t deltaY, const Bool_t xFixed, const Bool_t yFixed, const Bool_t deltaXFixed, const Bool_t deltaYFixed, const Bool_t deltaXSecondStage, const Bool_t deltaYSecondStage) : LauAbsCoeffSet{ compName }, x_{ std::make_unique("X", x, minRealImagPart_, maxRealImagPart_, xFixed) }, y_{ std::make_unique("Y", y, minRealImagPart_, maxRealImagPart_, yFixed) }, deltaX_{ std::make_unique("DeltaX", deltaX, minDelta_, maxDelta_, deltaXFixed) }, deltaY_{ std::make_unique("DeltaY", deltaY, minDelta_, maxDelta_, deltaYFixed) }, acp_{ "ACP", -2.0*(x*deltaX + y*deltaY)/(x*x + deltaX*deltaX + y*y + deltaY*deltaY), -1.0, 1.0, deltaXFixed&&deltaYFixed } { if (deltaXSecondStage && !deltaXFixed) { deltaX_->secondStage(kTRUE); deltaX_->initValue(0.0); } if (deltaYSecondStage && !deltaYFixed) { deltaY_->secondStage(kTRUE); deltaY_->initValue(0.0); } } LauCartesianCPCoeffSet::LauCartesianCPCoeffSet(const LauCartesianCPCoeffSet& rhs, const CloneOption cloneOption, const Double_t constFactor) : LauAbsCoeffSet{ rhs.name() }, particleCoeff_{ rhs.particleCoeff_ }, antiparticleCoeff_{ rhs.antiparticleCoeff_ }, acp_{ rhs.acp_ } { if ( cloneOption == CloneOption::All || cloneOption == CloneOption::TieRealPart ) { x_.reset( rhs.x_->createClone(constFactor) ); } else { x_ = std::make_unique("X", rhs.x_->value(), minRealImagPart_, maxRealImagPart_, rhs.x_->fixed()); if ( rhs.x_->blind() ) { const LauBlind* blinder { rhs.x_->blinder() }; x_->blindParameter( blinder->blindingString(), blinder->blindingWidth() ); } } if ( cloneOption == CloneOption::All || cloneOption == CloneOption::TieImagPart ) { y_.reset( rhs.y_->createClone(constFactor) ); } else { y_ = std::make_unique("Y", rhs.y_->value(), minRealImagPart_, maxRealImagPart_, rhs.y_->fixed()); if ( rhs.y_->blind() ) { const LauBlind* blinder { rhs.y_->blinder() }; y_->blindParameter( blinder->blindingString(), blinder->blindingWidth() ); } } if ( cloneOption == CloneOption::All || cloneOption == CloneOption::TieCPPars ) { deltaX_.reset( rhs.deltaX_->createClone(constFactor) ); deltaY_.reset( rhs.deltaY_->createClone(constFactor) ); } else { deltaX_ = std::make_unique("DeltaX", rhs.deltaX_->value(), minDelta_, maxDelta_, rhs.deltaX_->fixed()); deltaY_ = std::make_unique("DeltaY", rhs.deltaY_->value(), minDelta_, maxDelta_, rhs.deltaY_->fixed()); if ( rhs.deltaX_->secondStage() && !rhs.deltaX_->fixed() ) { deltaX_->secondStage(kTRUE); deltaX_->initValue(0.0); } if ( rhs.deltaY_->secondStage() && !rhs.deltaY_->fixed() ) { deltaY_->secondStage(kTRUE); deltaY_->initValue(0.0); } if ( rhs.deltaX_->blind() ) { const LauBlind* blinder { rhs.deltaX_->blinder() }; deltaX_->blindParameter( blinder->blindingString(), blinder->blindingWidth() ); } if ( rhs.deltaY_->blind() ) { const LauBlind* blinder { rhs.deltaY_->blinder() }; deltaY_->blindParameter( blinder->blindingString(), blinder->blindingWidth() ); } } } std::vector LauCartesianCPCoeffSet::getParameters() { return { x_.get(), y_.get(), deltaX_.get(), deltaY_.get() }; } +std::vector LauCartesianCPCoeffSet::getParameters() const +{ + return { x_.get(), y_.get(), deltaX_.get(), deltaY_.get() }; +} + void LauCartesianCPCoeffSet::printParValues() const { std::cout<<"INFO in LauCartesianCPCoeffSet::printParValues : Component \""<name()<<"\" has "; std::cout<<"x = "<value()<<",\t"; std::cout<<"y = "<value()<<",\t"; std::cout<<"Delta x = "<value()<<",\t"; std::cout<<"Delta y = "<value()<<"."<name() }; resName = resName.ReplaceAll("_", "\\_"); stream<value()); stream<<" \\pm "; print.printFormat(stream, x_->error()); stream<<"$ & $"; print.printFormat(stream, y_->value()); stream<<" \\pm "; print.printFormat(stream, y_->error()); stream<<"$ & $"; print.printFormat(stream, deltaX_->value()); stream<<" \\pm "; print.printFormat(stream, deltaX_->error()); stream<<"$ & $"; print.printFormat(stream, deltaY_->value()); stream<<" \\pm "; print.printFormat(stream, deltaY_->error()); stream<<"$ \\\\"<fixed() == kFALSE) { // Choose a value for "X" between -3.0 and 3.0 const Double_t value { LauAbsCoeffSet::getRandomiser()->Rndm()*6.0 - 3.0 }; x_->initValue(value); x_->value(value); } if (y_->fixed() == kFALSE) { // Choose a value for "Y" between -3.0 and 3.0 const Double_t value { LauAbsCoeffSet::getRandomiser()->Rndm()*6.0 - 3.0 }; y_->initValue(value); y_->value(value); } if (deltaX_->fixed() == kFALSE && deltaX_->secondStage() == kFALSE) { // Choose a value for "Delta X" between -0.5 and 0.5 const Double_t value { LauAbsCoeffSet::getRandomiser()->Rndm()*1.0 - 0.5 }; deltaX_->initValue(value); deltaX_->value(value); } if (deltaY_->fixed() == kFALSE && deltaY_->secondStage() == kFALSE) { // Choose a value for "Delta Y" between -0.5 and 0.5 const Double_t value { LauAbsCoeffSet::getRandomiser()->Rndm()*1.0 - 0.5 }; deltaY_->initValue(value); deltaY_->value(value); } } void LauCartesianCPCoeffSet::finaliseValues() { // update the pulls x_->updatePull(); y_->updatePull(); deltaX_->updatePull(); deltaY_->updatePull(); } const LauComplex& LauCartesianCPCoeffSet::particleCoeff() { particleCoeff_.setRealImagPart( x_->unblindValue() + deltaX_->unblindValue(), y_->unblindValue() + deltaY_->unblindValue() ); return particleCoeff_; } const LauComplex& LauCartesianCPCoeffSet::antiparticleCoeff() { antiparticleCoeff_.setRealImagPart( x_->unblindValue() - deltaX_->unblindValue(), y_->unblindValue() - deltaY_->unblindValue() ); return antiparticleCoeff_; } void LauCartesianCPCoeffSet::setCoeffValues( const LauComplex& coeff, const LauComplex& coeffBar, const Bool_t init ) { LauComplex average{ coeff }; average += coeffBar; average.rescale( 0.5 ); const Double_t xVal{ average.re() }; const Double_t yVal{ average.im() }; const Double_t deltaXVal{ coeff.re() - average.re() }; const Double_t deltaYVal{ coeff.im() - average.im() }; x_->value( xVal ); y_->value( yVal ); deltaX_->value( deltaXVal ); deltaY_->value( deltaYVal ); if ( init ) { x_->genValue( xVal ); y_->genValue( yVal ); deltaX_->genValue( deltaXVal ); deltaY_->genValue( deltaYVal ); x_->initValue( xVal ); y_->initValue( yVal ); deltaX_->initValue( deltaXVal ); deltaY_->initValue( deltaYVal ); } } LauParameter LauCartesianCPCoeffSet::acp() { // set the name const TString parName{ this->baseName() + "_ACP" }; acp_.name(parName); // work out the ACP value const Double_t numer { x_->value()*deltaX_->value() + y_->value()*deltaY_->value() }; const Double_t denom { x_->value()*x_->value() + deltaX_->value()*deltaX_->value() + y_->value()*y_->value() + deltaY_->value()*deltaY_->value() }; const Double_t value { -2.0*numer/denom }; // is it fixed? const Bool_t fixed { deltaX_->fixed() && deltaY_->fixed() }; acp_.fixed(fixed); // we can't work out the error without the covariance matrix const Double_t error{0.0}; // set the value and error acp_.valueAndErrors(value,error); return acp_; } LauCartesianCPCoeffSet* LauCartesianCPCoeffSet::createClone_impl(const TString& newName, const CloneOption cloneOption, const Double_t constFactor) { if ( ! ( cloneOption == CloneOption::All || cloneOption == CloneOption::TieRealPart || cloneOption == CloneOption::TieImagPart || cloneOption == CloneOption::TieCPPars ) ) { std::cerr << "ERROR in LauCartesianCPCoeffSet::createClone : Invalid clone option" << std::endl; return nullptr; } auto clone = new LauCartesianCPCoeffSet{ *this, cloneOption, constFactor }; clone->name( newName ); return clone; } + +LauCartesianCPCoeffSet nlohmann::adl_serializer::from_json(const json& j) +{ + const LauCoeffType type { j.at("type").get() }; + if ( type != LauCoeffType::CartesianCP ) { + throw LauWrongCoeffType("Wrong coefficient type given to construct LauCartesianCPCoeffSet"); + } + + const TString name { j.at("name").get().c_str() }; + + // TODO - handle cloned coeffs + + const Double_t x { j.at("x").get() }; + const Double_t y { j.at("y").get() }; + const Double_t deltaX { j.at("deltaX").get() }; + const Double_t deltaY { j.at("deltaY").get() }; + + const Bool_t xFixed { j.at("xFixed").get() }; + const Bool_t yFixed { j.at("yFixed").get() }; + const Bool_t deltaXFixed { j.at("deltaXFixed").get() }; + const Bool_t deltaYFixed { j.at("deltaYFixed").get() }; + + const Bool_t deltaXSecondStage { j.at("deltaXSecondStage").get() }; + const Bool_t deltaYSecondStage { j.at("deltaYSecondStage").get() }; + + return { name, x, y, deltaX, deltaY, xFixed, yFixed, deltaXFixed, deltaYFixed, deltaXSecondStage, deltaYSecondStage }; +} + +void nlohmann::adl_serializer::to_json(json& j, const LauCartesianCPCoeffSet& t) +{ + j["type"] = LauCoeffType::CartesianCP; + j["name"] = t.name(); + + // TODO - handle cloned coeffs + + auto pars = t.getParameters(); + + j["x"] = pars[0]->value(); + j["y"] = pars[1]->value(); + j["deltaX"] = pars[2]->value(); + j["deltaY"] = pars[3]->value(); + + j["xFixed"] = pars[0]->fixed(); + j["yFixed"] = pars[1]->fixed(); + j["deltaXFixed"] = pars[2]->fixed(); + j["deltaYFixed"] = pars[3]->fixed(); + + j["deltaXSecondStage"] = pars[2]->secondStage(); + j["deltaYSecondStage"] = pars[3]->secondStage(); +} diff --git a/src/LauCartesianGammaCPCoeffSet.cc b/src/LauCartesianGammaCPCoeffSet.cc index 48004d0..086e8e0 100644 --- a/src/LauCartesianGammaCPCoeffSet.cc +++ b/src/LauCartesianGammaCPCoeffSet.cc @@ -1,308 +1,377 @@ /* Copyright 2014 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 LauCartesianGammaCPCoeffSet.cc \brief File containing implementation of LauCartesianGammaCPCoeffSet class. */ #include #include #include #include "TMath.h" #include "TRandom.h" #include "LauCartesianGammaCPCoeffSet.hh" #include "LauComplex.hh" #include "LauConstants.hh" #include "LauParameter.hh" #include "LauPrint.hh" ClassImp(LauCartesianGammaCPCoeffSet) LauCartesianGammaCPCoeffSet::LauCartesianGammaCPCoeffSet(const TString& compName, const Double_t x, const Double_t y, const Double_t xCP, const Double_t yCP, const Double_t deltaXCP, const Double_t deltaYCP, const Bool_t xFixed, const Bool_t yFixed, const Bool_t xCPFixed, const Bool_t yCPFixed, const Bool_t deltaXCPFixed, const Bool_t deltaYCPFixed, const Bool_t deltaXCPSecondStage, const Bool_t deltaYCPSecondStage) : LauAbsCoeffSet{ compName }, x_{ std::make_unique("X", x, minRealImagPart_, maxRealImagPart_, xFixed) }, y_{ std::make_unique("Y", y, minRealImagPart_, maxRealImagPart_, yFixed) }, xCP_{ std::make_unique("XCP", xCP, minRealImagPart_, maxRealImagPart_, xCPFixed) }, yCP_{ std::make_unique("YCP", yCP, minRealImagPart_, maxRealImagPart_, yCPFixed) }, deltaXCP_{ std::make_unique("DeltaXCP", deltaXCP, minDelta_, maxDelta_, deltaXCPFixed) }, deltaYCP_{ std::make_unique("DeltaYCP", deltaYCP, minDelta_, maxDelta_, deltaYCPFixed) }, nonCPPart_{ x, y }, cpPart_{ 1+xCP+deltaXCP, yCP+deltaYCP }, cpAntiPart_{ 1+xCP-deltaXCP, yCP-deltaYCP }, particleCoeff_{ nonCPPart_ * cpPart_ }, antiparticleCoeff_{ nonCPPart_ * cpAntiPart_ }, acp_{ "ACP", (antiparticleCoeff_.abs2()-particleCoeff_.abs2())/(antiparticleCoeff_.abs2()+particleCoeff_.abs2()), -1.0, 1.0, deltaXCPFixed&&deltaYCPFixed } { if (deltaXCPSecondStage && !deltaXCPFixed) { deltaXCP_->secondStage(kTRUE); deltaXCP_->initValue(0.0); } if (deltaYCPSecondStage && !deltaYCPFixed) { deltaYCP_->secondStage(kTRUE); deltaYCP_->initValue(0.0); } } LauCartesianGammaCPCoeffSet::LauCartesianGammaCPCoeffSet(const LauCartesianGammaCPCoeffSet& rhs, CloneOption cloneOption, Double_t constFactor) : LauAbsCoeffSet{ rhs.name() }, nonCPPart_{ rhs.nonCPPart_ }, cpPart_{ rhs.cpPart_ }, cpAntiPart_{ rhs.cpAntiPart_ }, particleCoeff_{ rhs.particleCoeff_ }, antiparticleCoeff_{ rhs.antiparticleCoeff_ }, acp_{ rhs.acp_ } { if ( cloneOption == CloneOption::All || cloneOption == CloneOption::TieRealPart ) { x_.reset( rhs.x_->createClone(constFactor) ); } else { x_ = std::make_unique("X", rhs.x_->value(), minRealImagPart_, maxRealImagPart_, rhs.x_->fixed()); if ( rhs.x_->blind() ) { const LauBlind* blinder { rhs.x_->blinder() }; x_->blindParameter( blinder->blindingString(), blinder->blindingWidth() ); } } if ( cloneOption == CloneOption::All || cloneOption == CloneOption::TieImagPart ) { y_.reset( rhs.y_->createClone(constFactor) ); } else { y_ = std::make_unique("Y", rhs.y_->value(), minRealImagPart_, maxRealImagPart_, rhs.y_->fixed()); if ( rhs.y_->blind() ) { const LauBlind* blinder { rhs.y_->blinder() }; y_->blindParameter( blinder->blindingString(), blinder->blindingWidth() ); } } if ( cloneOption == CloneOption::All || cloneOption == CloneOption::TieCPPars ) { xCP_.reset( rhs.xCP_->createClone(constFactor) ); yCP_.reset( rhs.yCP_->createClone(constFactor) ); deltaXCP_.reset( rhs.deltaXCP_->createClone(constFactor) ); deltaYCP_.reset( rhs.deltaYCP_->createClone(constFactor) ); } else { xCP_ = std::make_unique("XCP", rhs.xCP_->value(), minRealImagPart_, maxRealImagPart_, rhs.xCP_->fixed()); if ( rhs.xCP_->blind() ) { const LauBlind* blinder { rhs.xCP_->blinder() }; xCP_->blindParameter( blinder->blindingString(), blinder->blindingWidth() ); } yCP_ = std::make_unique("YCP", rhs.yCP_->value(), minRealImagPart_, maxRealImagPart_, rhs.yCP_->fixed()); if ( rhs.yCP_->blind() ) { const LauBlind* blinder { rhs.yCP_->blinder() }; yCP_->blindParameter( blinder->blindingString(), blinder->blindingWidth() ); } deltaXCP_ = std::make_unique("DeltaXCP", rhs.deltaXCP_->value(), minDelta_, maxDelta_, rhs.deltaXCP_->fixed()); deltaYCP_ = std::make_unique("DeltaYCP", rhs.deltaYCP_->value(), minDelta_, maxDelta_, rhs.deltaYCP_->fixed()); if ( rhs.deltaXCP_->secondStage() && !rhs.deltaXCP_->fixed() ) { deltaXCP_->secondStage(kTRUE); deltaXCP_->initValue(0.0); } if ( rhs.deltaYCP_->secondStage() && !rhs.deltaYCP_->fixed() ) { deltaYCP_->secondStage(kTRUE); deltaYCP_->initValue(0.0); } if ( rhs.deltaXCP_->blind() ) { const LauBlind* blinder { rhs.deltaXCP_->blinder() }; deltaXCP_->blindParameter( blinder->blindingString(), blinder->blindingWidth() ); } if ( rhs.deltaYCP_->blind() ) { const LauBlind* blinder { rhs.deltaYCP_->blinder() }; deltaYCP_->blindParameter( blinder->blindingString(), blinder->blindingWidth() ); } } } std::vector LauCartesianGammaCPCoeffSet::getParameters() { - std::vector pars; - pars.reserve(6); - pars.push_back(x_.get()); - pars.push_back(y_.get()); - if (!xCP_->fixed()) { pars.push_back(xCP_.get()); } - if (!yCP_->fixed()) { pars.push_back(yCP_.get()); } - if (!deltaXCP_->fixed()) { pars.push_back(deltaXCP_.get()); } - if (!deltaYCP_->fixed()) { pars.push_back(deltaYCP_.get()); } - return pars; + return { + x_.get(), + y_.get(), + xCP_.get(), + yCP_.get(), + deltaXCP_.get(), + deltaYCP_.get() + }; +} + +std::vector LauCartesianGammaCPCoeffSet::getParameters() const +{ + return { + x_.get(), + y_.get(), + xCP_.get(), + yCP_.get(), + deltaXCP_.get(), + deltaYCP_.get() + }; } void LauCartesianGammaCPCoeffSet::printParValues() const { std::cout<<"INFO in LauCartesianGammaCPCoeffSet::printParValues : Component \""<name()<<"\" has "; std::cout<<"x = "<value()<<",\t"; std::cout<<"y = "<value()<<",\t"; std::cout<<"xCP = "<value()<<",\t"; std::cout<<"yCP = "<value()<<",\t"; std::cout<<"Delta xCP = "<value()<<",\t"; std::cout<<"Delta yCP = "<value()<<"."<name() }; resName = resName.ReplaceAll("_", "\\_"); stream<value()); stream<<" \\pm "; print.printFormat(stream, x_->error()); stream<<"$ & $"; print.printFormat(stream, y_->value()); stream<<" \\pm "; print.printFormat(stream, y_->error()); stream<<"$ & $"; print.printFormat(stream, xCP_->value()); stream<<" \\pm "; print.printFormat(stream, xCP_->error()); stream<<"$ & $"; print.printFormat(stream, yCP_->value()); stream<<" \\pm "; print.printFormat(stream, yCP_->error()); stream<<"$ & $"; print.printFormat(stream, deltaXCP_->value()); stream<<" \\pm "; print.printFormat(stream, deltaXCP_->error()); stream<<"$ & $"; print.printFormat(stream, deltaYCP_->value()); stream<<" \\pm "; print.printFormat(stream, deltaYCP_->error()); stream<<"$ \\\\"<fixed() == kFALSE) { // Choose a value for "X" between -3.0 and 3.0 const Double_t value { LauAbsCoeffSet::getRandomiser()->Rndm()*6.0 - 3.0 }; x_->initValue(value); x_->value(value); } if (y_->fixed() == kFALSE) { // Choose a value for "Y" between -3.0 and 3.0 const Double_t value { LauAbsCoeffSet::getRandomiser()->Rndm()*6.0 - 3.0 }; y_->initValue(value); y_->value(value); } if (xCP_->fixed() == kFALSE) { // Choose a value for "XCP" between -3.0 and 3.0 const Double_t value { LauAbsCoeffSet::getRandomiser()->Rndm()*6.0 - 3.0 }; xCP_->initValue(value); xCP_->value(value); } if (yCP_->fixed() == kFALSE) { // Choose a value for "YCP" between -3.0 and 3.0 const Double_t value { LauAbsCoeffSet::getRandomiser()->Rndm()*6.0 - 3.0 }; yCP_->initValue(value); yCP_->value(value); } if (deltaXCP_->fixed() == kFALSE && deltaXCP_->secondStage() == kFALSE) { // Choose a value for "Delta XCP" between -0.5 and 0.5 const Double_t value { LauAbsCoeffSet::getRandomiser()->Rndm()*1.0 - 0.5 }; deltaXCP_->initValue(value); deltaXCP_->value(value); } if (deltaYCP_->fixed() == kFALSE && deltaYCP_->secondStage() == kFALSE) { // Choose a value for "Delta YCP" between -0.5 and 0.5 const Double_t value { LauAbsCoeffSet::getRandomiser()->Rndm()*1.0 - 0.5 }; deltaYCP_->initValue(value); deltaYCP_->value(value); } } void LauCartesianGammaCPCoeffSet::finaliseValues() { // update the pulls x_->updatePull(); y_->updatePull(); xCP_->updatePull(); yCP_->updatePull(); deltaXCP_->updatePull(); deltaYCP_->updatePull(); } const LauComplex& LauCartesianGammaCPCoeffSet::particleCoeff() { nonCPPart_.setRealImagPart( x_->unblindValue(), y_->unblindValue() ); cpPart_.setRealImagPart( 1.0 + xCP_->unblindValue() + deltaXCP_->unblindValue(), yCP_->unblindValue() + deltaYCP_->unblindValue() ); particleCoeff_ = nonCPPart_ * cpPart_; return particleCoeff_; } const LauComplex& LauCartesianGammaCPCoeffSet::antiparticleCoeff() { nonCPPart_.setRealImagPart( x_->unblindValue(), y_->unblindValue() ); cpAntiPart_.setRealImagPart( 1.0 + xCP_->unblindValue() - deltaXCP_->unblindValue(), yCP_->unblindValue() - deltaYCP_->unblindValue() ); antiparticleCoeff_ = nonCPPart_ * cpAntiPart_; return antiparticleCoeff_; } void LauCartesianGammaCPCoeffSet::setCoeffValues( const LauComplex&, const LauComplex&, const Bool_t ) { std::cerr << "ERROR in LauCartesianGammaCPCoeffSet::setCoeffValues : Method not supported by this class - too many parameters" << std::endl; } LauParameter LauCartesianGammaCPCoeffSet::acp() { // set the name const TString parName{ this->baseName() + "_ACP" }; acp_.name(parName); // work out the ACP value const LauComplex nonCPPart{ x_->value(), y_->value() }; const LauComplex cpPart{ 1.0 + xCP_->value() + deltaXCP_->value(), yCP_->value() + deltaYCP_->value() }; const LauComplex cpAntiPart{ 1.0 + xCP_->value() - deltaXCP_->value(), yCP_->value() - deltaYCP_->value() }; const LauComplex partCoeff { nonCPPart * cpPart }; const LauComplex antiCoeff { nonCPPart * cpAntiPart }; const Double_t numer { antiCoeff.abs2() - partCoeff.abs2() }; const Double_t denom { antiCoeff.abs2() + partCoeff.abs2() }; const Double_t value { numer/denom }; // is it fixed? const Bool_t fixed { deltaXCP_->fixed() && deltaYCP_->fixed() }; acp_.fixed(fixed); // we can't work out the error without the covariance matrix const Double_t error{0.0}; // set the value and error acp_.valueAndErrors(value,error); return acp_; } LauCartesianGammaCPCoeffSet* LauCartesianGammaCPCoeffSet::createClone_impl(const TString& newName, const CloneOption cloneOption, const Double_t constFactor) { if ( ! ( cloneOption == CloneOption::All || cloneOption == CloneOption::TieRealPart || cloneOption == CloneOption::TieImagPart || cloneOption == CloneOption::TieCPPars ) ) { std::cerr << "ERROR in LauCartesianGammaCPCoeffSet::createClone : Invalid clone option" << std::endl; return nullptr; } auto clone = new LauCartesianGammaCPCoeffSet{ *this, cloneOption, constFactor }; clone->name( newName ); return clone; } + +LauCartesianGammaCPCoeffSet nlohmann::adl_serializer::from_json(const json& j) +{ + const LauCoeffType type { j.at("type").get() }; + if ( type != LauCoeffType::CartesianGammaCP ) { + throw LauWrongCoeffType("Wrong coefficient type given to construct LauCartesianGammaCPCoeffSet"); + } + + const TString name { j.at("name").get().c_str() }; + + // TODO - handle cloned coeffs + + const Double_t x { j.at("x").get() }; + const Double_t y { j.at("y").get() }; + const Double_t xCP { j.at("xCP").get() }; + const Double_t yCP { j.at("yCP").get() }; + const Double_t deltaXCP { j.at("deltaXCP").get() }; + const Double_t deltaYCP { j.at("deltaYCP").get() }; + + const Bool_t xFixed { j.at("xFixed").get() }; + const Bool_t yFixed { j.at("yFixed").get() }; + const Bool_t xCPFixed { j.at("xCPFixed").get() }; + const Bool_t yCPFixed { j.at("yCPFixed").get() }; + const Bool_t deltaXCPFixed { j.at("deltaXCPFixed").get() }; + const Bool_t deltaYCPFixed { j.at("deltaYCPFixed").get() }; + + const Bool_t deltaXCPSecondStage { j.at("deltaXCPSecondStage").get() }; + const Bool_t deltaYCPSecondStage { j.at("deltaYCPSecondStage").get() }; + + return { name, x, y, xCP, yCP, deltaXCP, deltaYCP, xFixed, yFixed, xCPFixed, yCPFixed, deltaXCPFixed, deltaYCPFixed, deltaXCPSecondStage, deltaYCPSecondStage }; +} + +void nlohmann::adl_serializer::to_json(json& j, const LauCartesianGammaCPCoeffSet& t) +{ + j["type"] = LauCoeffType::CartesianGammaCP; + j["name"] = t.name(); + + // TODO - handle cloned coeffs + + auto pars = t.getParameters(); + + j["x"] = pars[0]->value(); + j["y"] = pars[1]->value(); + j["xCP"] = pars[2]->value(); + j["yCP"] = pars[3]->value(); + j["deltaXCP"] = pars[4]->value(); + j["deltaYCP"] = pars[5]->value(); + + j["xFixed"] = pars[0]->fixed(); + j["yFixed"] = pars[1]->fixed(); + j["xCPFixed"] = pars[2]->fixed(); + j["yCPFixed"] = pars[3]->fixed(); + j["deltaXCPFixed"] = pars[4]->fixed(); + j["deltaYCPFixed"] = pars[5]->fixed(); + + j["deltaXCPSecondStage"] = pars[4]->secondStage(); + j["deltaYCPSecondStage"] = pars[5]->secondStage(); +} diff --git a/src/LauCategoryFlavTag.cc b/src/LauCategoryFlavTag.cc index bb1fd32..5c8706c 100644 --- a/src/LauCategoryFlavTag.cc +++ b/src/LauCategoryFlavTag.cc @@ -1,280 +1,280 @@ /* Copyright 2017 University of Warwick Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Laura++ package authors: John Back Paul Harrison Thomas Latham */ /*! \file LauCategoryFlavTag.cc \brief File containing implementation of LauCategoryFlavTag class. */ #include #include #include #include "TString.h" #include "TSystem.h" #include "LauCategoryFlavTag.hh" #include "LauFitDataTree.hh" #include "LauParameter.hh" ClassImp(LauCategoryFlavTag) LauCategoryFlavTag::LauCategoryFlavTag(const std::vector& params, const Bool_t useUntaggedEvents, const TString& tagVarName, const TString& tagCatVarName) : useUntaggedEvents_(useUntaggedEvents), signalTagCatFrac_(), tagVarName_(tagVarName), tagCatVarName_(tagCatVarName), validTagCats_(), curEvtTagFlv_(0), curEvtTagCat_(0), evtTagFlvVals_(0), evtTagCatVals_(0), dilution_(), deltaDilution_(), params_(params) { // Add the untagged category as a valid category this->addValidTagCat(0); // Set the fraction, average dilution and dilution difference for the untagged category this->setSignalTagCatPars(0, 1.0, 1.0, 0.0, kTRUE); } LauCategoryFlavTag::~LauCategoryFlavTag() { } void LauCategoryFlavTag::initialise() { this->checkSignalTagCatFractions(); } void LauCategoryFlavTag::addValidTagCats(const std::vector& tagCats) { for (std::vector::const_iterator iter = tagCats.begin(); iter != tagCats.end(); ++iter) { this->addValidTagCat(*iter); } } void LauCategoryFlavTag::addValidTagCat(const Int_t tagCat) { validTagCats_.insert(tagCat); } void LauCategoryFlavTag::setSignalTagCatPars(const Int_t tagCat, const Double_t tagCatFrac, const Double_t dilution, const Double_t deltaDilution, const Bool_t fixTCFrac) { if (!this->validTagCat(tagCat)) { std::cerr<<"ERROR in LauCategoryFlavTag::setSignalTagCatPars : Tagging category \""<first != 0) { const LauParameter& par = iter->second; totalTaggedFrac += par.value(); } } if ( ((totalTaggedFrac < (1.0-1.0e-8))&&!useUntaggedEvents_) || (totalTaggedFrac > (1.0+1.0e-8)) ) { std::cerr<<"WARNING in LauCategoryFlavTag::checkSignalTagCatFractions : Tagging category fractions add up to "<second; Double_t newVal = par.value() / totalTaggedFrac; par.value(newVal); par.initValue(newVal); par.genValue(newVal); } } else if (useUntaggedEvents_) { Double_t tagCatFrac = 1.0 - totalTaggedFrac; TString tagCatFracName("signalTagCatFrac0"); signalTagCatFrac_[0].name(tagCatFracName); signalTagCatFrac_[0].range(0.0,1.0); signalTagCatFrac_[0].value(tagCatFrac); signalTagCatFrac_[0].initValue(tagCatFrac); signalTagCatFrac_[0].genValue(tagCatFrac); signalTagCatFrac_[0].fixed(kTRUE); TString dilutionName("dilution0"); dilution_[0].name(dilutionName); dilution_[0].range(0.0,1.0); dilution_[0].value(0.0); dilution_[0].initValue(0.0); dilution_[0].genValue(0.0); dilution_[0].fixed(kTRUE); TString deltaDilutionName("deltaDilution0"); deltaDilution_[0].name(deltaDilutionName); deltaDilution_[0].range(-2.0,2.0); deltaDilution_[0].value(0.0); deltaDilution_[0].initValue(0.0); deltaDilution_[0].genValue(0.0); deltaDilution_[0].fixed(kTRUE); } for (LauTagCatParamMap::const_iterator iter=dilution_.begin(); iter!=dilution_.end(); ++iter) { - std::cout<<"INFO in LauCategoryFlavTag::checkSignalTagCatFractions : Setting dilution for tagging category "<<(*iter).first<<" to "<<(*iter).second<setFirstTagCatFrac(signalTagCatFrac_); // TODO - add background maps } void LauCategoryFlavTag::setFirstTagCatFrac(LauTagCatParamMap& theMap) { Double_t firstCatFrac = 1.0; Int_t firstCat(0); for (LauTagCatParamMap::iterator iter = theMap.begin(); iter != theMap.end(); ++iter) { if (iter == theMap.begin()) { firstCat = iter->first; continue; } LauParameter& par = iter->second; firstCatFrac -= par.unblindValue(); } theMap[firstCat].value(firstCatFrac); } Bool_t LauCategoryFlavTag::validTagCat(Int_t tagCat) const { return (validTagCats_.find(tagCat) != validTagCats_.end()); } std::set LauCategoryFlavTag::getValidTagCats() { return validTagCats_; } Bool_t LauCategoryFlavTag::checkTagCatFracMap(const LauTagCatParamMap& theMap) const { // TODO - this is for checking the the background maps are OK (so it is unused at the moment) // First check that there is an entry for each tagging category. // NB an entry won't have been added if it isn't a valid category // so don't need to check for that here. if (theMap.size() != signalTagCatFrac_.size()) { std::cerr<<"ERROR in LauCategoryFlavTag::checkTagCatFracMap : Not all tagging categories present."< 1E-10) { std::cerr<<"ERROR in LauCategoryFlavTag::checkTagCatFracMap : Tagging category event fractions do not sum to unity."<haveBranch( tagCatVarName_ ) ) { std::cerr << "ERROR in LauCategoryFlavTag::cacheInputFitVars : Input data does not contain branch \"" << tagCatVarName_ << "\"." << std::endl; gSystem->Exit(EXIT_FAILURE); } if ( ! inputFitData->haveBranch( tagVarName_ ) ) { std::cerr << "ERROR in LauCategoryFlavTag::cacheInputFitVars : Input data does not contain branch \"" << tagVarName_ << "\"." << std::endl; gSystem->Exit(EXIT_FAILURE); } UInt_t nEvents = inputFitData->nEvents(); evtTagCatVals_.reserve( nEvents ); evtTagFlvVals_.reserve( nEvents ); LauFitData::const_iterator fitdata_iter; for (UInt_t iEvt = 0; iEvt < nEvents; iEvt++) { const LauFitData& dataValues = inputFitData->getData(iEvt); fitdata_iter = dataValues.find( tagCatVarName_ ); curEvtTagCat_ = static_cast( fitdata_iter->second ); if ( ! this->validTagCat( curEvtTagCat_ ) ) { std::cerr << "WARNING in LauCategoryFlavTag::cacheInputFitVars : Invalid tagging category " << curEvtTagCat_ << " for event " << iEvt << ", setting it to untagged" << std::endl; curEvtTagCat_ = 0; } evtTagCatVals_.push_back( curEvtTagCat_ ); fitdata_iter = dataValues.find( tagVarName_ ); curEvtTagFlv_ = static_cast( fitdata_iter->second ); if ( TMath::Abs( curEvtTagFlv_ ) != 1 && curEvtTagCat_!=0) { if ( curEvtTagFlv_ > 0 ) { std::cerr << "WARNING in LauCategoryFlavTag::cacheInputFitVars : Invalid tagging output " << curEvtTagFlv_ << " for event " << iEvt << ", setting it to +1" << std::endl; curEvtTagFlv_ = +1; } else { std::cerr << "WARNING in LauCategoryFlavTag::cacheInputFitVars : Invalid tagging output " << curEvtTagFlv_ << " for event " << iEvt << ", setting it to -1" << std::endl; curEvtTagFlv_ = -1; } } evtTagFlvVals_.push_back( curEvtTagFlv_ ); } } LauParameter* LauCategoryFlavTag::findParameter(const TString& parName) { for ( std::vector::iterator iter = params_.begin(); iter != params_.end(); ++iter ) { if ((*iter)->name().Contains(parName)) { return (*iter); } } std::cerr << "ERROR in LauCategoryFlavTag::findParameter : Parameter \"" << parName << "\" not found." << std::endl; return 0; } diff --git a/src/LauCleoCPCoeffSet.cc b/src/LauCleoCPCoeffSet.cc index df417d3..9699313 100644 --- a/src/LauCleoCPCoeffSet.cc +++ b/src/LauCleoCPCoeffSet.cc @@ -1,334 +1,390 @@ /* 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 LauCleoCPCoeffSet.cc \brief File containing implementation of LauCleoCPCoeffSet class. */ #include #include #include #include "TMath.h" #include "TRandom.h" #include "LauCleoCPCoeffSet.hh" #include "LauComplex.hh" #include "LauConstants.hh" #include "LauParameter.hh" #include "LauPrint.hh" ClassImp(LauCleoCPCoeffSet) LauCleoCPCoeffSet::LauCleoCPCoeffSet(const TString& compName, const Double_t a, const Double_t delta, const Double_t b, const Double_t phi, const Bool_t aFixed, const Bool_t deltaFixed, const Bool_t bFixed, const Bool_t phiFixed, const Bool_t bSecondStage, const Bool_t phiSecondStage) : LauAbsCoeffSet{ compName }, a_{ std::make_unique("A", a, minMagnitude_, maxMagnitude_, aFixed) }, b_{ std::make_unique("B", b, minMagnitude_, maxMagnitude_, bFixed) }, delta_{ std::make_unique("Delta", delta, minPhase_, maxPhase_, deltaFixed) }, phi_{ std::make_unique("Phi", phi, minPhase_, maxPhase_, phiFixed) }, acp_{ "ACP", (-2.0*a*b)/(a*a + b*b), -1.0, 1.0, bFixed&&phiFixed } { if (bSecondStage && !bFixed) { b_->secondStage(kTRUE); b_->initValue(0.0); } if (phiSecondStage && !phiFixed) { phi_->secondStage(kTRUE); phi_->initValue(0.0); } } LauCleoCPCoeffSet::LauCleoCPCoeffSet(const LauCleoCPCoeffSet& rhs, const CloneOption cloneOption, const Double_t constFactor) : LauAbsCoeffSet{ rhs.name() }, particleCoeff_{ rhs.particleCoeff_ }, antiparticleCoeff_{ rhs.antiparticleCoeff_ }, acp_{ rhs.acp_ } { if ( cloneOption == CloneOption::All || cloneOption == CloneOption::TieMagnitude ) { a_.reset( rhs.a_->createClone(constFactor) ); } else { a_ = std::make_unique("A", rhs.a_->value(), minMagnitude_, maxMagnitude_, rhs.a_->fixed()); if ( rhs.a_->blind() ) { const LauBlind* blinder { rhs.a_->blinder() }; a_->blindParameter( blinder->blindingString(), blinder->blindingWidth() ); } } if ( cloneOption == CloneOption::All || cloneOption == CloneOption::TieCPPars ) { b_.reset( rhs.b_->createClone(constFactor) ); } else { b_ = std::make_unique("B", rhs.b_->value(), minMagnitude_, maxMagnitude_, rhs.b_->fixed()); if ( rhs.b_->blind() ) { const LauBlind* blinder { rhs.b_->blinder() }; b_->blindParameter( blinder->blindingString(), blinder->blindingWidth() ); } } if ( cloneOption == CloneOption::All || cloneOption == CloneOption::TiePhase ) { delta_.reset( rhs.delta_->createClone(constFactor) ); } else { delta_ = std::make_unique("Delta", rhs.delta_->value(), minPhase_, maxPhase_, rhs.delta_->fixed()); if ( rhs.delta_->blind() ) { const LauBlind* blinder { rhs.delta_->blinder() }; delta_->blindParameter( blinder->blindingString(), blinder->blindingWidth() ); } } if ( cloneOption == CloneOption::All || cloneOption == CloneOption::TieCPPars ) { phi_.reset( rhs.phi_->createClone(constFactor) ); } else { phi_ = std::make_unique("Phi", rhs.phi_->value(), minPhase_, maxPhase_, rhs.phi_->fixed()); if ( rhs.phi_->blind() ) { const LauBlind* blinder { rhs.phi_->blinder() }; phi_->blindParameter( blinder->blindingString(), blinder->blindingWidth() ); } } } std::vector LauCleoCPCoeffSet::getParameters() { - return { a_.get(), b_.get(), delta_.get(), phi_.get() }; + return { a_.get(), delta_.get(), b_.get(), phi_.get() }; +} + +std::vector LauCleoCPCoeffSet::getParameters() const +{ + return { a_.get(), delta_.get(), b_.get(), phi_.get() }; } void LauCleoCPCoeffSet::printParValues() const { std::cout<<"INFO in LauCleoCPCoeffSet::printParValues : Component \""<name()<<"\" has "; std::cout<<"a-magnitude = "<value()<<",\t"; std::cout<<"delta = "<value()<<",\t"; std::cout<<"b-magnitude = "<value()<<",\t"; std::cout<<"phi = "<value()<<"."<name() }; resName = resName.ReplaceAll("_", "\\_"); stream<value()); stream<<" \\pm "; print.printFormat(stream, a_->error()); stream<<"$ & $"; print.printFormat(stream, delta_->value()); stream<<" \\pm "; print.printFormat(stream, delta_->error()); stream<<"$ & $"; print.printFormat(stream, b_->value()); stream<<" \\pm "; print.printFormat(stream, b_->error()); stream<<"$ & $"; print.printFormat(stream, phi_->value()); stream<<" \\pm "; print.printFormat(stream, phi_->error()); stream<<"$ \\\\"<fixed() == kFALSE) { // Choose an a-magnitude between 0.0 and 2.0 const Double_t mag { LauAbsCoeffSet::getRandomiser()->Rndm()*2.0 }; a_->initValue(mag); a_->value(mag); } if (b_->fixed() == kFALSE && b_->secondStage() == kFALSE) { // Choose a b-magnitude between 0.0 and 0.1 const Double_t mag { LauAbsCoeffSet::getRandomiser()->Rndm()*0.1 }; b_->initValue(mag); b_->value(mag); } if (delta_->fixed() == kFALSE) { // Choose a phase between +- pi const Double_t phase { LauAbsCoeffSet::getRandomiser()->Rndm()*LauConstants::twoPi - LauConstants::pi }; delta_->initValue(phase); delta_->value(phase); } if (phi_->fixed() == kFALSE && phi_->secondStage() == kFALSE) { // Choose a phase between +- pi const Double_t phase { LauAbsCoeffSet::getRandomiser()->Rndm()*LauConstants::twoPi - LauConstants::pi }; phi_->initValue(phase); phi_->value(phase); } } void LauCleoCPCoeffSet::finaliseValues() { // retrieve the current values from the parameters Double_t aVal { a_->value() }; Double_t bVal { b_->value() }; Double_t deltaVal { delta_->value() }; Double_t phiVal { phi_->value() }; // Check whether we have a negative "a" magnitude. // If so make it positive and add pi to the "delta" phase. if (aVal < 0.0) { aVal *= -1.0; bVal *= -1.0; deltaVal += LauConstants::pi; } // Check now whether the phases lies in the right range (-pi to pi). Bool_t deltaWithinRange{kFALSE}; Bool_t phiWithinRange{kFALSE}; while (deltaWithinRange == kFALSE && phiWithinRange == kFALSE) { if (deltaVal > -LauConstants::pi && deltaVal < LauConstants::pi) { deltaWithinRange = kTRUE; } else { // Not within the specified range if (deltaVal > LauConstants::pi) { deltaVal -= LauConstants::twoPi; } else if (deltaVal < -LauConstants::pi) { deltaVal += LauConstants::twoPi; } } if (phiVal > -LauConstants::pi && phiVal < LauConstants::pi) { phiWithinRange = kTRUE; } else { // Not within the specified range if (phiVal > LauConstants::pi) { phiVal -= LauConstants::twoPi; } else if (phiVal < -LauConstants::pi) { phiVal += 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. const Double_t genDelta { delta_->genValue() }; const Double_t genPhi { phi_->genValue() }; Double_t diff { deltaVal - genDelta }; if (diff > LauConstants::pi) { deltaVal -= LauConstants::twoPi; } else if (diff < -LauConstants::pi) { deltaVal += LauConstants::twoPi; } diff = phiVal - genPhi; if (diff > LauConstants::pi) { phiVal -= LauConstants::twoPi; } else if (diff < -LauConstants::pi) { phiVal += LauConstants::twoPi; } // finally store the new values in the parameters // and update the pulls a_->value(aVal); a_->updatePull(); b_->value(bVal); b_->updatePull(); delta_->value(deltaVal); delta_->updatePull(); phi_->value(phiVal); phi_->updatePull(); } const LauComplex& LauCleoCPCoeffSet::particleCoeff() { const Double_t magnitude { a_->unblindValue() + b_->unblindValue() }; const Double_t phase { delta_->unblindValue() + phi_->unblindValue() }; particleCoeff_.setRealImagPart(magnitude*TMath::Cos(phase), magnitude*TMath::Sin(phase)); return particleCoeff_; } const LauComplex& LauCleoCPCoeffSet::antiparticleCoeff() { const Double_t magnitude { a_->unblindValue() - b_->unblindValue() }; const Double_t phase { delta_->unblindValue() - phi_->unblindValue() }; antiparticleCoeff_.setRealImagPart(magnitude*TMath::Cos(phase), magnitude*TMath::Sin(phase)); return antiparticleCoeff_; } void LauCleoCPCoeffSet::setCoeffValues( const LauComplex& coeff, const LauComplex& coeffBar, const Bool_t init ) { const Double_t mag { coeff.abs() }; const Double_t magBar { coeffBar.abs() }; const Double_t phase { coeff.arg() }; const Double_t phaseBar { coeffBar.arg() }; const Double_t aVal{ 0.5 * ( mag + magBar ) }; const Double_t deltaVal{ 0.5 * ( phase + phaseBar ) }; const Double_t bVal{ 0.5 * ( mag - magBar ) }; const Double_t phiVal{ 0.5 * ( phase - phaseBar ) }; a_->value( aVal ); delta_->value( deltaVal ); b_->value( bVal ); phi_->value( phiVal ); if ( init ) { a_->genValue( aVal ); delta_->genValue( deltaVal ); b_->genValue( bVal ); phi_->genValue( phiVal ); a_->initValue( aVal ); delta_->initValue( deltaVal ); b_->initValue( bVal ); phi_->initValue( phiVal ); } } LauParameter LauCleoCPCoeffSet::acp() { // set the name const TString parName{ this->baseName() + "_ACP" }; acp_.name(parName); // work out the ACP value const Double_t numer { -2.0*a_->value()*b_->value() }; const Double_t denom { a_->value()*a_->value() + b_->value()*b_->value() }; const Double_t value { numer/denom }; // is it fixed? const Bool_t fixed { a_->fixed() && b_->fixed() }; acp_.fixed(fixed); // we can't work out the error without the covariance matrix const Double_t error{0.0}; // set the value and error acp_.valueAndErrors(value,error); return acp_; } LauCleoCPCoeffSet* LauCleoCPCoeffSet::createClone_impl(const TString& newName, const CloneOption cloneOption, const Double_t constFactor) { if ( ! ( cloneOption == CloneOption::All || cloneOption == CloneOption::TiePhase || cloneOption == CloneOption::TieMagnitude || cloneOption == CloneOption::TieCPPars ) ) { std::cerr << "ERROR in LauCleoCPCoeffSet::createClone : Invalid clone option" << std::endl; return nullptr; } auto clone = new LauCleoCPCoeffSet{ *this, cloneOption, constFactor }; clone->name( newName ); return clone; } + +LauCleoCPCoeffSet nlohmann::adl_serializer::from_json(const json& j) +{ + const LauCoeffType type { j.at("type").get() }; + if ( type != LauCoeffType::CleoCP ) { + throw LauWrongCoeffType("Wrong coefficient type given to construct LauCleoCPCoeffSet"); + } + + const TString name { j.at("name").get().c_str() }; + + // TODO - handle cloned coeffs + + const Double_t a { j.at("a").get() }; + const Double_t delta { j.at("delta").get() }; + const Double_t b { j.at("b").get() }; + const Double_t phi { j.at("phi").get() }; + + const Bool_t aFixed { j.at("aFixed").get() }; + const Bool_t deltaFixed { j.at("deltaFixed").get() }; + const Bool_t bFixed { j.at("bFixed").get() }; + const Bool_t phiFixed { j.at("phiFixed").get() }; + + // TODO - these should be optional? + const Bool_t bSecondStage { j.at("bSecondStage").get() }; + const Bool_t phiSecondStage { j.at("phiSecondStage").get() }; + + return { name, a, delta, b, phi, aFixed, deltaFixed, bFixed, phiFixed, bSecondStage, phiSecondStage }; +} + +void nlohmann::adl_serializer::to_json(json& j, const LauCleoCPCoeffSet& t) +{ + j["type"] = LauCoeffType::CleoCP; + j["name"] = t.name(); + + // TODO - handle cloned coeffs + + auto pars = t.getParameters(); + + j["a"] = pars[0]->value(); + j["delta"] = pars[1]->value(); + j["b"] = pars[2]->value(); + j["phi"] = pars[3]->value(); + + j["aFixed"] = pars[0]->fixed(); + j["deltaFixed"] = pars[1]->fixed(); + j["bFixed"] = pars[2]->fixed(); + j["phiFixed"] = pars[3]->fixed(); + + j["bSecondStage"] = pars[2]->secondStage(); + j["phiSecondStage"] = pars[3]->secondStage(); +} diff --git a/src/LauMagPhaseCPCoeffSet.cc b/src/LauMagPhaseCPCoeffSet.cc index e18f4e6..61f568f 100644 --- a/src/LauMagPhaseCPCoeffSet.cc +++ b/src/LauMagPhaseCPCoeffSet.cc @@ -1,309 +1,358 @@ /* Copyright 2011 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 LauMagPhaseCPCoeffSet.cc \brief File containing implementation of LauMagPhaseCPCoeffSet class. */ #include #include #include #include "TMath.h" #include "TRandom.h" #include "LauMagPhaseCPCoeffSet.hh" #include "LauComplex.hh" #include "LauConstants.hh" #include "LauParameter.hh" #include "LauPrint.hh" ClassImp(LauMagPhaseCPCoeffSet) LauMagPhaseCPCoeffSet::LauMagPhaseCPCoeffSet(const TString& compName, const Double_t mag, const Double_t phase, const Double_t magBar, const Double_t phaseBar, const Bool_t magFixed, const Bool_t phaseFixed, const Bool_t magBarFixed, const Bool_t phaseBarFixed) : LauAbsCoeffSet{ compName }, mag_{ std::make_unique("Mag", mag, minMagnitude_, maxMagnitude_, magFixed) }, phase_{ std::make_unique("Phase", phase, minPhase_, maxPhase_, phaseFixed) }, magBar_{ std::make_unique("MagBar", magBar, minMagnitude_, maxMagnitude_, magBarFixed) }, phaseBar_{ std::make_unique("PhaseBar", phaseBar, minPhase_, maxPhase_, phaseBarFixed) }, acp_{ "ACP", (magBar*magBar - mag*mag)/(magBar*magBar + mag*mag), -1.0, 1.0 } { } LauMagPhaseCPCoeffSet::LauMagPhaseCPCoeffSet(const LauMagPhaseCPCoeffSet& rhs, CloneOption cloneOption, Double_t constFactor) : LauAbsCoeffSet{ rhs.name() }, particleCoeff_{ rhs.particleCoeff_ }, antiparticleCoeff_{ rhs.antiparticleCoeff_ }, acp_{ rhs.acp_ } { if ( cloneOption == CloneOption::All || cloneOption == CloneOption::TieMagnitude ) { mag_.reset( rhs.mag_->createClone(constFactor) ); magBar_.reset( rhs.magBar_->createClone(constFactor) ); } else { mag_ = std::make_unique("Mag", rhs.mag_->value(), minMagnitude_, maxMagnitude_, rhs.mag_->fixed()); if ( rhs.mag_->blind() ) { const LauBlind* blinder { rhs.mag_->blinder() }; mag_->blindParameter( blinder->blindingString(), blinder->blindingWidth() ); } magBar_ = std::make_unique("MagBar", rhs.magBar_->value(), minMagnitude_, maxMagnitude_, rhs.magBar_->fixed()); if ( rhs.magBar_->blind() ) { const LauBlind* blinder { rhs.magBar_->blinder() }; magBar_->blindParameter( blinder->blindingString(), blinder->blindingWidth() ); } } if ( cloneOption == CloneOption::All || cloneOption == CloneOption::TiePhase ) { phase_.reset( rhs.phase_->createClone(constFactor) ); phaseBar_.reset( rhs.phaseBar_->createClone(constFactor) ); } else { phase_ = std::make_unique("Phase", rhs.phase_->value(), minPhase_, maxPhase_, rhs.phase_->fixed()); if ( rhs.phase_->blind() ) { const LauBlind* blinder { rhs.phase_->blinder() }; phase_->blindParameter( blinder->blindingString(), blinder->blindingWidth() ); } phaseBar_ = std::make_unique("PhaseBar", rhs.phaseBar_->value(), minPhase_, maxPhase_, rhs.phaseBar_->fixed()); if ( rhs.phaseBar_->blind() ) { const LauBlind* blinder { rhs.phaseBar_->blinder() }; phaseBar_->blindParameter( blinder->blindingString(), blinder->blindingWidth() ); } } } std::vector LauMagPhaseCPCoeffSet::getParameters() { return { mag_.get(), phase_.get(), magBar_.get(), phaseBar_.get() }; } +std::vector LauMagPhaseCPCoeffSet::getParameters() const +{ + return { mag_.get(), phase_.get(), magBar_.get(), phaseBar_.get() }; +} + void LauMagPhaseCPCoeffSet::printParValues() const { std::cout<<"INFO in LauMagPhaseCPCoeffSet::printParValues : Component \""<name()<<"\" has "; std::cout<<"mag = "<value()<<",\t"; std::cout<<"phase = "<value()<<",\t"; std::cout<<"magBar = "<value()<<",\t"; std::cout<<"phaseBar = "<value()<<"."<name() }; resName = resName.ReplaceAll("_", "\\_"); stream<value()); stream<<" \\pm "; print.printFormat(stream, mag_->error()); stream<<"$ & $"; print.printFormat(stream, phase_->value()); stream<<" \\pm "; print.printFormat(stream, phase_->error()); stream<<"$ & $"; print.printFormat(stream, magBar_->value()); stream<<" \\pm "; print.printFormat(stream, magBar_->error()); stream<<"$ & $"; print.printFormat(stream, phaseBar_->value()); stream<<" \\pm "; print.printFormat(stream, phaseBar_->error()); stream<<"$ \\\\"<fixed() == kFALSE) { // Choose a value for "magnitude" between 0.0 and 2.0 const Double_t value { LauAbsCoeffSet::getRandomiser()->Rndm()*2.0 }; mag_->initValue(value); mag_->value(value); } if (phase_->fixed() == kFALSE) { // Choose a phase between +- pi const Double_t value { LauAbsCoeffSet::getRandomiser()->Rndm()*LauConstants::twoPi - LauConstants::pi }; phase_->initValue(value); phase_->value(value); } if (magBar_->fixed() == kFALSE) { // Choose a value for "magnitude" between 0.0 and 2.0 const Double_t value { LauAbsCoeffSet::getRandomiser()->Rndm()*2.0 }; magBar_->initValue(value); magBar_->value(value); } if (phaseBar_->fixed() == kFALSE) { // Choose a phase between +- pi const Double_t value { LauAbsCoeffSet::getRandomiser()->Rndm()*LauConstants::twoPi - LauConstants::pi }; phaseBar_->initValue(value); phaseBar_->value(value); } } void LauMagPhaseCPCoeffSet::finaliseValues() { // retrieve the current values from the parameters Double_t mVal{ mag_->value() }; Double_t pVal{ phase_->value() }; Double_t mBarVal{ magBar_->value() }; Double_t pBarVal{ phaseBar_->value() }; // Check whether we have a negative magnitude. // If so make it positive and add pi to the phase. if (mVal < 0.0) { mVal *= -1.0; pVal += LauConstants::pi; } if (mBarVal < 0.0) { mBarVal *= -1.0; pBarVal += LauConstants::pi; } // Check now whether the phases lies in the right range (-pi to pi). Bool_t pWithinRange{kFALSE}; Bool_t pBarWithinRange{kFALSE}; while (pWithinRange == kFALSE && pBarWithinRange == kFALSE) { if (pVal > -LauConstants::pi && pVal < LauConstants::pi) { pWithinRange = kTRUE; } else { // Not within the specified range if (pVal > LauConstants::pi) { pVal -= LauConstants::twoPi; } else if (pVal < -LauConstants::pi) { pVal += LauConstants::twoPi; } } if (pBarVal > -LauConstants::pi && pBarVal < LauConstants::pi) { pBarWithinRange = kTRUE; } else { // Not within the specified range if (pBarVal > LauConstants::pi) { pBarVal -= LauConstants::twoPi; } else if (pBarVal < -LauConstants::pi) { pBarVal += 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. const Double_t genPhase { phase_->genValue() }; const Double_t genPhaseBar { phaseBar_->genValue() }; Double_t diff { pVal - genPhase }; if (diff > LauConstants::pi) { pVal -= LauConstants::twoPi; } else if (diff < -LauConstants::pi) { pVal += LauConstants::twoPi; } diff = pBarVal - genPhaseBar; if (diff > LauConstants::pi) { pBarVal -= LauConstants::twoPi; } else if (diff < -LauConstants::pi) { pBarVal += LauConstants::twoPi; } // finally store the new values in the parameters // and update the pulls mag_->value(mVal); mag_->updatePull(); phase_->value(pVal); phase_->updatePull(); magBar_->value(mBarVal); magBar_->updatePull(); phaseBar_->value(pBarVal); phaseBar_->updatePull(); } const LauComplex& LauMagPhaseCPCoeffSet::particleCoeff() { particleCoeff_.setRealImagPart( mag_->unblindValue()*TMath::Cos(phase_->unblindValue()), mag_->unblindValue()*TMath::Sin(phase_->unblindValue()) ); return particleCoeff_; } const LauComplex& LauMagPhaseCPCoeffSet::antiparticleCoeff() { antiparticleCoeff_.setRealImagPart( magBar_->unblindValue()*TMath::Cos(phaseBar_->unblindValue()), magBar_->unblindValue()*TMath::Sin(phaseBar_->unblindValue()) ); return antiparticleCoeff_; } void LauMagPhaseCPCoeffSet::setCoeffValues( const LauComplex& coeff, const LauComplex& coeffBar, Bool_t init ) { const Double_t magVal{ coeff.abs() }; const Double_t phaseVal{ coeff.arg() }; const Double_t magBarVal{ coeffBar.abs() }; const Double_t phaseBarVal{ coeffBar.arg() }; mag_->value( magVal ); phase_->value( phaseVal ); magBar_->value( magBarVal ); phaseBar_->value( phaseBarVal ); if ( init ) { mag_->genValue( magVal ); phase_->genValue( phaseVal ); magBar_->genValue( magBarVal ); phaseBar_->genValue( phaseBarVal ); mag_->initValue( magVal ); phase_->initValue( phaseVal ); magBar_->initValue( magBarVal ); phaseBar_->initValue( phaseBarVal ); } } LauParameter LauMagPhaseCPCoeffSet::acp() { // set the name const TString parName{ this->baseName() + "_ACP" }; acp_.name(parName); // work out the ACP value const Double_t value { (magBar_->value()*magBar_->value() - mag_->value()*mag_->value())/(magBar_->value()*magBar_->value() + mag_->value()*mag_->value()) }; // is it fixed? const Bool_t fixed { magBar_->fixed() && mag_->fixed() }; acp_.fixed(fixed); // we can't work out the error without the covariance matrix const Double_t error{0.0}; // set the value and error acp_.valueAndErrors(value,error); return acp_; } LauMagPhaseCPCoeffSet* LauMagPhaseCPCoeffSet::createClone_impl(const TString& newName, const CloneOption cloneOption, const Double_t constFactor) { if ( ! ( cloneOption == CloneOption::All || cloneOption == CloneOption::TiePhase || cloneOption == CloneOption::TieMagnitude ) ) { std::cerr << "ERROR in LauMagPhaseCPCoeffSet::createClone : Invalid clone option" << std::endl; return nullptr; } auto clone = new LauMagPhaseCPCoeffSet{ *this, cloneOption, constFactor }; clone->name( newName ); return clone; } + +LauMagPhaseCPCoeffSet nlohmann::adl_serializer::from_json(const json& j) +{ + const LauCoeffType type { j.at("type").get() }; + if ( type != LauCoeffType::MagPhaseCP ) { + throw LauWrongCoeffType("Wrong coefficient type given to construct LauMagPhaseCPCoeffSet"); + } + + const TString name { j.at("name").get().c_str() }; + + // TODO - handle cloned coeffs + + const Double_t mag { j.at("mag").get() }; + const Double_t phase { j.at("phase").get() }; + const Double_t magBar { j.at("magBar").get() }; + const Double_t phaseBar { j.at("phaseBar").get() }; + + const Bool_t magFixed { j.at("magFixed").get() }; + const Bool_t phaseFixed { j.at("phaseFixed").get() }; + const Bool_t magBarFixed { j.at("magBarFixed").get() }; + const Bool_t phaseBarFixed { j.at("phaseBarFixed").get() }; + + return { name, mag, phase, magBar, phaseBar, magFixed, phaseFixed, magBarFixed, phaseBarFixed }; +} + +void nlohmann::adl_serializer::to_json(json& j, const LauMagPhaseCPCoeffSet& t) +{ + j["type"] = LauCoeffType::MagPhaseCP; + j["name"] = t.name(); + + // TODO - handle cloned coeffs + + auto pars = t.getParameters(); + + j["mag"] = pars[0]->value(); + j["phase"] = pars[1]->value(); + j["magBar"] = pars[2]->value(); + j["phaseBar"] = pars[3]->value(); + + j["magFixed"] = pars[0]->fixed(); + j["phaseFixed"] = pars[1]->fixed(); + j["magBarFixed"] = pars[2]->fixed(); + j["phaseBarFixed"] = pars[3]->fixed(); +} diff --git a/src/LauMagPhaseCoeffSet.cc b/src/LauMagPhaseCoeffSet.cc index e627857..443a833 100644 --- a/src/LauMagPhaseCoeffSet.cc +++ b/src/LauMagPhaseCoeffSet.cc @@ -1,218 +1,257 @@ /* 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 LauMagPhaseCoeffSet.cc \brief File containing implementation of LauMagPhaseCoeffSet class. */ #include #include #include #include "TMath.h" #include "TRandom.h" #include "LauComplex.hh" #include "LauConstants.hh" #include "LauMagPhaseCoeffSet.hh" #include "LauParameter.hh" #include "LauPrint.hh" ClassImp(LauMagPhaseCoeffSet) LauMagPhaseCoeffSet::LauMagPhaseCoeffSet(const TString& compName, const Double_t magnitude, const Double_t phase, const Bool_t magFixed, const Bool_t phaseFixed) : LauAbsCoeffSet{ compName }, magnitude_{ std::make_unique("A",magnitude,minMagnitude_,maxMagnitude_,magFixed) }, phase_{ std::make_unique("Delta",phase,minPhase_,maxPhase_,phaseFixed) } { } LauMagPhaseCoeffSet::LauMagPhaseCoeffSet(const LauMagPhaseCoeffSet& rhs, const CloneOption cloneOption, const Double_t constFactor) : LauAbsCoeffSet{ rhs.name() }, coeff_{ rhs.coeff_ } { if ( cloneOption == CloneOption::All || cloneOption == CloneOption::TieMagnitude ) { magnitude_.reset( rhs.magnitude_->createClone(constFactor) ); } else { magnitude_ = std::make_unique("A", rhs.magnitude_->value(), minMagnitude_, maxMagnitude_, rhs.magnitude_->fixed()); if ( rhs.magnitude_->blind() ) { const LauBlind* blinder { rhs.magnitude_->blinder() }; magnitude_->blindParameter( blinder->blindingString(), blinder->blindingWidth() ); } } if ( cloneOption == CloneOption::All || cloneOption == CloneOption::TiePhase ) { phase_.reset( rhs.phase_->createClone(constFactor) ); } else { phase_ = std::make_unique("Delta", rhs.phase_->value(), minPhase_, maxPhase_, rhs.phase_->fixed()); if ( rhs.phase_->blind() ) { const LauBlind* blinder { rhs.phase_->blinder() }; phase_->blindParameter( blinder->blindingString(), blinder->blindingWidth() ); } } } std::vector LauMagPhaseCoeffSet::getParameters() { return { magnitude_.get(), phase_.get() }; } +std::vector LauMagPhaseCoeffSet::getParameters() const +{ + return { magnitude_.get(), phase_.get() }; +} + void LauMagPhaseCoeffSet::printParValues() const { std::cout<<"INFO in LauMagPhaseCoeffSet::printParValues : Component \""<name()<<"\" has magnitude = "<value()<<" and phase = "<value()<<"."<name() }; resName = resName.ReplaceAll("_", "\\_"); stream<value()); stream<<" \\pm "; print.printFormat(stream, magnitude_->error()); stream<<"$ & $"; print.printFormat(stream, phase_->value()); stream<<" \\pm "; print.printFormat(stream, phase_->error()); stream<<"$ \\\\"<fixed() == kFALSE) { // Choose a magnitude between 0.0 and 2.0 const Double_t mag { LauAbsCoeffSet::getRandomiser()->Rndm()*2.0 }; magnitude_->initValue(mag); magnitude_->value(mag); } if (phase_->fixed() == kFALSE) { // Choose a phase between +- pi const Double_t phase { LauAbsCoeffSet::getRandomiser()->Rndm()*LauConstants::twoPi - LauConstants::pi }; phase_->initValue(phase); phase_->value(phase); } } void LauMagPhaseCoeffSet::finaliseValues() { // retrieve the current values from the parameters Double_t mag { magnitude_->value() }; Double_t phase { phase_->value() }; // Check whether we have a negative magnitude. // If so make it positive and add pi to the phase. if (mag < 0.0) { mag *= -1.0; phase += LauConstants::pi; } // 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. const Double_t genPhase { phase_->genValue() }; const Double_t diff { phase - genPhase }; if (diff > LauConstants::pi) { phase -= LauConstants::twoPi; } else if (diff < -LauConstants::pi) { phase += LauConstants::twoPi; } // finally store the new values in the parameters // and update the pulls magnitude_->value(mag); magnitude_->updatePull(); phase_->value(phase); phase_->updatePull(); } const LauComplex& LauMagPhaseCoeffSet::particleCoeff() { coeff_.setRealImagPart(magnitude_->unblindValue()*TMath::Cos(phase_->unblindValue()), magnitude_->unblindValue()*TMath::Sin(phase_->unblindValue())); return coeff_; } const LauComplex& LauMagPhaseCoeffSet::antiparticleCoeff() { return this->particleCoeff(); } void LauMagPhaseCoeffSet::setCoeffValues( const LauComplex& coeff, const LauComplex& coeffBar, const Bool_t init ) { LauComplex average{ coeff }; average += coeffBar; average.rescale( 0.5 ); const Double_t magVal{ average.abs() }; const Double_t phaseVal{ average.arg() }; magnitude_->value( magVal ); phase_->value( phaseVal ); if ( init ) { magnitude_->genValue( magVal ); phase_->genValue( phaseVal ); magnitude_->initValue( magVal ); phase_->initValue( phaseVal ); } } LauParameter LauMagPhaseCoeffSet::acp() { const TString parName{ this->baseName() + "_ACP" }; return LauParameter{ parName, 0.0 }; } LauMagPhaseCoeffSet* LauMagPhaseCoeffSet::createClone_impl(const TString& newName, const CloneOption cloneOption, const Double_t constFactor) { if ( ! ( cloneOption == CloneOption::All || cloneOption == CloneOption::TiePhase || cloneOption == CloneOption::TieMagnitude ) ) { std::cerr << "ERROR in LauMagPhaseCoeffSet::createClone : Invalid clone option" << std::endl; return nullptr; } auto clone = new LauMagPhaseCoeffSet{ *this, cloneOption, constFactor }; clone->name( newName ); return clone; } + +LauMagPhaseCoeffSet nlohmann::adl_serializer::from_json(const json& j) +{ + const LauCoeffType type { j.at("type").get() }; + if ( type != LauCoeffType::MagPhase ) { + throw LauWrongCoeffType("Wrong coefficient type given to construct LauMagPhaseCoeffSet"); + } + + const TString name { j.at("name").get().c_str() }; + + // TODO - handle cloned coeffs + + const Double_t mag { j.at("mag").get() }; + const Double_t phase { j.at("phase").get() }; + const Bool_t magFixed { j.at("magFixed").get() }; + const Bool_t phaseFixed { j.at("phaseFixed").get() }; + + return { name, mag, phase, magFixed, phaseFixed }; +} + +void nlohmann::adl_serializer::to_json(json& j, const LauMagPhaseCoeffSet& t) +{ + j["type"] = LauCoeffType::MagPhase; + j["name"] = t.name(); + + // TODO - handle cloned coeffs + + auto pars = t.getParameters(); + + j["mag"] = pars[0]->value(); + j["phase"] = pars[1]->value(); + j["magFixed"] = pars[0]->fixed(); + j["phaseFixed"] = pars[1]->fixed(); +} diff --git a/src/LauNSCCartesianCPCoeffSet.cc b/src/LauNSCCartesianCPCoeffSet.cc index 1f6f815..1fcf04d 100644 --- a/src/LauNSCCartesianCPCoeffSet.cc +++ b/src/LauNSCCartesianCPCoeffSet.cc @@ -1,315 +1,406 @@ /* Copyright 2015 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 LauNSCCartesianCPCoeffSet.cc \brief File containing implementation of LauNSCCartesianCPCoeffSet class. */ #include #include #include #include "TMath.h" #include "TRandom.h" #include "LauNSCCartesianCPCoeffSet.hh" #include "LauComplex.hh" #include "LauConstants.hh" #include "LauParameter.hh" #include "LauPrint.hh" #include "LauRandom.hh" ClassImp(LauNSCCartesianCPCoeffSet) LauNSCCartesianCPCoeffSet::LauNSCCartesianCPCoeffSet(const TString& compName, const Bool_t finalStateIsF, const Double_t x, const Double_t y, const Double_t deltaX, const Double_t deltaY, const Bool_t xFixed, const Bool_t yFixed, const Bool_t deltaXFixed, const Bool_t deltaYFixed, const Bool_t deltaXSecondStage, const Bool_t deltaYSecondStage, const Double_t xPrime, const Double_t yPrime, const Double_t deltaXPrime, const Double_t deltaYPrime, const Bool_t xPrimeFixed, const Bool_t yPrimeFixed, const Bool_t deltaXPrimeFixed, const Bool_t deltaYPrimeFixed, const Bool_t deltaXPrimeSecondStage, const Bool_t deltaYPrimeSecondStage ) : LauAbsCoeffSet{ compName }, finalStateIsF_{ finalStateIsF }, x_{ std::make_unique("X", x, minRealImagPart_, maxRealImagPart_, xFixed) }, y_{ std::make_unique("Y", y, minRealImagPart_, maxRealImagPart_, yFixed) }, deltaX_{ std::make_unique("DeltaX", deltaX, minDelta_, maxDelta_, deltaXFixed) }, deltaY_{ std::make_unique("DeltaY", deltaY, minDelta_, maxDelta_, deltaYFixed) }, xPrime_{ std::make_unique("XPrime", xPrime, minRealImagPart_, maxRealImagPart_, xPrimeFixed) }, yPrime_{ std::make_unique("YPrime", yPrime, minRealImagPart_, maxRealImagPart_, yPrimeFixed) }, deltaXPrime_{ std::make_unique("DeltaXPrime", deltaXPrime, minDelta_, maxDelta_, deltaXPrimeFixed) }, deltaYPrime_{ std::make_unique("DeltaYPrime", deltaYPrime, minDelta_, maxDelta_, deltaYPrimeFixed) }, acp_{ "ACP", 0.0, -1.0, 1.0, kTRUE } { if (deltaXSecondStage && !deltaXFixed) { deltaX_->secondStage(kTRUE); deltaX_->initValue(0.0); } if (deltaYSecondStage && !deltaYFixed) { deltaY_->secondStage(kTRUE); deltaY_->initValue(0.0); } if (deltaXPrimeSecondStage && !deltaXPrimeFixed) { deltaXPrime_->secondStage(kTRUE); deltaXPrime_->initValue(0.0); } if (deltaYPrimeSecondStage && !deltaYPrimeFixed) { deltaYPrime_->secondStage(kTRUE); deltaYPrime_->initValue(0.0); } } LauNSCCartesianCPCoeffSet::LauNSCCartesianCPCoeffSet(const LauNSCCartesianCPCoeffSet& rhs, const CloneOption cloneOption, const Double_t constFactor) : LauAbsCoeffSet{ rhs.name() }, finalStateIsF_{ rhs.finalStateIsF_ }, coeffAf_{ rhs.coeffAf_ }, coeffAfbar_{ rhs.coeffAfbar_ }, coeffAbarf_{ rhs.coeffAbarf_ }, coeffAbarfbar_{ rhs.coeffAbarfbar_ }, acp_{ rhs.acp_ } { if ( cloneOption == CloneOption::All || cloneOption == CloneOption::TieRealPart ) { x_.reset( rhs.x_->createClone(constFactor) ); xPrime_.reset( rhs.xPrime_->createClone(constFactor) ); } else { x_ = std::make_unique("X", rhs.x_->value(), minRealImagPart_, maxRealImagPart_, rhs.x_->fixed()); xPrime_ = std::make_unique("XPrime", rhs.xPrime_->value(), minRealImagPart_, maxRealImagPart_, rhs.xPrime_->fixed()); } if ( cloneOption == CloneOption::All || cloneOption == CloneOption::TieImagPart ) { y_.reset( rhs.y_->createClone(constFactor) ); yPrime_.reset( rhs.yPrime_->createClone(constFactor) ); } else { y_ = std::make_unique("Y", rhs.y_->value(), minRealImagPart_, maxRealImagPart_, rhs.y_->fixed()); yPrime_ = std::make_unique("YPrime", rhs.yPrime_->value(), minRealImagPart_, maxRealImagPart_, rhs.yPrime_->fixed()); } if ( cloneOption == CloneOption::All || cloneOption == CloneOption::TieCPPars ) { deltaX_.reset( rhs.deltaX_->createClone(constFactor) ); deltaY_.reset( rhs.deltaY_->createClone(constFactor) ); deltaXPrime_.reset( rhs.deltaXPrime_->createClone(constFactor) ); deltaYPrime_.reset( rhs.deltaYPrime_->createClone(constFactor) ); } else { deltaX_ = std::make_unique("DeltaX", rhs.deltaX_->value(), minDelta_, maxDelta_, rhs.deltaX_->fixed()); deltaY_ = std::make_unique("DeltaY", rhs.deltaY_->value(), minDelta_, maxDelta_, rhs.deltaY_->fixed()); deltaXPrime_ = std::make_unique("DeltaXPrime", rhs.deltaXPrime_->value(), minDelta_, maxDelta_, rhs.deltaXPrime_->fixed()); deltaYPrime_ = std::make_unique("DeltaYPrime", rhs.deltaYPrime_->value(), minDelta_, maxDelta_, rhs.deltaYPrime_->fixed()); if ( rhs.deltaX_->secondStage() && !rhs.deltaX_->fixed() ) { deltaX_->secondStage(kTRUE); deltaX_->initValue(0.0); } if ( rhs.deltaY_->secondStage() && !rhs.deltaY_->fixed() ) { deltaY_->secondStage(kTRUE); deltaY_->initValue(0.0); } if ( rhs.deltaXPrime_->secondStage() && !rhs.deltaXPrime_->fixed() ) { deltaXPrime_->secondStage(kTRUE); deltaXPrime_->initValue(0.0); } if ( rhs.deltaYPrime_->secondStage() && !rhs.deltaYPrime_->fixed() ) { deltaYPrime_->secondStage(kTRUE); deltaYPrime_->initValue(0.0); } } } std::vector LauNSCCartesianCPCoeffSet::getParameters() { return { x_.get(), y_.get(), deltaX_.get(), deltaY_.get(), xPrime_.get(), yPrime_.get(), deltaXPrime_.get(), deltaYPrime_.get() }; } +std::vector LauNSCCartesianCPCoeffSet::getParameters() const +{ + return { x_.get(), y_.get(), deltaX_.get(), deltaY_.get(), xPrime_.get(), yPrime_.get(), deltaXPrime_.get(), deltaYPrime_.get() }; +} + void LauNSCCartesianCPCoeffSet::printParValues() const { std::cout<<"INFO in LauNSCCartesianCPCoeffSet::printParValues : Component \""<name()<<"\" has "; std::cout<<"x = "<value()<<",\t"; std::cout<<"y = "<value()<<",\t"; std::cout<<"Delta x = "<value()<<",\t"; std::cout<<"Delta y = "<value()<<",\t"; std::cout<<"xPrime = "<value()<<",\t"; std::cout<<"yPrime = "<value()<<",\t"; std::cout<<"Delta xPrime = "<value()<<",\t"; std::cout<<"Delta yPrime = "<value()<<"."<name() }; resName = resName.ReplaceAll("_", "\\_"); stream<value()); stream<<" \\pm "; print.printFormat(stream, x_->error()); stream<<"$ & $"; print.printFormat(stream, y_->value()); stream<<" \\pm "; print.printFormat(stream, y_->error()); stream<<"$ & $"; print.printFormat(stream, deltaX_->value()); stream<<" \\pm "; print.printFormat(stream, deltaX_->error()); stream<<"$ & $"; print.printFormat(stream, deltaY_->value()); stream<<" \\pm "; print.printFormat(stream, deltaY_->error()); stream<<"$ & $"; print.printFormat(stream, xPrime_->value()); stream<<" \\pm "; print.printFormat(stream, xPrime_->error()); stream<<"$ & $"; print.printFormat(stream, yPrime_->value()); stream<<" \\pm "; print.printFormat(stream, yPrime_->error()); stream<<"$ & $"; print.printFormat(stream, deltaXPrime_->value()); stream<<" \\pm "; print.printFormat(stream, deltaXPrime_->error()); stream<<"$ & $"; print.printFormat(stream, deltaYPrime_->value()); stream<<" \\pm "; print.printFormat(stream, deltaYPrime_->error()); stream<<"$ \\\\"<fixed() == kFALSE) { // Choose a value for "X" between -3.0 and 3.0 const Double_t value { LauRandom::zeroSeedRandom()->Rndm()*6.0 - 3.0 }; x_->initValue(value); x_->value(value); } if (y_->fixed() == kFALSE) { // Choose a value for "Y" between -3.0 and 3.0 const Double_t value { LauRandom::zeroSeedRandom()->Rndm()*6.0 - 3.0 }; y_->initValue(value); y_->value(value); } if (deltaX_->fixed() == kFALSE && deltaX_->secondStage() == kFALSE) { // Choose a value for "Delta X" between -0.5 and 0.5 const Double_t value { LauRandom::zeroSeedRandom()->Rndm()*1.0 - 0.5 }; deltaX_->initValue(value); deltaX_->value(value); } if (deltaY_->fixed() == kFALSE && deltaY_->secondStage() == kFALSE) { // Choose a value for "Delta Y" between -0.5 and 0.5 const Double_t value { LauRandom::zeroSeedRandom()->Rndm()*1.0 - 0.5 }; deltaY_->initValue(value); deltaY_->value(value); } if (xPrime_->fixed() == kFALSE) { // Choose a value for "XPrime" between -3.0 and 3.0 const Double_t value { LauRandom::zeroSeedRandom()->Rndm()*6.0 - 3.0 }; xPrime_->initValue(value); xPrime_->value(value); } if (yPrime_->fixed() == kFALSE) { // Choose a value for "YPrime" between -3.0 and 3.0 const Double_t value { LauRandom::zeroSeedRandom()->Rndm()*6.0 - 3.0 }; yPrime_->initValue(value); yPrime_->value(value); } if (deltaXPrime_->fixed() == kFALSE && deltaXPrime_->secondStage() == kFALSE) { // Choose a value for "Delta XPrime" between -0.5 and 0.5 const Double_t value { LauRandom::zeroSeedRandom()->Rndm()*1.0 - 0.5 }; deltaXPrime_->initValue(value); deltaXPrime_->value(value); } if (deltaYPrime_->fixed() == kFALSE && deltaYPrime_->secondStage() == kFALSE) { // Choose a value for "Delta YPrime" between -0.5 and 0.5 const Double_t value { LauRandom::zeroSeedRandom()->Rndm()*1.0 - 0.5 }; deltaYPrime_->initValue(value); deltaYPrime_->value(value); } } void LauNSCCartesianCPCoeffSet::finaliseValues() { // update the pulls x_->updatePull(); y_->updatePull(); deltaX_->updatePull(); deltaY_->updatePull(); xPrime_->updatePull(); yPrime_->updatePull(); deltaXPrime_->updatePull(); deltaYPrime_->updatePull(); } const LauComplex& LauNSCCartesianCPCoeffSet::particleCoeff() { if ( finalStateIsF_ ) { coeffAf_.setRealImagPart( x_->value() + deltaX_->value(), y_->value() + deltaY_->value() ); return coeffAf_; } else { coeffAfbar_.setRealImagPart( xPrime_->value() + deltaXPrime_->value(), yPrime_->value() + deltaYPrime_->value() ); return coeffAfbar_; } } const LauComplex& LauNSCCartesianCPCoeffSet::antiparticleCoeff() { if ( finalStateIsF_ ) { coeffAbarf_.setRealImagPart( xPrime_->value() - deltaXPrime_->value(), yPrime_->value() - deltaYPrime_->value() ); return coeffAbarf_; } else { coeffAbarfbar_.setRealImagPart( x_->value() - deltaX_->value(), y_->value() - deltaY_->value() ); return coeffAbarfbar_; } } void LauNSCCartesianCPCoeffSet::setCoeffValues( const LauComplex&, const LauComplex&, Bool_t ) { std::cerr << "ERROR in LauNSCCartesianCPCoeffSet::setCoeffValues : Method not supported by this class - too many parameters" << std::endl; } LauParameter LauNSCCartesianCPCoeffSet::acp() { // set the name const TString parName{ this->baseName() + "_ACP" }; acp_.name(parName); // a single ACP parameter doesn't really make much sense here const Double_t value{0.0}; const Double_t error{0.0}; // set the value and error acp_.valueAndErrors(value,error); return acp_; } LauNSCCartesianCPCoeffSet* LauNSCCartesianCPCoeffSet::createClone_impl(const TString& newName, const CloneOption cloneOption, const Double_t constFactor) { if ( ! ( cloneOption == CloneOption::All || cloneOption == CloneOption::TieRealPart || cloneOption == CloneOption::TieImagPart || cloneOption == CloneOption::TieCPPars ) ) { std::cerr << "ERROR in LauNSCCartesianCPCoeffSet::createClone : Invalid clone option" << std::endl; return nullptr; } auto clone = new LauNSCCartesianCPCoeffSet{ *this, cloneOption, constFactor }; clone->name( newName ); return clone; } + +LauNSCCartesianCPCoeffSet nlohmann::adl_serializer::from_json(const json& j) +{ + const LauCoeffType type { j.at("type").get() }; + if ( type != LauCoeffType::NSCCartesianCP ) { + throw LauWrongCoeffType("Wrong coefficient type given to construct LauNSCCartesianCPCoeffSet"); + } + + const TString name { j.at("name").get().c_str() }; + + const Bool_t finalStateIsF { j.at("finalStateIsF").get() }; + + // TODO - handle cloned coeffs + + const Double_t x { j.at("x").get() }; + const Double_t y { j.at("y").get() }; + const Double_t deltaX { j.at("deltaX").get() }; + const Double_t deltaY { j.at("deltaY").get() }; + + const Bool_t xFixed { j.at("xFixed").get() }; + const Bool_t yFixed { j.at("yFixed").get() }; + const Bool_t deltaXFixed { j.at("deltaXFixed").get() }; + const Bool_t deltaYFixed { j.at("deltaYFixed").get() }; + + const Bool_t deltaXSecondStage { j.at("deltaXSecondStage").get() }; + const Bool_t deltaYSecondStage { j.at("deltaYSecondStage").get() }; + + const Double_t xPrime { j.at("xPrime").get() }; + const Double_t yPrime { j.at("yPrime").get() }; + const Double_t deltaXPrime { j.at("deltaXPrime").get() }; + const Double_t deltaYPrime { j.at("deltaYPrime").get() }; + + const Bool_t xPrimeFixed { j.at("xPrimeFixed").get() }; + const Bool_t yPrimeFixed { j.at("yPrimeFixed").get() }; + const Bool_t deltaXPrimeFixed { j.at("deltaXPrimeFixed").get() }; + const Bool_t deltaYPrimeFixed { j.at("deltaYPrimeFixed").get() }; + + const Bool_t deltaXPrimeSecondStage { j.at("deltaXPrimeSecondStage").get() }; + const Bool_t deltaYPrimeSecondStage { j.at("deltaYPrimeSecondStage").get() }; + + return { name, finalStateIsF, + x, y, deltaX, deltaY, + xFixed, yFixed, deltaXFixed, deltaYFixed, + deltaXSecondStage, deltaYSecondStage, + xPrime, yPrime, deltaXPrime, deltaYPrime, + xPrimeFixed, yPrimeFixed, deltaXPrimeFixed, deltaYPrimeFixed, + deltaXPrimeSecondStage, deltaYPrimeSecondStage }; +} + +void nlohmann::adl_serializer::to_json(json& j, const LauNSCCartesianCPCoeffSet& t) +{ + j["type"] = LauCoeffType::NSCCartesianCP; + j["name"] = t.name(); + + j["finalStateIsF"] = t.finalStateIsF(); + + // TODO - handle cloned coeffs + + auto pars = t.getParameters(); + + j["x"] = pars[0]->value(); + j["y"] = pars[1]->value(); + j["deltaX"] = pars[2]->value(); + j["deltaY"] = pars[3]->value(); + + j["xFixed"] = pars[0]->fixed(); + j["yFixed"] = pars[1]->fixed(); + j["deltaXFixed"] = pars[2]->fixed(); + j["deltaYFixed"] = pars[3]->fixed(); + + j["deltaXSecondStage"] = pars[2]->secondStage(); + j["deltaYSecondStage"] = pars[3]->secondStage(); + + j["xPrime"] = pars[4]->value(); + j["yPrime"] = pars[5]->value(); + j["deltaXPrime"] = pars[6]->value(); + j["deltaYPrime"] = pars[7]->value(); + + j["xPrimeFixed"] = pars[4]->fixed(); + j["yPrimeFixed"] = pars[5]->fixed(); + j["deltaXPrimeFixed"] = pars[6]->fixed(); + j["deltaYPrimeFixed"] = pars[7]->fixed(); + + j["deltaXPrimeSecondStage"] = pars[6]->secondStage(); + j["deltaYPrimeSecondStage"] = pars[7]->secondStage(); +} diff --git a/src/LauParameter.cc b/src/LauParameter.cc index 21ad0e9..c11f8ed 100644 --- a/src/LauParameter.cc +++ b/src/LauParameter.cc @@ -1,595 +1,610 @@ /* 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 LauParameter.cc \brief File containing implementation of LauParameter class. */ #include #include #include "TRandom.h" #include "LauParameter.hh" #include "LauRandom.hh" ClassImp(LauParameter) LauParameter::LauParameter(const TString& parName) : name_{parName} { } LauParameter::LauParameter(const Double_t parValue) : value_{parValue}, genValue_{parValue}, initValue_{parValue}, minValue_{parValue-1e-6}, maxValue_{parValue+1e-6} { } LauParameter::LauParameter(const TString& parName, const Double_t parValue) : name_{parName}, value_{parValue}, genValue_{parValue}, initValue_{parValue}, minValue_{parValue-1e-6}, maxValue_{parValue+1e-6} { } LauParameter::LauParameter(const Double_t parValue, const Double_t min, const Double_t max) : value_{parValue}, genValue_{parValue}, initValue_{parValue}, minValue_{min}, maxValue_{max} { this->checkRange(); } LauParameter::LauParameter(const Double_t parValue, const Double_t parError, const Double_t min, const Double_t max) : value_{parValue}, error_{parError}, genValue_{parValue}, initValue_{parValue}, minValue_{min}, maxValue_{max} { this->checkRange(); } LauParameter::LauParameter(const Double_t parValue, const Double_t min, const Double_t max, const Bool_t parFixed) : value_{parValue}, genValue_{parValue}, initValue_{parValue}, minValue_{min}, maxValue_{max}, fixed_{parFixed} { this->checkRange(); } LauParameter::LauParameter(const TString& parName, const Double_t parValue, const Double_t min, const Double_t max) : name_{parName}, value_{parValue}, genValue_{parValue}, initValue_{parValue}, minValue_{min}, maxValue_{max} { this->checkRange(); } LauParameter::LauParameter(const TString& parName, const Double_t parValue, const Double_t min, const Double_t max, const Bool_t parFixed) : name_{parName}, value_{parValue}, genValue_{parValue}, initValue_{parValue}, minValue_{min}, maxValue_{max}, fixed_{parFixed} { this->checkRange(); } LauParameter::LauParameter(const TString& parName, const Double_t parValue, const Double_t parError, const Double_t min, const Double_t max) : name_{parName}, value_{parValue}, error_{parError}, genValue_{parValue}, initValue_{parValue}, minValue_{min}, maxValue_{max} { this->checkRange(); } LauParameter::LauParameter(const LauParameter& rhs) : TObject(rhs), LauAbsRValue(rhs), name_{rhs.name_}, value_{rhs.value_}, error_{rhs.error_}, negError_{rhs.negError_}, posError_{rhs.posError_}, genValue_{rhs.genValue_}, initValue_{rhs.initValue_}, minValue_{rhs.minValue_}, maxValue_{rhs.maxValue_}, fixed_{rhs.fixed_}, secondStage_{rhs.secondStage_}, gaussConstraint_{rhs.gaussConstraint_}, constraintMean_{rhs.constraintMean_}, constraintWidth_{rhs.constraintWidth_}, gcc_{rhs.gcc_}, bias_{rhs.bias_}, pull_{rhs.pull_}, clone_{rhs.clone_}, parent_{rhs.parent_}, clones_{rhs.clones_}, blinder_{(rhs.blinder_) ? std::make_unique(*(rhs.blinder_)) : nullptr} { } LauParameter& LauParameter::operator=(const LauParameter& rhs) { if (&rhs != this) { TObject::operator=(rhs); LauAbsRValue::operator=(rhs); name_ = rhs.name_; value_ = rhs.value_; error_ = rhs.error_; negError_ = rhs.negError_; posError_ = rhs.posError_; genValue_ = rhs.genValue_; initValue_ = rhs.initValue_; minValue_ = rhs.minValue_; maxValue_ = rhs.maxValue_; fixed_ = rhs.fixed_; secondStage_ = rhs.secondStage_; gaussConstraint_ = rhs.gaussConstraint_; constraintMean_ = rhs.constraintMean_; constraintWidth_ = rhs.constraintWidth_; gcc_ = rhs.gcc_; bias_ = rhs.bias_; pull_ = rhs.pull_; clone_ = rhs.clone_; parent_ = rhs.parent_; clones_ = rhs.clones_; blinder_.reset(); if ( rhs.blinder_ ) { blinder_ = std::make_unique(*(rhs.blinder_)); } } return *this; } LauParameter::~LauParameter() noexcept { // if we're a clone, we just need to inform our parent of our demise if ( this->clone() ) { parent_->removeFromCloneList(this); return; } // if we have no clones there's nothing to do if ( clones_.empty() ) { return; } // otherwise if we have clones we need to make one of them the new parent and inform the rest of the change // let's (arbitrarily) make the first parameter in the map the new parent auto iter = clones_.begin(); auto [ newParent, constFactor ] { *iter }; // remove that entry in the map clones_.erase(iter); // for all the other entries, we need to tell them they are clones of the new parent // and also rescale the constants so that they are relative to the new parent for ( auto& [ theClone, theFactor ] : clones_ ) { theClone->clone(newParent); theFactor /= constFactor; } // transfer the list of clones to the new parent newParent->clones_ = std::move(clones_); // finally, the new parent has to be told that it isn't a clone anymore newParent->clone(nullptr); } std::vector LauParameter::getPars() { std::vector list; list.push_back(this); return list; } void LauParameter::value(const Double_t newValue) { if (this->clone()) { parent_->value(newValue); } else { this->checkRange(newValue,this->minValue(),this->maxValue()); this->updateClones(kTRUE); } } void LauParameter::error(const Double_t newError) { if (this->clone()) { parent_->error(newError); } else { error_ = TMath::Abs(newError); this->updateClones(kFALSE); } } void LauParameter::negError(const Double_t newNegError) { if (this->clone()) { parent_->negError(newNegError); } else { negError_ = TMath::Abs(newNegError); this->updateClones(kFALSE); } } void LauParameter::posError(const Double_t newPosError) { if (this->clone()) { parent_->posError(newPosError); } else { posError_ = TMath::Abs(newPosError); this->updateClones(kFALSE); } } void LauParameter::errors(const Double_t newError, const Double_t newNegError, const Double_t newPosError) { if (this->clone()) { parent_->errors(newError,newNegError,newPosError); } else { error_ = TMath::Abs(newError); negError_ = TMath::Abs(newNegError); posError_ = TMath::Abs(newPosError); this->updateClones(kFALSE); } } void LauParameter::valueAndErrors(const Double_t newValue, const Double_t newError, const Double_t newNegError, const Double_t newPosError) { if (this->clone()) { parent_->valueAndErrors(newValue,newError,newNegError,newPosError); } else { this->checkRange(newValue,this->minValue(),this->maxValue()); error_ = TMath::Abs(newError); negError_ = TMath::Abs(newNegError); posError_ = TMath::Abs(newPosError); this->updateClones(kFALSE); } } void LauParameter::globalCorrelationCoeff(const Double_t newGCCValue) { if (this->clone()) { parent_->globalCorrelationCoeff(newGCCValue); } else { gcc_ = newGCCValue; this->updateClones(kFALSE); } } void LauParameter::genValue(const Double_t newGenValue) { if (this->clone()) { parent_->genValue(newGenValue); } else { genValue_ = newGenValue; this->updateClones(kFALSE); } } void LauParameter::initValue(const Double_t newInitValue) { if (this->clone()) { parent_->initValue(newInitValue); } else { initValue_ = newInitValue; this->updateClones(kFALSE); } } void LauParameter::minValue(const Double_t newMinValue) { if (this->clone()) { parent_->minValue(newMinValue); } else { this->checkRange(this->value(),newMinValue,this->maxValue()); this->updateClones(kFALSE); } } void LauParameter::maxValue(const Double_t newMaxValue) { if (this->clone()) { parent_->maxValue(newMaxValue); } else { this->checkRange(this->value(),this->minValue(),newMaxValue); this->updateClones(kFALSE); } } void LauParameter::range(const Double_t newMinValue, const Double_t newMaxValue) { if (this->clone()) { parent_->range(newMinValue,newMaxValue); } else { this->checkRange(this->value(),newMinValue,newMaxValue); this->updateClones(kFALSE); } } void LauParameter::valueAndRange(const Double_t newValue, const Double_t newMinValue, const Double_t newMaxValue) { if (this->clone()) { parent_->valueAndRange(newValue,newMinValue,newMaxValue); } else { this->checkRange(newValue,newMinValue,newMaxValue); this->updateClones(kFALSE); } } void LauParameter::name(const TString& newName) { // no need to update clones here // clones are allowed to have different names name_ = newName; } void LauParameter::fixed(const Bool_t parFixed) { if (this->clone()) { parent_->fixed(parFixed); } else { fixed_ = parFixed; this->updateClones(kFALSE); } } void LauParameter::secondStage(const Bool_t secondStagePar) { if (this->clone()) { parent_->secondStage(secondStagePar); } else { secondStage_ = secondStagePar; this->updateClones(kFALSE); } } void LauParameter::addGaussianConstraint(const Double_t newGaussMean, const Double_t newGaussWidth) { if (this->clone()) { parent_->addGaussianConstraint(newGaussMean,newGaussWidth); } else { gaussConstraint_ = kTRUE; constraintMean_ = newGaussMean; constraintWidth_ = newGaussWidth; this->updateClones(kFALSE); } } void LauParameter::removeGaussianConstraint() { if (this->clone()) { parent_->removeGaussianConstraint(); } else { gaussConstraint_ = kFALSE; this->updateClones(kFALSE); } } void LauParameter::blindParameter(const TString& blindingString, const Double_t width, const Bool_t flipSign) { if (this->clone()) { parent_->blindParameter(blindingString,width,flipSign); return; } if ( blinder_ ) { std::cerr << "WARNING in LauParameter::blindParameter : blinding has already been set up for this parameter" << std::endl; return; } blinder_ = std::make_unique(blindingString,width,flipSign); for ( auto& [ clonePar, _ ] : clones_ ) { if ( clonePar->blinder_ != nullptr ) { std::cerr << "WARNING in LauParameter::blindParameter : blinding has already been set up for a clone of this parameter - it will be replaced!" << std::endl; clonePar->blinder_.reset(); } clonePar->blinder_ = std::make_unique(*blinder_); } } void LauParameter::updatePull() { if (this->clone()) { parent_->updatePull(); return; } // calculate the bias bias_ = value_ - genValue_; // if we have errors calculated then calculate // the pull using the best error available if ((bias_ > 0.0) && (negError_ > 1e-10)) { pull_ = bias_ / negError_; } else if ((bias_ < 0.0) && (posError_ > 1e-10)) { pull_ = bias_ / posError_; } else if (error_ > 1e-10) { pull_ = bias_ / error_; } else { pull_ = 0.0; } this->updateClones(kFALSE); } void LauParameter::checkRange(const Double_t val, const Double_t minVal, const Double_t maxVal) { // first check that min is less than max (or they are the same - this is allowed) if (minVal > maxVal) { std::cerr<<"ERROR in LauParameter::checkRange : minValue: "< maxValue_) { minValue_ = maxValue_; std::cerr<<" : Setting both to "< maxVal)) { if (name_ != "") { std::cerr<<"ERROR in LauParameter::checkRange : value: "<clone()) { LauParameter* clonePar = parent_->createClone(constFactor); clonePar->name(this->name()); return clonePar; } // clone ourselves using the copy-constructor LauParameter* clonePar = new LauParameter(*this); Double_t newValue = clonePar->value() * constFactor; clonePar->value( newValue ); clonePar->wipeClones(); clonePar->clone(this); clones_.insert( std::make_pair( clonePar, constFactor ) ); return clonePar; } LauParameter* LauParameter::createClone(const TString& newName, const Double_t constFactor) { // self message to create the clone LauParameter* clonePar = this->createClone(constFactor); // set the new name clonePar->name(newName); // and return return clonePar; } void LauParameter::updateClones(const Bool_t justValue) { // if we don't have any clones then there's nothing to do if ( clones_.empty() ) { return; } // we have to set the values directly rather than using member functions because otherwise we'd get into an infinite loop if (justValue) { for ( auto& [ clonePar, constFactor ] : clones_ ) { clonePar->value_ = constFactor*value_; } } else { for ( auto& [ clonePar, constFactor ] : clones_ ) { clonePar->value_ = constFactor*value_; clonePar->error_ = constFactor*error_; clonePar->negError_ = constFactor*negError_; clonePar->posError_ = constFactor*posError_; clonePar->genValue_ = constFactor*genValue_; clonePar->initValue_ = constFactor*initValue_; clonePar->minValue_ = constFactor*minValue_; clonePar->maxValue_ = constFactor*maxValue_; clonePar->fixed_ = fixed_; clonePar->secondStage_ = secondStage_; clonePar->gaussConstraint_ = gaussConstraint_; clonePar->constraintMean_ = constraintMean_; clonePar->constraintWidth_ = constraintWidth_; clonePar->gcc_ = gcc_; clonePar->bias_ = bias_; clonePar->pull_ = pull_; } } } void LauParameter::randomiseValue() { this->randomiseValue(this->minValue(), this->maxValue()); } void LauParameter::randomiseValue(const Double_t minVal, const Double_t maxVal) { // if we're fixed then do nothing if (this->fixed()) { return; } // check supplied values are sensible if (maxVal < minVal) { std::cerr<<"ERROR in LauParameter::randomiseValue : Supplied maximum value smaller than minimum value."<Uniform( TMath::Max( minVal, this->minValue() ), TMath::Min( maxVal, this->maxValue() ) ) }; this->initValue(val); } // ostream operator -std::ostream& operator << (std::ostream& stream, const LauParameter& par) +std::ostream& operator<<(std::ostream& stream, const LauParameter& par) { + stream << par.name() << " : "; + stream << par.value(); + + if ( par.negError() > 1e-10 && par.posError() > 1e-10 ) { + stream << " +/- (" << par.negError() << ", " << par.posError() << ")"; + } else if ( par.error() > 1e-10 ) { + stream << " +/- " << par.error(); + } + + if ( par.fixed() ) { + stream << " C"; + } + + stream << " L(" << par.minValue() << ", " << par.maxValue() << ")"; + return stream; } diff --git a/src/LauPolarGammaCPCoeffSet.cc b/src/LauPolarGammaCPCoeffSet.cc index 6d0a0a8..d86e64a 100644 --- a/src/LauPolarGammaCPCoeffSet.cc +++ b/src/LauPolarGammaCPCoeffSet.cc @@ -1,756 +1,890 @@ /* Copyright 2014 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 LauPolarGammaCPCoeffSet.cc \brief File containing implementation of LauPolarGammaCPCoeffSet class. */ #include #include #include #include "TMath.h" #include "TRandom.h" #include "LauPolarGammaCPCoeffSet.hh" #include "LauComplex.hh" #include "LauConstants.hh" #include "LauParameter.hh" #include "LauPrint.hh" std::shared_ptr LauPolarGammaCPCoeffSet::gammaGlobal_; std::shared_ptr LauPolarGammaCPCoeffSet::rDGlobal_; std::shared_ptr LauPolarGammaCPCoeffSet::deltaDGlobal_; ClassImp(LauPolarGammaCPCoeffSet) LauPolarGammaCPCoeffSet::LauPolarGammaCPCoeffSet(const TString& compName, const DecayType decayType, const Double_t x, const Double_t y, const Double_t rB, const Double_t deltaB, const Double_t gamma, const Double_t rD, const Double_t deltaD, const Bool_t xFixed, const Bool_t yFixed, const Bool_t rBFixed, const Bool_t deltaBFixed, const Bool_t gammaFixed, const Bool_t rDFixed, const Bool_t deltaDFixed, const Bool_t rBSecondStage, const Bool_t deltaBSecondStage, const Bool_t gammaSecondStage, const Bool_t rDSecondStage, const Bool_t deltaDSecondStage, const Bool_t useGlobalGamma, const Bool_t useGlobalADSPars) : LauAbsCoeffSet{ compName }, decayType_{ decayType }, useGlobalGamma_{ useGlobalGamma }, useGlobalADSPars_{ useGlobalADSPars }, acp_{ "ACP", 0.0, -1.0, 1.0 } { // All of the possible D decay types need these two parameters x_ = std::make_unique("X", x, minRealImagPart_, maxRealImagPart_, xFixed); y_ = std::make_unique("Y", y, minRealImagPart_, maxRealImagPart_, yFixed); // if we're using a global gamma, create it if it doesn't already exist then set gamma_ to point to it // otherwise create our individual copy of gamma if (useGlobalGamma_) { if (!gammaGlobal_) { gammaGlobal_ = std::make_shared("gamma", gamma, minPhase_, maxPhase_, gammaFixed); gamma_ = gammaGlobal_; } else { gamma_.reset( gammaGlobal_->createClone() ); } } else { gamma_ = std::make_shared("gamma", gamma, minPhase_, maxPhase_, gammaFixed); } if (gammaSecondStage && !gammaFixed) { gamma_->secondStage(kTRUE); gamma_->initValue(0.0); } // which of the other parameter we need depends on the D-decay type if ( decayType_ == DecayType::ADS_Favoured || decayType_ == DecayType::ADS_Suppressed || decayType_ == DecayType::GLW_CPOdd || decayType_ == DecayType::GLW_CPEven ) { rB_ = std::make_unique("rB", rB, minMagnitude_, maxMagnitude_, rBFixed); deltaB_ = std::make_unique("deltaB", deltaB, minPhase_, maxPhase_, deltaBFixed); if (rBSecondStage && !rBFixed) { rB_->secondStage(kTRUE); rB_->initValue(0.0); } if (deltaBSecondStage && !deltaBFixed) { deltaB_->secondStage(kTRUE); deltaB_->initValue(0.0); } } if ( decayType_ == DecayType::ADS_Favoured || decayType_ == DecayType::ADS_Suppressed || decayType_ == DecayType::ADS_Favoured_btouOnly ) { if (useGlobalADSPars_) { if ( !rDGlobal_ ) { rDGlobal_ = std::make_shared("rD", rD, minMagnitude_, maxMagnitude_, rDFixed); deltaDGlobal_ = std::make_shared("deltaD", deltaD, minPhase_, maxPhase_, deltaDFixed); rD_ = rDGlobal_; deltaD_ = deltaDGlobal_; } else { rD_.reset( rDGlobal_->createClone() ); deltaD_.reset( deltaDGlobal_->createClone() ); } } else { rD_ = std::make_shared("rD", rD, minMagnitude_, maxMagnitude_, rDFixed); deltaD_ = std::make_shared("deltaD", deltaD, minPhase_, maxPhase_, deltaDFixed); } if (rDSecondStage && !rDFixed) { rD_->secondStage(kTRUE); rD_->initValue(0.0); } if (deltaDSecondStage && !deltaDFixed) { deltaD_->secondStage(kTRUE); deltaD_->initValue(0.0); } } } LauPolarGammaCPCoeffSet::LauPolarGammaCPCoeffSet(const LauPolarGammaCPCoeffSet& rhs, const CloneOption cloneOption, const Double_t constFactor) : LauAbsCoeffSet{ rhs.name() }, decayType_{ rhs.decayType_ }, useGlobalGamma_{ rhs.useGlobalGamma_ }, useGlobalADSPars_{ rhs.useGlobalADSPars_ }, nonCPPart_{ rhs.nonCPPart_ }, cpPart_{ rhs.cpPart_ }, cpAntiPart_{ rhs.cpAntiPart_ }, particleCoeff_{ rhs.particleCoeff_ }, antiparticleCoeff_{ rhs.antiparticleCoeff_ }, acp_{ rhs.acp_ } { if ( cloneOption == CloneOption::All || cloneOption == CloneOption::TieRealPart ) { x_.reset( rhs.x_->createClone(constFactor) ); } else { x_ = std::make_unique("X", rhs.x_->value(), minRealImagPart_, maxRealImagPart_, rhs.x_->fixed()); if ( rhs.x_->blind() ) { const LauBlind* blinder { rhs.x_->blinder() }; x_->blindParameter( blinder->blindingString(), blinder->blindingWidth() ); } } if ( cloneOption == CloneOption::All || cloneOption == CloneOption::TieImagPart ) { y_.reset( rhs.y_->createClone(constFactor) ); } else { y_ = std::make_unique("Y", rhs.y_->value(), minRealImagPart_, maxRealImagPart_, rhs.y_->fixed()); if ( rhs.y_->blind() ) { const LauBlind* blinder { rhs.y_->blinder() }; y_->blindParameter( blinder->blindingString(), blinder->blindingWidth() ); } } if ( cloneOption == CloneOption::All || cloneOption == CloneOption::TieCPPars ) { gamma_.reset( rhs.gamma_->createClone(constFactor) ); if ( decayType_ == DecayType::ADS_Favoured || decayType_ == DecayType::ADS_Suppressed || decayType_ == DecayType::GLW_CPOdd || decayType_ == DecayType::GLW_CPEven ) { rB_.reset( rhs.rB_->createClone(constFactor) ); deltaB_.reset( rhs.deltaB_->createClone(constFactor) ); } if ( decayType_ == DecayType::ADS_Favoured || decayType_ == DecayType::ADS_Suppressed || decayType_ == DecayType::ADS_Favoured_btouOnly ) { rD_.reset( rhs.rD_->createClone(constFactor) ); deltaD_.reset( rhs.deltaD_->createClone(constFactor) ); } } else { if (useGlobalGamma_) { gamma_.reset( gammaGlobal_->createClone() ); } else { gamma_ = std::make_shared("gamma", rhs.gamma_->value(), minPhase_, maxPhase_, rhs.gamma_->fixed()); if ( rhs.gamma_->blind() ) { const LauBlind* blinder { rhs.gamma_->blinder() }; gamma_->blindParameter( blinder->blindingString(), blinder->blindingWidth() ); } if ( rhs.gamma_->secondStage() && !rhs.gamma_->fixed() ) { gamma_->secondStage(kTRUE); gamma_->initValue(0.0); } } if ( decayType_ == DecayType::ADS_Favoured || decayType_ == DecayType::ADS_Suppressed || decayType_ == DecayType::GLW_CPOdd || decayType_ == DecayType::GLW_CPEven ) { rB_ = std::make_unique("rB", rhs.rB_->value(), minMagnitude_, maxMagnitude_, rhs.rB_->fixed()); if ( rhs.rB_->blind() ) { const LauBlind* blinder { rhs.rB_->blinder() }; rB_->blindParameter( blinder->blindingString(), blinder->blindingWidth() ); } deltaB_ = std::make_unique("deltaB", rhs.deltaB_->value(), minPhase_, maxPhase_, rhs.deltaB_->fixed()); if ( rhs.deltaB_->blind() ) { const LauBlind* blinder { rhs.deltaB_->blinder() }; deltaB_->blindParameter( blinder->blindingString(), blinder->blindingWidth() ); } if ( rhs.rB_->secondStage() && !rhs.rB_->fixed() ) { rB_->secondStage(kTRUE); rB_->initValue(0.0); } if ( rhs.deltaB_->secondStage() && !rhs.deltaB_->fixed() ) { deltaB_->secondStage(kTRUE); deltaB_->initValue(0.0); } } if ( decayType_ == DecayType::ADS_Favoured || decayType_ == DecayType::ADS_Suppressed || decayType_ == DecayType::ADS_Favoured_btouOnly ) { if ( useGlobalADSPars_ ) { rD_.reset( rDGlobal_->createClone() ); deltaD_.reset( deltaDGlobal_->createClone() ); } else { rD_ = std::make_shared("rD", rhs.rD_->value(), minMagnitude_, maxMagnitude_, rhs.rD_->fixed()); if ( rhs.rD_->blind() ) { const LauBlind* blinder { rhs.rD_->blinder() }; rD_->blindParameter( blinder->blindingString(), blinder->blindingWidth() ); } deltaD_ = std::make_shared("deltaD", rhs.deltaD_->value(), minPhase_, maxPhase_, rhs.deltaD_->fixed()); if ( rhs.deltaD_->blind() ) { const LauBlind* blinder { rhs.deltaD_->blinder() }; deltaD_->blindParameter( blinder->blindingString(), blinder->blindingWidth() ); } if ( rhs.rD_->secondStage() && !rhs.rD_->fixed() ) { rD_->secondStage(kTRUE); rD_->initValue(0.0); } if ( rhs.deltaD_->secondStage() && !rhs.deltaD_->fixed() ) { deltaD_->secondStage(kTRUE); deltaD_->initValue(0.0); } } } } } void LauPolarGammaCPCoeffSet::adjustName(LauParameter& par, const TString& oldBaseName) { if ( ( &par == gamma_.get() && useGlobalGamma_ ) || ( &par == rD_.get() && useGlobalADSPars_ ) || ( &par == deltaD_.get() && useGlobalADSPars_ ) ) { // for global parameters we do not want to adjust their names return; } else { LauAbsCoeffSet::adjustName(par,oldBaseName); } } std::vector LauPolarGammaCPCoeffSet::getParameters() { std::vector pars; pars.reserve(7); pars.push_back(x_.get()); pars.push_back(y_.get()); - if ( !gamma_->fixed() ) { - pars.push_back(gamma_.get()); + pars.push_back(gamma_.get()); + + if ( decayType_ == DecayType::ADS_Favoured || decayType_ == DecayType::ADS_Suppressed || decayType_ == DecayType::GLW_CPOdd || decayType_ == DecayType::GLW_CPEven ) { + pars.push_back(rB_.get()); + pars.push_back(deltaB_.get()); } + if ( decayType_ == DecayType::ADS_Favoured || decayType_ == DecayType::ADS_Suppressed || decayType_ == DecayType::ADS_Favoured_btouOnly ) { + pars.push_back(rD_.get()); + pars.push_back(deltaD_.get()); + } + + return pars; +} + +std::vector LauPolarGammaCPCoeffSet::getParameters() const +{ + std::vector pars; + pars.reserve(7); + + pars.push_back(x_.get()); + pars.push_back(y_.get()); + + pars.push_back(gamma_.get()); + if ( decayType_ == DecayType::ADS_Favoured || decayType_ == DecayType::ADS_Suppressed || decayType_ == DecayType::GLW_CPOdd || decayType_ == DecayType::GLW_CPEven ) { - if ( !rB_->fixed() ) { - pars.push_back(rB_.get()); - } - if ( !deltaB_->fixed() ) { - pars.push_back(deltaB_.get()); - } + pars.push_back(rB_.get()); + pars.push_back(deltaB_.get()); } if ( decayType_ == DecayType::ADS_Favoured || decayType_ == DecayType::ADS_Suppressed || decayType_ == DecayType::ADS_Favoured_btouOnly ) { - if ( !rD_->fixed() ) { - pars.push_back(rD_.get()); - } - if ( !deltaD_->fixed() ) { - pars.push_back(deltaD_.get()); - } + pars.push_back(rD_.get()); + pars.push_back(deltaD_.get()); } return pars; } void LauPolarGammaCPCoeffSet::printParValues() const { std::cout<<"INFO in LauPolarGammaCPCoeffSet::printParValues : Component \""<name()<<"\" has "; std::cout<<"x = "<value()<<",\t"; std::cout<<"y = "<value()<<",\t"; if ( decayType_ == DecayType::ADS_Favoured || decayType_ == DecayType::ADS_Suppressed || decayType_ == DecayType::GLW_CPOdd || decayType_ == DecayType::GLW_CPEven ) { std::cout<<"rB = "<value()<<",\t"; std::cout<<"deltaB = "<value()<<",\t"; } if ( decayType_ == DecayType::ADS_Favoured || decayType_ == DecayType::ADS_Suppressed || decayType_ == DecayType::ADS_Favoured_btouOnly ) { std::cout<<"rD = "<value()<<",\t"; std::cout<<"deltaD = "<value()<<",\t"; } std::cout<<"gamma = "<value()<<"."<name() }; resName = resName.ReplaceAll("_", "\\_"); stream<value()); stream<<" \\pm "; print.printFormat(stream, x_->error()); stream<<"$ & $"; print.printFormat(stream, y_->value()); stream<<" \\pm "; print.printFormat(stream, y_->error()); stream<<"$ & $"; if ( decayType_ == DecayType::ADS_Favoured || decayType_ == DecayType::ADS_Suppressed || decayType_ == DecayType::GLW_CPOdd || decayType_ == DecayType::GLW_CPEven ) { print.printFormat(stream, rB_->value()); stream<<" \\pm "; print.printFormat(stream, rB_->error()); stream<<"$ & $"; print.printFormat(stream, deltaB_->value()); stream<<" \\pm "; print.printFormat(stream, deltaB_->error()); stream<<"$ & $"; } if ( decayType_ == DecayType::ADS_Favoured || decayType_ == DecayType::ADS_Suppressed || decayType_ == DecayType::ADS_Favoured_btouOnly ) { print.printFormat(stream, rD_->value()); stream<<" \\pm "; print.printFormat(stream, rD_->error()); stream<<"$ & $"; print.printFormat(stream, deltaD_->value()); stream<<" \\pm "; print.printFormat(stream, deltaD_->error()); stream<<"$ & $"; } print.printFormat(stream, gamma_->value()); stream<<" \\pm "; print.printFormat(stream, gamma_->error()); stream<<"$ \\\\"<fixed() == kFALSE) { // Choose a value for "X" between -3.0 and 3.0 const Double_t value { LauAbsCoeffSet::getRandomiser()->Rndm()*6.0 - 3.0 }; x_->initValue(value); x_->value(value); } if (y_->fixed() == kFALSE) { // Choose a value for "Y" between -3.0 and 3.0 const Double_t value { LauAbsCoeffSet::getRandomiser()->Rndm()*6.0 - 3.0 }; y_->initValue(value); y_->value(value); } if (gamma_->fixed() == kFALSE && gamma_->secondStage() == kFALSE) { // Choose a value for "gamma" between +-pi const Double_t value { LauAbsCoeffSet::getRandomiser()->Rndm()*LauConstants::twoPi - LauConstants::pi }; gamma_->initValue(value); gamma_->value(value); } if ( decayType_ == DecayType::ADS_Favoured || decayType_ == DecayType::ADS_Suppressed || decayType_ == DecayType::GLW_CPOdd || decayType_ == DecayType::GLW_CPEven ) { if (rB_->fixed() == kFALSE && rB_->secondStage() == kFALSE) { // Choose a value for "rB" between 0.0 and 2.0 const Double_t value { LauAbsCoeffSet::getRandomiser()->Rndm()*2.0 }; rB_->initValue(value); rB_->value(value); } if (deltaB_->fixed() == kFALSE && deltaB_->secondStage() == kFALSE) { // Choose a value for "deltaB" between +- pi const Double_t value { LauAbsCoeffSet::getRandomiser()->Rndm()*LauConstants::twoPi - LauConstants::pi }; deltaB_->initValue(value); deltaB_->value(value); } } if ( decayType_ == DecayType::ADS_Favoured || decayType_ == DecayType::ADS_Suppressed || decayType_ == DecayType::ADS_Favoured_btouOnly ) { if (rD_->fixed() == kFALSE && rD_->secondStage() == kFALSE) { // Choose a value for "rD" between 0.0 and 2.0 const Double_t value { LauAbsCoeffSet::getRandomiser()->Rndm()*2.0 }; rD_->initValue(value); rD_->value(value); } if (deltaD_->fixed() == kFALSE && deltaD_->secondStage() == kFALSE) { // Choose a value for "deltaD" between +- pi const Double_t value { LauAbsCoeffSet::getRandomiser()->Rndm()*LauConstants::twoPi - LauConstants::pi }; deltaD_->initValue(value); deltaD_->value(value); } } } void LauPolarGammaCPCoeffSet::finaliseValues() { // retrieve the current values from the parameters Double_t gammaVal { gamma_->value() }; Double_t rBVal { 0.0 }; Double_t deltaBVal { 0.0 }; Double_t genDeltaB { 0.0 }; Double_t rDVal { 0.0 }; Double_t deltaDVal { 0.0 }; Double_t genDeltaD { 0.0 }; if ( decayType_ == DecayType::ADS_Favoured || decayType_ == DecayType::ADS_Suppressed || decayType_ == DecayType::GLW_CPOdd || decayType_ == DecayType::GLW_CPEven ) { rBVal = rB_->value(); deltaBVal = deltaB_->value(); genDeltaB = deltaB_->genValue(); } if ( decayType_ == DecayType::ADS_Favoured || decayType_ == DecayType::ADS_Suppressed || decayType_ == DecayType::ADS_Favoured_btouOnly ) { rDVal = rD_->value(); deltaDVal = deltaD_->value(); genDeltaD = deltaD_->genValue(); } // Check whether we have a negative magnitude. // If so make it positive and add pi to the phases. if (rBVal < 0.0) { rBVal *= -1.0; deltaBVal += LauConstants::pi; } if (rDVal < 0.0) { rDVal *= -1.0; deltaDVal += LauConstants::pi; } // Check now whether the phases lie in the right range (-pi to pi). Bool_t deltaBWithinRange{kFALSE}; Bool_t deltaDWithinRange{kFALSE}; Bool_t gammaWithinRange{kFALSE}; while ( deltaBWithinRange == kFALSE ) { if (deltaBVal > -LauConstants::pi && deltaBVal <= LauConstants::pi) { deltaBWithinRange = kTRUE; } else { // Not within the specified range if (deltaBVal > LauConstants::pi) { deltaBVal -= LauConstants::twoPi; } else if (deltaBVal <= -LauConstants::pi) { deltaBVal += LauConstants::twoPi; } } } while ( deltaDWithinRange == kFALSE ) { if (deltaDVal > -LauConstants::pi && deltaDVal <= LauConstants::pi) { deltaDWithinRange = kTRUE; } else { // Not within the specified range if (deltaDVal > LauConstants::pi) { deltaDVal -= LauConstants::twoPi; } else if (deltaDVal <= -LauConstants::pi) { deltaDVal += LauConstants::twoPi; } } } while ( gammaWithinRange == kFALSE ) { if (gammaVal > -LauConstants::pi && gammaVal <= LauConstants::pi) { gammaWithinRange = kTRUE; } else { // Not within the specified range if (gammaVal > LauConstants::pi) { gammaVal -= LauConstants::twoPi; } else if (gammaVal <= -LauConstants::pi) { gammaVal += LauConstants::twoPi; } } } // To resolve the two-fold ambiguity in gamma and deltaB we require gamma to be in the range 0-pi if ( decayType_ == DecayType::ADS_Favoured || decayType_ == DecayType::ADS_Suppressed || decayType_ == DecayType::GLW_CPOdd || decayType_ == DecayType::GLW_CPEven ) { if (gammaVal < 0.0) { if (deltaBVal <= 0.0) { gammaVal += LauConstants::pi; deltaBVal += LauConstants::pi; } else { gammaVal += LauConstants::pi; deltaBVal -= LauConstants::pi; } } } // 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 { deltaBVal - genDeltaB }; if (diff > LauConstants::pi) { deltaBVal -= LauConstants::twoPi; } else if (diff < -LauConstants::pi) { deltaBVal += LauConstants::twoPi; } diff = deltaDVal - genDeltaD; if (diff > LauConstants::pi) { deltaDVal -= LauConstants::twoPi; } else if (diff < -LauConstants::pi) { deltaDVal += LauConstants::twoPi; } // finally store the new values in the parameters // and update the pulls gamma_->value(gammaVal); gamma_->updatePull(); if ( decayType_ == DecayType::ADS_Favoured || decayType_ == DecayType::ADS_Suppressed || decayType_ == DecayType::GLW_CPOdd || decayType_ == DecayType::GLW_CPEven ) { rB_->value(rBVal); rB_->updatePull(); deltaB_->value(deltaBVal); deltaB_->updatePull(); } if ( decayType_ == DecayType::ADS_Favoured || decayType_ == DecayType::ADS_Suppressed || decayType_ == DecayType::ADS_Favoured_btouOnly ) { rD_->value(rDVal); rD_->updatePull(); deltaD_->value(deltaDVal); deltaD_->updatePull(); } } const LauComplex& LauPolarGammaCPCoeffSet::particleCoeff() { this->updateAmplitudes(); return particleCoeff_; } const LauComplex& LauPolarGammaCPCoeffSet::antiparticleCoeff() { this->updateAmplitudes(); return antiparticleCoeff_; } void LauPolarGammaCPCoeffSet::updateAmplitudes() { nonCPPart_.setRealImagPart( x_->unblindValue(), y_->unblindValue() ); const Double_t gammaVal { gamma_->unblindValue() }; switch ( decayType_ ) { case DecayType::GLW_CPOdd : { const Double_t rBVal { rB_->unblindValue() }; const Double_t deltaBVal { deltaB_->unblindValue() }; cpPart_.setRealImagPart( 1.0 - rBVal*TMath::Cos(deltaBVal + gammaVal), -rBVal*TMath::Sin(deltaBVal + gammaVal) ); cpAntiPart_.setRealImagPart( 1.0 - rBVal*TMath::Cos(deltaBVal - gammaVal), -rBVal*TMath::Sin(deltaBVal - gammaVal) ); break; } case DecayType::GLW_CPEven : { const Double_t rBVal { rB_->unblindValue() }; const Double_t deltaBVal { deltaB_->unblindValue() }; cpPart_.setRealImagPart( 1.0 + rBVal*TMath::Cos(deltaBVal + gammaVal), rBVal*TMath::Sin(deltaBVal + gammaVal) ); cpAntiPart_.setRealImagPart( 1.0 + rBVal*TMath::Cos(deltaBVal - gammaVal), rBVal*TMath::Sin(deltaBVal - gammaVal) ); break; } case DecayType::ADS_Favoured : { const Double_t rBVal { rB_->unblindValue() }; const Double_t deltaBVal { deltaB_->unblindValue() }; const Double_t rDVal { rD_->unblindValue() }; const Double_t deltaDVal { deltaD_->unblindValue() }; cpPart_.setRealImagPart( 1.0 + rBVal*rDVal*TMath::Cos(deltaBVal - deltaDVal + gammaVal), rBVal*rDVal*TMath::Sin(deltaBVal - deltaDVal + gammaVal) ); cpAntiPart_.setRealImagPart( 1.0 + rBVal*rDVal*TMath::Cos(deltaBVal - deltaDVal - gammaVal), rBVal*rDVal*TMath::Sin(deltaBVal - deltaDVal - gammaVal) ); break; } case DecayType::ADS_Suppressed : { const Double_t rBVal { rB_->unblindValue() }; const Double_t deltaBVal { deltaB_->unblindValue() }; const Double_t rDVal { rD_->unblindValue() }; const Double_t deltaDVal { deltaD_->unblindValue() }; cpPart_.setRealImagPart( rDVal*TMath::Cos(-deltaDVal) + rBVal*TMath::Cos(deltaBVal + gammaVal), rDVal*TMath::Sin(-deltaDVal) + rBVal*TMath::Sin(deltaBVal + gammaVal) ); cpAntiPart_.setRealImagPart( rDVal*TMath::Cos(-deltaDVal) + rBVal*TMath::Cos(deltaBVal - gammaVal), rDVal*TMath::Sin(-deltaDVal) + rBVal*TMath::Sin(deltaBVal - gammaVal) ); break; } case DecayType::GLW_CPOdd_btouOnly : nonCPPart_.rescale(-1.0); cpPart_.setRealImagPart( 1.0 * TMath::Cos( gammaVal ), 1.0 * TMath::Sin( gammaVal ) ); cpAntiPart_.setRealImagPart( 1.0 * TMath::Cos( -gammaVal ), 1.0 * TMath::Sin( -gammaVal ) ); break; case DecayType::GLW_CPEven_btouOnly : cpPart_.setRealImagPart( 1.0 * TMath::Cos( gammaVal ), 1.0 * TMath::Sin( gammaVal ) ); cpAntiPart_.setRealImagPart( 1.0 * TMath::Cos( -gammaVal ), 1.0 * TMath::Sin( -gammaVal ) ); break; case DecayType::ADS_Favoured_btouOnly : { const Double_t rDVal { rD_->unblindValue() }; const Double_t deltaDVal { deltaD_->unblindValue() }; cpPart_.setRealImagPart( rDVal * TMath::Cos( -deltaDVal + gammaVal ), rDVal * TMath::Sin( -deltaDVal + gammaVal ) ); cpAntiPart_.setRealImagPart( rDVal * TMath::Cos( -deltaDVal - gammaVal ), rDVal * TMath::Sin( -deltaDVal - gammaVal ) ); break; } case DecayType::ADS_Suppressed_btouOnly : cpPart_.setRealImagPart( 1.0 * TMath::Cos( gammaVal ), 1.0 * TMath::Sin( gammaVal ) ); cpAntiPart_.setRealImagPart( 1.0 * TMath::Cos( -gammaVal ), 1.0 * TMath::Sin( -gammaVal ) ); break; } particleCoeff_ = nonCPPart_ * cpPart_; antiparticleCoeff_ = nonCPPart_ * cpAntiPart_; } void LauPolarGammaCPCoeffSet::setCoeffValues( const LauComplex&, const LauComplex&, Bool_t ) { std::cerr << "ERROR in LauPolarGammaCPCoeffSet::setCoeffValues : Method not supported by this class - too many parameters" << std::endl; } LauParameter LauPolarGammaCPCoeffSet::acp() { // set the name const TString parName{ this->baseName() + "_ACP" }; acp_.name(parName); // work out the ACP value LauComplex nonCPPart{ x_->value(), y_->value() }; LauComplex cpPart; LauComplex cpAntiPart; const Double_t gammaVal { gamma_->value() }; switch ( decayType_ ) { case DecayType::GLW_CPOdd : { const Double_t rBVal { rB_->value() }; const Double_t deltaBVal { deltaB_->value() }; cpPart.setRealImagPart( 1.0 - rBVal*TMath::Cos(deltaBVal + gammaVal), -rBVal*TMath::Sin(deltaBVal + gammaVal) ); cpAntiPart.setRealImagPart( 1.0 - rBVal*TMath::Cos(deltaBVal - gammaVal), -rBVal*TMath::Sin(deltaBVal - gammaVal) ); break; } case DecayType::GLW_CPEven : { const Double_t rBVal { rB_->value() }; const Double_t deltaBVal { deltaB_->value() }; cpPart.setRealImagPart( 1.0 + rBVal*TMath::Cos(deltaBVal + gammaVal), rBVal*TMath::Sin(deltaBVal + gammaVal) ); cpAntiPart.setRealImagPart( 1.0 + rBVal*TMath::Cos(deltaBVal - gammaVal), rBVal*TMath::Sin(deltaBVal - gammaVal) ); break; } case DecayType::ADS_Favoured : { const Double_t rBVal { rB_->value() }; const Double_t deltaBVal { deltaB_->value() }; const Double_t rDVal { rD_->value() }; const Double_t deltaDVal { deltaD_->value() }; cpPart.setRealImagPart( 1.0 + rBVal*rDVal*TMath::Cos(deltaBVal - deltaDVal + gammaVal), rBVal*rDVal*TMath::Sin(deltaBVal - deltaDVal + gammaVal) ); cpAntiPart.setRealImagPart( 1.0 + rBVal*rDVal*TMath::Cos(deltaBVal - deltaDVal - gammaVal), rBVal*rDVal*TMath::Sin(deltaBVal - deltaDVal - gammaVal) ); break; } case DecayType::ADS_Suppressed : { const Double_t rBVal { rB_->value() }; const Double_t deltaBVal { deltaB_->value() }; const Double_t rDVal { rD_->value() }; const Double_t deltaDVal { deltaD_->value() }; cpPart.setRealImagPart( rDVal*TMath::Cos(-deltaDVal) + rBVal*TMath::Cos(deltaBVal + gammaVal), rDVal*TMath::Sin(-deltaDVal) + rBVal*TMath::Sin(deltaBVal + gammaVal) ); cpAntiPart.setRealImagPart( rDVal*TMath::Cos(-deltaDVal) + rBVal*TMath::Cos(deltaBVal - gammaVal), rDVal*TMath::Sin(-deltaDVal) + rBVal*TMath::Sin(deltaBVal - gammaVal) ); break; } case DecayType::GLW_CPOdd_btouOnly : nonCPPart.rescale(-1.0); cpPart.setRealImagPart( 1.0 * TMath::Cos( gammaVal ), 1.0 * TMath::Sin( gammaVal ) ); cpAntiPart.setRealImagPart( 1.0 * TMath::Cos( -gammaVal ), 1.0 * TMath::Sin( -gammaVal ) ); break; case DecayType::GLW_CPEven_btouOnly : cpPart.setRealImagPart( 1.0 * TMath::Cos( gammaVal ), 1.0 * TMath::Sin( gammaVal ) ); cpAntiPart.setRealImagPart( 1.0 * TMath::Cos( -gammaVal ), 1.0 * TMath::Sin( -gammaVal ) ); break; case DecayType::ADS_Favoured_btouOnly : { const Double_t rDVal { rD_->value() }; const Double_t deltaDVal { deltaD_->value() }; cpPart.setRealImagPart( rDVal * TMath::Cos( -deltaDVal + gammaVal ), rDVal * TMath::Sin( -deltaDVal + gammaVal ) ); cpAntiPart.setRealImagPart( rDVal * TMath::Cos( -deltaDVal - gammaVal ), rDVal * TMath::Sin( -deltaDVal - gammaVal ) ); break; } case DecayType::ADS_Suppressed_btouOnly : cpPart.setRealImagPart( 1.0 * TMath::Cos( gammaVal ), 1.0 * TMath::Sin( gammaVal ) ); cpAntiPart.setRealImagPart( 1.0 * TMath::Cos( -gammaVal ), 1.0 * TMath::Sin( -gammaVal ) ); break; } const LauComplex partCoeff { nonCPPart * cpPart }; const LauComplex antiCoeff { nonCPPart * cpAntiPart }; const Double_t numer { antiCoeff.abs2() - partCoeff.abs2() }; const Double_t denom { antiCoeff.abs2() + partCoeff.abs2() }; const Double_t value { numer/denom }; // is it fixed? const Bool_t fixed { gamma_->fixed() }; acp_.fixed(fixed); // we can't work out the error without the covariance matrix const Double_t error{0.0}; // set the value and error acp_.valueAndErrors(value,error); return acp_; } LauPolarGammaCPCoeffSet* LauPolarGammaCPCoeffSet::createClone_impl(const TString& newName, const CloneOption cloneOption, const Double_t constFactor) { if ( ! ( cloneOption == CloneOption::All || cloneOption == CloneOption::TieRealPart || cloneOption == CloneOption::TieImagPart || cloneOption == CloneOption::TieCPPars ) ) { std::cerr << "ERROR in LauPolarGammaCPCoeffSet::createClone : Invalid clone option" << std::endl; return nullptr; } auto clone = new LauPolarGammaCPCoeffSet( *this, cloneOption, constFactor ); clone->name( newName ); return clone; } + +LauPolarGammaCPCoeffSet nlohmann::adl_serializer::from_json(const json& j) +{ + const LauCoeffType type { j.at("type").get() }; + if ( type != LauCoeffType::PolarGammaCP ) { + throw LauWrongCoeffType("Wrong coefficient type given to construct LauPolarGammaCPCoeffSet"); + } + + const TString name { j.at("name").get().c_str() }; + + const LauPolarGammaCPCoeffSet::DecayType decayType { j.at("decayType").get() }; + + // TODO - handle cloned coeffs + + const Double_t x { j.at("x").get() }; + const Double_t y { j.at("y").get() }; + + const Double_t rB { j.at("rB").get() }; + const Double_t deltaB { j.at("deltaB").get() }; + const Double_t gamma { j.at("gamma").get() }; + + const Double_t rD { j.at("rD").get() }; + const Double_t deltaD { j.at("deltaD").get() }; + + const Bool_t xFixed { j.at("xFixed").get() }; + const Bool_t yFixed { j.at("yFixed").get() }; + + const Bool_t rBFixed { j.at("rBFixed").get() }; + const Bool_t deltaBFixed { j.at("deltaBFixed").get() }; + const Bool_t gammaFixed { j.at("gammaFixed").get() }; + + const Bool_t rDFixed { j.at("rDFixed").get() }; + const Bool_t deltaDFixed { j.at("deltaDFixed").get() }; + + const Bool_t rBSecondStage { j.at("rBSecondStage").get() }; + const Bool_t deltaBSecondStage { j.at("deltaBSecondStage").get() }; + const Bool_t gammaSecondStage { j.at("gammaSecondStage").get() }; + + const Bool_t rDSecondStage { j.at("rDSecondStage").get() }; + const Bool_t deltaDSecondStage { j.at("deltaDSecondStage").get() }; + + const Bool_t useGlobalGamma { j.at("useGlobalGamma").get() }; + const Bool_t useGlobalADSPars { j.at("useGlobalADSPars").get() }; + + return { name, decayType, + x, y, rB, deltaB, gamma, rD, deltaD, + xFixed, yFixed, rBFixed, deltaBFixed, gammaFixed, rDFixed, deltaDFixed, + rBSecondStage, deltaBSecondStage, gammaSecondStage, rDSecondStage, deltaDSecondStage, + useGlobalGamma, useGlobalADSPars }; +} + +void nlohmann::adl_serializer::to_json(json& j, const LauPolarGammaCPCoeffSet& t) +{ + j["type"] = LauCoeffType::PolarGammaCP; + j["name"] = t.name(); + + const LauPolarGammaCPCoeffSet::DecayType decayType { t.decayType() }; + j["decayType"] = decayType; + + j["useGlobalGamma"] = t.useGlobalGamma(); + j["useGlobalADSPars"] = t.useGlobalADSPars(); + + // TODO - handle cloned coeffs + + auto pars = t.getParameters(); + + j["x"] = pars[0]->value(); + j["y"] = pars[1]->value(); + j["gamma"] = pars[2]->value(); + + j["xFixed"] = pars[0]->fixed(); + j["yFixed"] = pars[1]->fixed(); + j["gammaFixed"] = pars[2]->fixed(); + + j["gammaSecondStage"] = pars[2]->secondStage(); + + switch ( decayType ) { + case LauPolarGammaCPCoeffSet::DecayType::GLW_CPOdd : + case LauPolarGammaCPCoeffSet::DecayType::GLW_CPEven : + j["rB"] = pars[3]->value(); + j["deltaB"] = pars[4]->value(); + + j["rBFixed"] = pars[3]->fixed(); + j["deltaBFixed"] = pars[4]->fixed(); + + j["rBSecondStage"] = pars[3]->secondStage(); + j["deltaBSecondStage"] = pars[4]->secondStage(); + break; + case LauPolarGammaCPCoeffSet::DecayType::ADS_Favoured : + case LauPolarGammaCPCoeffSet::DecayType::ADS_Suppressed : + j["rB"] = pars[3]->value(); + j["deltaB"] = pars[4]->value(); + j["rD"] = pars[5]->value(); + j["deltaD"] = pars[6]->value(); + + j["rBFixed"] = pars[3]->fixed(); + j["deltaBFixed"] = pars[4]->fixed(); + j["rDFixed"] = pars[5]->fixed(); + j["deltaDFixed"] = pars[6]->fixed(); + + j["rBSecondStage"] = pars[3]->secondStage(); + j["deltaBSecondStage"] = pars[4]->secondStage(); + j["rDSecondStage"] = pars[5]->secondStage(); + j["deltaDSecondStage"] = pars[6]->secondStage(); + break; + case LauPolarGammaCPCoeffSet::DecayType::GLW_CPOdd_btouOnly : + case LauPolarGammaCPCoeffSet::DecayType::GLW_CPEven_btouOnly : + case LauPolarGammaCPCoeffSet::DecayType::ADS_Suppressed_btouOnly : + break; + case LauPolarGammaCPCoeffSet::DecayType::ADS_Favoured_btouOnly : + j["rD"] = pars[3]->value(); + j["deltaD"] = pars[4]->value(); + + j["rDFixed"] = pars[3]->fixed(); + j["deltaDFixed"] = pars[4]->fixed(); + + j["rDSecondStage"] = pars[3]->secondStage(); + j["deltaDSecondStage"] = pars[4]->secondStage(); + break; + }; +} diff --git a/src/LauRealImagCPCoeffSet.cc b/src/LauRealImagCPCoeffSet.cc index 6cca8b4..2962005 100644 --- a/src/LauRealImagCPCoeffSet.cc +++ b/src/LauRealImagCPCoeffSet.cc @@ -1,250 +1,299 @@ /* Copyright 2014 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 LauRealImagCPCoeffSet.cc \brief File containing implementation of LauRealImagCPCoeffSet class. */ #include #include #include #include "TMath.h" #include "TRandom.h" #include "LauRealImagCPCoeffSet.hh" #include "LauComplex.hh" #include "LauConstants.hh" #include "LauParameter.hh" #include "LauPrint.hh" ClassImp(LauRealImagCPCoeffSet) LauRealImagCPCoeffSet::LauRealImagCPCoeffSet(const TString& compName, const Double_t x, const Double_t y, const Double_t xbar, const Double_t ybar, const Bool_t xFixed, const Bool_t yFixed, const Bool_t xbarFixed, const Bool_t ybarFixed) : LauAbsCoeffSet{ compName }, x_{ std::make_unique("X", x, minRealImagPart_, maxRealImagPart_, xFixed) }, y_{ std::make_unique("Y", y, minRealImagPart_, maxRealImagPart_, yFixed) }, xbar_{ std::make_unique("Xbar", xbar, minRealImagPart_, maxRealImagPart_, xbarFixed) }, ybar_{ std::make_unique("Ybar", ybar, minRealImagPart_, maxRealImagPart_, ybarFixed) }, particleCoeff_{ x,y }, antiparticleCoeff_{ xbar,ybar }, acp_{ "ACP", 0.0, -1.0, 1.0, kTRUE } { } LauRealImagCPCoeffSet::LauRealImagCPCoeffSet(const LauRealImagCPCoeffSet& rhs, CloneOption cloneOption, Double_t constFactor) : LauAbsCoeffSet{ rhs.name() }, particleCoeff_{ rhs.particleCoeff_ }, antiparticleCoeff_{ rhs.antiparticleCoeff_ }, acp_{ rhs.acp_ } { if ( cloneOption == CloneOption::All || cloneOption == CloneOption::TieRealPart ) { x_.reset( rhs.x_->createClone(constFactor) ); xbar_.reset( rhs.xbar_->createClone(constFactor) ); } else { x_ = std::make_unique("X", rhs.x_->value(), minRealImagPart_, maxRealImagPart_, rhs.x_->fixed()); if ( rhs.x_->blind() ) { const LauBlind* blinder { rhs.x_->blinder() }; x_->blindParameter( blinder->blindingString(), blinder->blindingWidth() ); } xbar_ = std::make_unique("Xbar", rhs.xbar_->value(), minRealImagPart_, maxRealImagPart_, rhs.xbar_->fixed()); if ( rhs.xbar_->blind() ) { const LauBlind* blinder { rhs.xbar_->blinder() }; xbar_->blindParameter( blinder->blindingString(), blinder->blindingWidth() ); } } if ( cloneOption == CloneOption::All || cloneOption == CloneOption::TieImagPart ) { y_.reset( rhs.y_->createClone(constFactor) ); ybar_.reset( rhs.ybar_->createClone(constFactor) ); } else { y_ = std::make_unique("Y", rhs.y_->value(), minRealImagPart_, maxRealImagPart_, rhs.y_->fixed()); if ( rhs.y_->blind() ) { const LauBlind* blinder { rhs.y_->blinder() }; y_->blindParameter( blinder->blindingString(), blinder->blindingWidth() ); } ybar_ = std::make_unique("Ybar", rhs.ybar_->value(), minRealImagPart_, maxRealImagPart_, rhs.ybar_->fixed()); if ( rhs.ybar_->blind() ) { const LauBlind* blinder { rhs.ybar_->blinder() }; ybar_->blindParameter( blinder->blindingString(), blinder->blindingWidth() ); } } } std::vector LauRealImagCPCoeffSet::getParameters() { return { x_.get(), y_.get(), xbar_.get(), ybar_.get() }; } +std::vector LauRealImagCPCoeffSet::getParameters() const +{ + return { x_.get(), y_.get(), xbar_.get(), ybar_.get() }; +} + void LauRealImagCPCoeffSet::printParValues() const { std::cout << "INFO in LauRealImagCPCoeffSet::printParValues : Component \"" << this->name() << "\" has "; std::cout << "x = " << x_->value() << ",\t"; std::cout << "y = " << y_->value() << ",\t"; std::cout << "xbar = " << xbar_->value() << ",\t"; std::cout << "ybar = " << ybar_->value() << "." << std::endl; } void LauRealImagCPCoeffSet::printTableHeading(std::ostream& stream) const { stream<<"\\begin{tabular}{|l|c|c|c|c|}"<name() }; resName = resName.ReplaceAll("_", "\\_"); stream<value()); stream<<" \\pm "; print.printFormat(stream, x_->error()); stream<<"$ & $"; print.printFormat(stream, y_->value()); stream<<" \\pm "; print.printFormat(stream, y_->error()); stream<<"$ & $"; print.printFormat(stream, xbar_->value()); stream<<" \\pm "; print.printFormat(stream, xbar_->error()); stream<<"$ & $"; print.printFormat(stream, ybar_->value()); stream<<" \\pm "; print.printFormat(stream, ybar_->error()); stream<<"$ \\\\"<fixed() == kFALSE) { // Choose a value for "X" between -3.0 and 3.0 Double_t value = LauAbsCoeffSet::getRandomiser()->Rndm()*6.0 - 3.0; x_->initValue(value); x_->value(value); } if (y_->fixed() == kFALSE) { // Choose a value for "Y" between -3.0 and 3.0 Double_t value = LauAbsCoeffSet::getRandomiser()->Rndm()*6.0 - 3.0; y_->initValue(value); y_->value(value); } if (xbar_->fixed() == kFALSE) { // Choose a value for "Xbar" between -3.0 and 3.0 Double_t value = LauAbsCoeffSet::getRandomiser()->Rndm()*6.0 - 3.0; xbar_->initValue(value); xbar_->value(value); } if (ybar_->fixed() == kFALSE) { // Choose a value for "Ybar" between -3.0 and 3.0 Double_t value = LauAbsCoeffSet::getRandomiser()->Rndm()*6.0 - 3.0; ybar_->initValue(value); ybar_->value(value); } } void LauRealImagCPCoeffSet::finaliseValues() { // update the pulls x_->updatePull(); y_->updatePull(); xbar_->updatePull(); ybar_->updatePull(); } const LauComplex& LauRealImagCPCoeffSet::particleCoeff() { particleCoeff_.setRealImagPart( x_->unblindValue(), y_->unblindValue() ); return particleCoeff_; } const LauComplex& LauRealImagCPCoeffSet::antiparticleCoeff() { antiparticleCoeff_.setRealImagPart( xbar_->unblindValue(), ybar_->unblindValue() ); return antiparticleCoeff_; } void LauRealImagCPCoeffSet::setCoeffValues( const LauComplex& coeff, const LauComplex& coeffBar, Bool_t init ) { const Double_t xVal{ coeff.re() }; const Double_t yVal{ coeff.im() }; const Double_t xBarVal{ coeffBar.re() }; const Double_t yBarVal{ coeffBar.im() }; x_->value( xVal ); y_->value( yVal ); xbar_->value( xBarVal ); ybar_->value( yBarVal ); if ( init ) { x_->genValue( xVal ); y_->genValue( yVal ); xbar_->genValue( xBarVal ); ybar_->genValue( yBarVal ); x_->initValue( xVal ); y_->initValue( yVal ); xbar_->initValue( xBarVal ); ybar_->initValue( yBarVal ); } } LauParameter LauRealImagCPCoeffSet::acp() { // set the name const TString parName{ this->baseName() + "_ACP" }; acp_.name(parName); // work out the ACP value const Double_t csq { x_->value()*x_->value() + y_->value()*y_->value() }; const Double_t cbarsq { xbar_->value()*xbar_->value() + ybar_->value()*ybar_->value() }; const Double_t numer { cbarsq - csq }; const Double_t denom { cbarsq + csq }; const Double_t value { numer/denom }; // is it fixed? const Bool_t fixed { x_->fixed() && y_->fixed() && xbar_->fixed() && ybar_->fixed() }; acp_.fixed(fixed); // we can't work out the error without the covariance matrix const Double_t error{0.0}; // set the value and error acp_.valueAndErrors(value,error); return acp_; } LauRealImagCPCoeffSet* LauRealImagCPCoeffSet::createClone_impl(const TString& newName, const CloneOption cloneOption, const Double_t constFactor) { if ( ! ( cloneOption == CloneOption::All || cloneOption == CloneOption::TieRealPart || cloneOption == CloneOption::TieImagPart ) ) { std::cerr << "ERROR in LauRealImagCPCoeffSet::createClone : Invalid clone option" << std::endl; return nullptr; } auto clone = new LauRealImagCPCoeffSet{ *this, cloneOption, constFactor }; clone->name( newName ); return clone; } + +LauRealImagCPCoeffSet nlohmann::adl_serializer::from_json(const json& j) +{ + const LauCoeffType type { j.at("type").get() }; + if ( type != LauCoeffType::RealImagCP ) { + throw LauWrongCoeffType("Wrong coefficient type given to construct LauRealImagCPCoeffSet"); + } + + const TString name { j.at("name").get().c_str() }; + + // TODO - handle cloned coeffs + + const Double_t x { j.at("x").get() }; + const Double_t y { j.at("y").get() }; + const Double_t xbar { j.at("xbar").get() }; + const Double_t ybar { j.at("ybar").get() }; + + const Bool_t xFixed { j.at("xFixed").get() }; + const Bool_t yFixed { j.at("yFixed").get() }; + const Bool_t xbarFixed { j.at("xbarFixed").get() }; + const Bool_t ybarFixed { j.at("ybarFixed").get() }; + + return { name, x, y, xbar, ybar, xFixed, yFixed, xbarFixed, ybarFixed }; +} + +void nlohmann::adl_serializer::to_json(json& j, const LauRealImagCPCoeffSet& t) +{ + j["type"] = LauCoeffType::RealImagCP; + j["name"] = t.name(); + + // TODO - handle cloned coeffs + + auto pars = t.getParameters(); + + j["x"] = pars[0]->value(); + j["y"] = pars[1]->value(); + j["xbar"] = pars[2]->value(); + j["ybar"] = pars[3]->value(); + + j["xFixed"] = pars[0]->fixed(); + j["yFixed"] = pars[1]->fixed(); + j["xbarFixed"] = pars[2]->fixed(); + j["ybarFixed"] = pars[3]->fixed(); +} diff --git a/src/LauRealImagCoeffSet.cc b/src/LauRealImagCoeffSet.cc index c32bc4b..3784191 100644 --- a/src/LauRealImagCoeffSet.cc +++ b/src/LauRealImagCoeffSet.cc @@ -1,180 +1,209 @@ /* 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 LauRealImagCoeffSet.cc \brief File containing implementation of LauRealImagCoeffSet class. */ #include #include #include #include "TMath.h" #include "TRandom.h" #include "LauComplex.hh" #include "LauConstants.hh" #include "LauRealImagCoeffSet.hh" #include "LauParameter.hh" #include "LauPrint.hh" ClassImp(LauRealImagCoeffSet) LauRealImagCoeffSet::LauRealImagCoeffSet(const TString& compName, const Double_t x, const Double_t y, const Bool_t xFixed, const Bool_t yFixed) : LauAbsCoeffSet{ compName }, x_{ std::make_unique("X",x,minRealImagPart_,maxRealImagPart_,xFixed) }, y_{ std::make_unique("Y",y,minRealImagPart_,maxRealImagPart_,yFixed) }, coeff_{ x,y } { } LauRealImagCoeffSet::LauRealImagCoeffSet(const LauRealImagCoeffSet& rhs, CloneOption cloneOption, Double_t constFactor) : LauAbsCoeffSet{ rhs.name() }, coeff_{ rhs.coeff_ } { if ( cloneOption == CloneOption::All || cloneOption == CloneOption::TieRealPart ) { x_.reset( rhs.x_->createClone(constFactor) ); } else { x_ = std::make_unique("X", rhs.x_->value(), minRealImagPart_, maxRealImagPart_, rhs.x_->fixed()); if ( rhs.x_->blind() ) { const LauBlind* blinder { rhs.x_->blinder() }; x_->blindParameter( blinder->blindingString(), blinder->blindingWidth() ); } } if ( cloneOption == CloneOption::All || cloneOption == CloneOption::TieImagPart ) { y_.reset( rhs.y_->createClone(constFactor) ); } else { y_ = std::make_unique("Y", rhs.y_->value(), minRealImagPart_, maxRealImagPart_, rhs.y_->fixed()); if ( rhs.y_->blind() ) { const LauBlind* blinder { rhs.y_->blinder() }; y_->blindParameter( blinder->blindingString(), blinder->blindingWidth() ); } } } -std::vector LauRealImagCoeffSet::getParameters() -{ - return { x_.get(), y_.get() }; -} - void LauRealImagCoeffSet::printParValues() const { std::cout<<"INFO in LauRealImagCoeffSet::printParValues : Component \""<name()<<"\" has real part = "<value()<<" and imaginary part = "<value()<<"."<name() }; resName = resName.ReplaceAll("_", "\\_"); stream<value()); stream<<" \\pm "; print.printFormat(stream, x_->error()); stream<<"$ & $"; print.printFormat(stream, y_->value()); stream<<" \\pm "; print.printFormat(stream, y_->error()); stream<<"$ \\\\"<fixed() == kFALSE) { // Choose a value between -10.0 and 10.0 Double_t value = LauAbsCoeffSet::getRandomiser()->Rndm()*20.0 - 10.0; x_->initValue(value); x_->value(value); } if (y_->fixed() == kFALSE) { // Choose a value between -10.0 and 10.0 Double_t value = LauAbsCoeffSet::getRandomiser()->Rndm()*20.0 - 10.0; y_->initValue(value); y_->value(value); } } void LauRealImagCoeffSet::finaliseValues() { x_->updatePull(); y_->updatePull(); } const LauComplex& LauRealImagCoeffSet::particleCoeff() { coeff_.setRealImagPart(x_->unblindValue(), y_->unblindValue()); return coeff_; } const LauComplex& LauRealImagCoeffSet::antiparticleCoeff() { return this->particleCoeff(); } void LauRealImagCoeffSet::setCoeffValues( const LauComplex& coeff, const LauComplex& coeffBar, Bool_t init ) { LauComplex average{ coeff }; average += coeffBar; average.rescale( 0.5 ); const Double_t xVal{ average.re() }; const Double_t yVal{ average.im() }; x_->value( xVal ); y_->value( yVal ); if ( init ) { x_->genValue( xVal ); y_->genValue( yVal ); x_->initValue( xVal ); y_->initValue( yVal ); } } LauParameter LauRealImagCoeffSet::acp() { const TString parName{ this->baseName() + "_ACP" }; return LauParameter{parName,0.0}; } LauRealImagCoeffSet* LauRealImagCoeffSet::createClone_impl(const TString& newName, const CloneOption cloneOption, const Double_t constFactor) { if ( ! ( cloneOption == CloneOption::All || cloneOption == CloneOption::TieRealPart || cloneOption == CloneOption::TieImagPart ) ) { std::cerr << "ERROR in LauRealImagCoeffSet::createClone : Invalid clone option" << std::endl; return nullptr; } auto clone = new LauRealImagCoeffSet{ *this, cloneOption, constFactor }; clone->name( newName ); return clone; } + +LauRealImagCoeffSet nlohmann::adl_serializer::from_json(const json& j) +{ + const LauCoeffType type { j.at("type").get() }; + if ( type != LauCoeffType::RealImag ) { + throw LauWrongCoeffType("Wrong coefficient type given to construct LauRealImagCoeffSet"); + } + + const TString name { j.at("name").get().c_str() }; + + // TODO - handle cloned coeffs + + const Double_t x { j.at("x").get() }; + const Double_t y { j.at("y").get() }; + const Bool_t xFixed { j.at("xFixed").get() }; + const Bool_t yFixed { j.at("yFixed").get() }; + + return { name, x, y, xFixed, yFixed }; +} + +void nlohmann::adl_serializer::to_json(json& j, const LauRealImagCoeffSet& t) +{ + j["type"] = LauCoeffType::RealImag; + j["name"] = t.name(); + + // TODO - handle cloned coeffs + + auto pars = t.getParameters(); + + j["x"] = pars[0]->value(); + j["y"] = pars[1]->value(); + j["xFixed"] = pars[0]->fixed(); + j["yFixed"] = pars[1]->fixed(); +} diff --git a/src/LauRealImagGammaCPCoeffSet.cc b/src/LauRealImagGammaCPCoeffSet.cc index f8bd611..8c6eb5e 100644 --- a/src/LauRealImagGammaCPCoeffSet.cc +++ b/src/LauRealImagGammaCPCoeffSet.cc @@ -1,291 +1,357 @@ /* Copyright 2014 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 LauRealImagGammaCPCoeffSet.cc \brief File containing implementation of LauRealImagGammaCPCoeffSet class. */ #include #include #include #include "TMath.h" #include "TRandom.h" #include "LauRealImagGammaCPCoeffSet.hh" #include "LauComplex.hh" #include "LauConstants.hh" #include "LauParameter.hh" #include "LauPrint.hh" ClassImp(LauRealImagGammaCPCoeffSet) LauRealImagGammaCPCoeffSet::LauRealImagGammaCPCoeffSet(const TString& compName, const Double_t x, const Double_t y, const Double_t xCP, const Double_t yCP, const Double_t xbarCP, const Double_t ybarCP, const Bool_t xFixed, const Bool_t yFixed, const Bool_t xCPFixed, const Bool_t yCPFixed, const Bool_t xbarCPFixed, const Bool_t ybarCPFixed) : LauAbsCoeffSet{ compName }, x_{ std::make_unique("X", x, minRealImagPart_, maxRealImagPart_, xFixed) }, y_{ std::make_unique("Y", y, minRealImagPart_, maxRealImagPart_, yFixed) }, xCP_{ std::make_unique("XCP", xCP, minRealImagPart_, maxRealImagPart_, xCPFixed) }, yCP_{ std::make_unique("YCP", yCP, minRealImagPart_, maxRealImagPart_, yCPFixed) }, xbarCP_{ std::make_unique("XbarCP", xbarCP, minRealImagPart_, maxRealImagPart_, xbarCPFixed) }, ybarCP_{ std::make_unique("YbarCP", ybarCP, minRealImagPart_, maxRealImagPart_, ybarCPFixed) }, nonCPPart_{ x, y }, cpPart_{ 1+xCP, yCP }, cpAntiPart_{ 1+xbarCP, ybarCP }, particleCoeff_{ nonCPPart_ * cpPart_ }, antiparticleCoeff_{ nonCPPart_ * cpAntiPart_ }, acp_{ "ACP", (antiparticleCoeff_.abs2()-particleCoeff_.abs2())/(antiparticleCoeff_.abs2()+particleCoeff_.abs2()), -1.0, 1.0, xCPFixed&&yCPFixed&&xbarCPFixed&&ybarCPFixed } { } LauRealImagGammaCPCoeffSet::LauRealImagGammaCPCoeffSet(const LauRealImagGammaCPCoeffSet& rhs, const CloneOption cloneOption, const Double_t constFactor) : LauAbsCoeffSet{ rhs.name() }, nonCPPart_{ rhs.nonCPPart_ }, cpPart_{ rhs.cpPart_ }, cpAntiPart_{ rhs.cpAntiPart_ }, particleCoeff_{ rhs.particleCoeff_ }, antiparticleCoeff_{ rhs.antiparticleCoeff_ }, acp_{ rhs.acp_ } { if ( cloneOption == CloneOption::All || cloneOption == CloneOption::TieRealPart ) { x_.reset( rhs.x_->createClone(constFactor) ); } else { x_ = std::make_unique("X", rhs.x_->value(), minRealImagPart_, maxRealImagPart_, rhs.x_->fixed()); if ( rhs.x_->blind() ) { const LauBlind* blinder { rhs.x_->blinder() }; x_->blindParameter( blinder->blindingString(), blinder->blindingWidth() ); } } if ( cloneOption == CloneOption::All || cloneOption == CloneOption::TieImagPart ) { y_.reset( rhs.y_->createClone(constFactor) ); } else { y_ = std::make_unique("Y", rhs.y_->value(), minRealImagPart_, maxRealImagPart_, rhs.y_->fixed()); if ( rhs.y_->blind() ) { const LauBlind* blinder { rhs.y_->blinder() }; y_->blindParameter( blinder->blindingString(), blinder->blindingWidth() ); } } if ( cloneOption == CloneOption::All || cloneOption == CloneOption::TieCPPars ) { xCP_.reset( rhs.xCP_->createClone(constFactor) ); yCP_.reset( rhs.yCP_->createClone(constFactor) ); xbarCP_.reset( rhs.xbarCP_->createClone(constFactor) ); ybarCP_.reset( rhs.ybarCP_->createClone(constFactor) ); } else { xCP_ = std::make_unique("XCP", rhs.xCP_->value(), minRealImagPart_, maxRealImagPart_, rhs.xCP_->fixed()); if ( rhs.xCP_->blind() ) { const LauBlind* blinder { rhs.xCP_->blinder() }; xCP_->blindParameter( blinder->blindingString(), blinder->blindingWidth() ); } yCP_ = std::make_unique("YCP", rhs.yCP_->value(), minRealImagPart_, maxRealImagPart_, rhs.yCP_->fixed()); if ( rhs.yCP_->blind() ) { const LauBlind* blinder { rhs.yCP_->blinder() }; yCP_->blindParameter( blinder->blindingString(), blinder->blindingWidth() ); } xbarCP_ = std::make_unique("XbarCP", rhs.xbarCP_->value(), minRealImagPart_, maxRealImagPart_, rhs.xbarCP_->fixed()); if ( rhs.xbarCP_->blind() ) { const LauBlind* blinder { rhs.xbarCP_->blinder() }; xbarCP_->blindParameter( blinder->blindingString(), blinder->blindingWidth() ); } ybarCP_ = std::make_unique("YbarCP", rhs.ybarCP_->value(), minRealImagPart_, maxRealImagPart_, rhs.ybarCP_->fixed()); if ( rhs.ybarCP_->blind() ) { const LauBlind* blinder { rhs.ybarCP_->blinder() }; ybarCP_->blindParameter( blinder->blindingString(), blinder->blindingWidth() ); } } } std::vector LauRealImagGammaCPCoeffSet::getParameters() { - std::vector pars; - pars.reserve(6); - pars.push_back(x_.get()); - pars.push_back(y_.get()); - if(!xCP_->fixed()) pars.push_back(xCP_.get()); - if(!yCP_->fixed()) pars.push_back(yCP_.get()); - if(!xbarCP_->fixed()) pars.push_back(xbarCP_.get()); - if(!ybarCP_->fixed()) pars.push_back(ybarCP_.get()); - return pars; + return { + x_.get(), + y_.get(), + xCP_.get(), + yCP_.get(), + xbarCP_.get(), + ybarCP_.get() + }; +} + +std::vector LauRealImagGammaCPCoeffSet::getParameters() const +{ + return { + x_.get(), + y_.get(), + xCP_.get(), + yCP_.get(), + xbarCP_.get(), + ybarCP_.get() + }; } void LauRealImagGammaCPCoeffSet::printParValues() const { std::cout << "INFO in LauRealImagGammaCPCoeffSet::printParValues : Component \"" << this->name() << "\" has "; std::cout << "x = " << x_->value() << ",\t"; std::cout << "y = " << y_->value() << ",\t"; std::cout << "xCP = " << xCP_->value() << ",\t"; std::cout << "yCP = " << yCP_->value() << ",\t"; std::cout << "xbarCP = " << xbarCP_->value() << ",\t"; std::cout << "ybarCP = " << ybarCP_->value() << "." << std::endl; } void LauRealImagGammaCPCoeffSet::printTableHeading(std::ostream& stream) const { stream<<"\\begin{tabular}{|l|c|c|c|c|c|c|}"<name() }; resName = resName.ReplaceAll("_", "\\_"); stream<value()); stream<<" \\pm "; print.printFormat(stream, x_->error()); stream<<"$ & $"; print.printFormat(stream, y_->value()); stream<<" \\pm "; print.printFormat(stream, y_->error()); stream<<"$ & $"; print.printFormat(stream, xCP_->value()); stream<<" \\pm "; print.printFormat(stream, xCP_->error()); stream<<"$ & $"; print.printFormat(stream, yCP_->value()); stream<<" \\pm "; print.printFormat(stream, yCP_->error()); stream<<"$ & $"; print.printFormat(stream, xbarCP_->value()); stream<<" \\pm "; print.printFormat(stream, xbarCP_->error()); stream<<"$ & $"; print.printFormat(stream, ybarCP_->value()); stream<<" \\pm "; print.printFormat(stream, ybarCP_->error()); stream<<"$ \\\\"<fixed() == kFALSE) { // Choose a value for "X" between -3.0 and 3.0 const Double_t value { LauAbsCoeffSet::getRandomiser()->Rndm()*6.0 - 3.0 }; x_->initValue(value); x_->value(value); } if (y_->fixed() == kFALSE) { // Choose a value for "Y" between -3.0 and 3.0 const Double_t value { LauAbsCoeffSet::getRandomiser()->Rndm()*6.0 - 3.0 }; y_->initValue(value); y_->value(value); } if (xCP_->fixed() == kFALSE) { // Choose a value for "XCP" between -3.0 and 3.0 const Double_t value { LauAbsCoeffSet::getRandomiser()->Rndm()*6.0 - 3.0 }; xCP_->initValue(value); xCP_->value(value); } if (yCP_->fixed() == kFALSE) { // Choose a value for "YCP" between -3.0 and 3.0 const Double_t value { LauAbsCoeffSet::getRandomiser()->Rndm()*6.0 - 3.0 }; yCP_->initValue(value); yCP_->value(value); } if (xbarCP_->fixed() == kFALSE) { // Choose a value for "XbarCP" between -3.0 and 3.0 const Double_t value { LauAbsCoeffSet::getRandomiser()->Rndm()*6.0 - 3.0 }; xbarCP_->initValue(value); xbarCP_->value(value); } if (ybarCP_->fixed() == kFALSE) { // Choose a value for "YbarCP" between -3.0 and 3.0 const Double_t value { LauAbsCoeffSet::getRandomiser()->Rndm()*6.0 - 3.0 }; ybarCP_->initValue(value); ybarCP_->value(value); } } void LauRealImagGammaCPCoeffSet::finaliseValues() { // update the pulls x_->updatePull(); y_->updatePull(); xCP_->updatePull(); yCP_->updatePull(); xbarCP_->updatePull(); ybarCP_->updatePull(); } const LauComplex& LauRealImagGammaCPCoeffSet::particleCoeff() { nonCPPart_.setRealImagPart( x_->unblindValue(), y_->unblindValue() ); cpPart_.setRealImagPart( 1.0+xCP_->unblindValue(), yCP_->unblindValue() ); particleCoeff_ = nonCPPart_ * cpPart_; return particleCoeff_; } const LauComplex& LauRealImagGammaCPCoeffSet::antiparticleCoeff() { nonCPPart_.setRealImagPart( x_->unblindValue(), y_->unblindValue() ); cpAntiPart_.setRealImagPart( 1.0+xbarCP_->unblindValue(), ybarCP_->unblindValue() ); antiparticleCoeff_ = nonCPPart_ * cpAntiPart_; return antiparticleCoeff_; } void LauRealImagGammaCPCoeffSet::setCoeffValues( const LauComplex&, const LauComplex&, Bool_t ) { std::cerr << "ERROR in LauCartesianGammaCPCoeffSet::setCoeffValues : Method not supported by this class - too many parameters" << std::endl; } LauParameter LauRealImagGammaCPCoeffSet::acp() { // set the name const TString parName{ this->baseName() + "_ACP" }; acp_.name(parName); // work out the ACP value const LauComplex nonCPPart{ x_->value(), y_->value() }; const LauComplex cpPart{ 1.0+xCP_->value(), yCP_->value() }; const LauComplex cpAntiPart{ 1.0+xbarCP_->value(), ybarCP_->value() }; const LauComplex partCoeff { nonCPPart * cpPart }; const LauComplex antiCoeff { nonCPPart * cpAntiPart }; const Double_t numer { antiCoeff.abs2() - partCoeff.abs2() }; const Double_t denom { antiCoeff.abs2() + partCoeff.abs2() }; const Double_t value { numer/denom }; // is it fixed? const Bool_t fixed { xCP_->fixed() && yCP_->fixed() && xbarCP_->fixed() && ybarCP_->fixed() }; acp_.fixed(fixed); // we can't work out the error without the covariance matrix const Double_t error{0.0}; // set the value and error acp_.valueAndErrors(value,error); return acp_; } LauRealImagGammaCPCoeffSet* LauRealImagGammaCPCoeffSet::createClone_impl(const TString& newName, const CloneOption cloneOption, const Double_t constFactor) { if ( ! ( cloneOption == CloneOption::All || cloneOption == CloneOption::TieRealPart || cloneOption == CloneOption::TieImagPart || cloneOption == CloneOption::TieCPPars ) ) { std::cerr << "ERROR in LauRealImagGammaCPCoeffSet::createClone : Invalid clone option" << std::endl; return nullptr; } auto clone = new LauRealImagGammaCPCoeffSet{ *this, cloneOption, constFactor }; clone->name( newName ); return clone; } + +LauRealImagGammaCPCoeffSet nlohmann::adl_serializer::from_json(const json& j) +{ + const LauCoeffType type { j.at("type").get() }; + if ( type != LauCoeffType::RealImagGammaCP ) { + throw LauWrongCoeffType("Wrong coefficient type given to construct LauRealImagGammaCPCoeffSet"); + } + + const TString name { j.at("name").get().c_str() }; + + // TODO - handle cloned coeffs + + const Double_t x { j.at("x").get() }; + const Double_t y { j.at("y").get() }; + const Double_t xCP { j.at("xCP").get() }; + const Double_t yCP { j.at("yCP").get() }; + const Double_t xbarCP { j.at("xbarCP").get() }; + const Double_t ybarCP { j.at("ybarCP").get() }; + + const Bool_t xFixed { j.at("xFixed").get() }; + const Bool_t yFixed { j.at("yFixed").get() }; + const Bool_t xCPFixed { j.at("xCPFixed").get() }; + const Bool_t yCPFixed { j.at("yCPFixed").get() }; + const Bool_t xbarCPFixed { j.at("xbarCPFixed").get() }; + const Bool_t ybarCPFixed { j.at("ybarCPFixed").get() }; + + return { name, + x, y, xCP, yCP, xbarCP, ybarCP, + xFixed, yFixed, xCPFixed, yCPFixed, xbarCPFixed, ybarCPFixed + }; +} + +void nlohmann::adl_serializer::to_json(json& j, const LauRealImagGammaCPCoeffSet& t) +{ + j["type"] = LauCoeffType::RealImagGammaCP; + j["name"] = t.name(); + + // TODO - handle cloned coeffs + + auto pars = t.getParameters(); + + j["x"] = pars[0]->value(); + j["y"] = pars[1]->value(); + j["xCP"] = pars[2]->value(); + j["yCP"] = pars[3]->value(); + j["xbarCP"] = pars[4]->value(); + j["ybarCP"] = pars[5]->value(); + + j["xFixed"] = pars[0]->fixed(); + j["yFixed"] = pars[1]->fixed(); + j["xCPFixed"] = pars[2]->fixed(); + j["yCPFixed"] = pars[3]->fixed(); + j["xbarCPFixed"] = pars[4]->fixed(); + j["ybarCPFixed"] = pars[5]->fixed(); +} diff --git a/src/LauSimpleFitModel.cc b/src/LauSimpleFitModel.cc index 21eb5cb..9ab3744 100644 --- a/src/LauSimpleFitModel.cc +++ b/src/LauSimpleFitModel.cc @@ -1,2336 +1,2336 @@ /* Copyright 2004 University of Warwick Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Laura++ package authors: John Back Paul Harrison Thomas Latham */ /*! \file LauSimpleFitModel.cc \brief File containing implementation of LauSimpleFitModel class. */ #include #include #include #include #include "TFile.h" #include "TH2.h" #include "TMinuit.h" #include "TRandom.h" #include "TSystem.h" #include "TVirtualFitter.h" #include "LauAbsBkgndDPModel.hh" #include "LauAbsCoeffSet.hh" #include "LauIsobarDynamics.hh" #include "LauAbsPdf.hh" #include "LauComplex.hh" #include "LauConstants.hh" #include "LauDaughters.hh" #include "LauEmbeddedData.hh" #include "LauEffModel.hh" #include "LauFitNtuple.hh" #include "LauGenNtuple.hh" #include "LauKinematics.hh" #include "LauPrint.hh" #include "LauRandom.hh" #include "LauScfMap.hh" #include "LauSimpleFitModel.hh" #include "TGraph2D.h" #include "TGraph.h" #include "TStyle.h" #include "TCanvas.h" ClassImp(LauSimpleFitModel) LauSimpleFitModel::LauSimpleFitModel(LauIsobarDynamics* sigModel) : LauAbsFitModel(), sigDPModel_(sigModel), kinematics_(sigModel ? sigModel->getKinematics() : 0), usingBkgnd_(kFALSE), nSigComp_(0), nSigDPPar_(0), nExtraPdfPar_(0), nNormPar_(0), meanEff_("meanEff",0.0,0.0,1.0), dpRate_("dpRate",0.0,0.0,100.0), //signalEvents_("signalEvents",1.0,0.0,1.0), signalEvents_(0), useSCF_(kFALSE), useSCFHist_(kFALSE), scfFrac_("scfFrac",0.0,0.0,1.0), scfFracHist_(0), scfMap_(0), compareFitData_(kFALSE), signalTree_(0), reuseSignal_(kFALSE), useReweighting_(kFALSE), sigDPLike_(0.0), scfDPLike_(0.0), sigExtraLike_(0.0), scfExtraLike_(0.0), sigTotalLike_(0.0), scfTotalLike_(0.0) { } LauSimpleFitModel::~LauSimpleFitModel() { delete signalTree_; for (LauBkgndEmbDataList::iterator iter = bkgndTree_.begin(); iter != bkgndTree_.end(); ++iter) { delete (*iter); } delete scfFracHist_; } void LauSimpleFitModel::setupBkgndVectors() { UInt_t nBkgnds = this->nBkgndClasses(); bkgndDPModels_.resize( nBkgnds ); bkgndPdfs_.resize( nBkgnds ); bkgndEvents_.resize( nBkgnds ); bkgndTree_.resize( nBkgnds ); reuseBkgnd_.resize( nBkgnds ); bkgndDPLike_.resize( nBkgnds ); bkgndExtraLike_.resize( nBkgnds ); bkgndTotalLike_.resize( nBkgnds ); } void LauSimpleFitModel::setNSigEvents(LauParameter* nSigEvents) { if ( nSigEvents == 0 ) { std::cerr << "ERROR in LauSimpleFitModel::setNSigEvents : The signal yield LauParameter pointer is null." << std::endl; gSystem->Exit(EXIT_FAILURE); } if ( signalEvents_ != 0 ) { std::cerr << "ERROR in LauSimpleFitModel::setNSigEvents : You are trying to overwrite the signal yield." << std::endl; return; } signalEvents_ = nSigEvents; TString name = signalEvents_->name(); if ( ! name.BeginsWith("signalEvents") ) { std::cerr << "ERROR in LauSimpleFitModel::setNSigEvents : The signal yield parameter name should start with \"signalEvents\" (plus any optional suffix)." << std::endl; gSystem->Exit(EXIT_FAILURE); } Double_t value = nSigEvents->value(); signalEvents_->range(-2.0*(TMath::Abs(value)+1.0), 2.0*(TMath::Abs(value)+1.0)); } void LauSimpleFitModel::setNBkgndEvents(LauAbsRValue* nBkgndEvents) { if ( nBkgndEvents == 0 ) { std::cerr << "ERROR in LauSimpleFitModel::setNBkgndEvents : The background yield LauParameter pointer is null." << std::endl; gSystem->Exit(EXIT_FAILURE); } TString yieldName = nBkgndEvents->name(); TString bkgndClassName = yieldName; if ( bkgndClassName.Contains("Events") ) { bkgndClassName.Remove( bkgndClassName.Index("Events") ); } else { yieldName += "Events"; nBkgndEvents->name( yieldName ); } if ( ! this->validBkgndClass( bkgndClassName ) ) { std::cerr << "ERROR in LauSimpleFitModel::setNBkgndEvents : Invalid background class \"" << bkgndClassName << "\"." << 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( bkgndClassName ); if ( bkgndEvents_[bkgndID] != 0 ) { std::cerr << "ERROR in LauSimpleFitModel::setNBkgndEvents : You are trying to overwrite the background yield." << std::endl; return; } 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; } void LauSimpleFitModel::splitSignalComponent( const TH2* dpHisto, const Bool_t upperHalf, const Bool_t fluctuateBins, LauScfMap* scfMap ) { if ( useSCF_ == kTRUE ) { std::cerr << "ERROR in LauSimpleFitModel::splitSignalComponent : Have already setup SCF." << std::endl; return; } if ( dpHisto == 0 ) { std::cerr << "ERROR in LauSimpleFitModel::splitSignalComponent : The histogram pointer is null." << std::endl; return; } const LauDaughters* daughters = sigDPModel_->getDaughters(); scfFracHist_ = new LauEffModel( daughters, 0 ); scfFracHist_->setEffHisto( dpHisto, kTRUE, fluctuateBins, 0.0, 0.0, upperHalf, daughters->squareDP() ); scfMap_ = scfMap; useSCF_ = kTRUE; useSCFHist_ = kTRUE; } void LauSimpleFitModel::splitSignalComponent( const Double_t scfFrac, const Bool_t fixed ) { if ( useSCF_ == kTRUE ) { std::cerr << "ERROR in LauSimpleFitModel::splitSignalComponent : Have already setup SCF." << std::endl; return; } scfFrac_.range( 0.0, 1.0 ); scfFrac_.value( scfFrac ); scfFrac_.initValue( scfFrac ); scfFrac_.genValue( scfFrac ); scfFrac_.fixed( fixed ); useSCF_ = kTRUE; useSCFHist_ = kFALSE; } void LauSimpleFitModel::setBkgndDPModel(const TString& bkgndClass, LauAbsBkgndDPModel* bkgndDPModel) { if (bkgndDPModel == 0) { std::cerr << "ERROR in LauSimpleFitModel::setBkgndDPModel : The model pointer is null." << std::endl; return; } // check that this background name is valid if ( ! this->validBkgndClass( bkgndClass ) ) { std::cerr << "ERROR in LauSimpleFitModel::setBkgndDPModel : 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 ); bkgndDPModels_[bkgndID] = bkgndDPModel; usingBkgnd_ = kTRUE; } void LauSimpleFitModel::setSignalPdf(LauAbsPdf* pdf) { if (pdf==0) { std::cerr << "ERROR in LauSimpleFitModel::setSignalPdf : The PDF pointer is null." << std::endl; return; } signalPdfs_.push_back(pdf); } void LauSimpleFitModel::setSCFPdf(LauAbsPdf* pdf) { if (pdf==0) { std::cerr << "ERROR in LauSimpleFitModel::setSCFPdf : The PDF pointer is null." << std::endl; return; } scfPdfs_.push_back(pdf); } void LauSimpleFitModel::setBkgndPdf(const TString& bkgndClass, LauAbsPdf* pdf) { if (pdf == 0) { std::cerr << "ERROR in LauSimpleFitModel::setBkgndPdf : The PDF pointer is null." << std::endl; return; } // check that this background name is valid if ( ! this->validBkgndClass( bkgndClass ) ) { std::cerr << "ERROR in LauSimpleFitModel::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 LauSimpleFitModel::setAmpCoeffSet(std::unique_ptr coeffSet) { // Resize the coeffPars vector if not already done if ( coeffPars_.empty() ) { coeffPars_.resize( sigDPModel_->getnTotAmp() ); } // Is there a component called compName in the signal model? const TString compName{ coeffSet->name() }; const Int_t index { sigDPModel_->resonanceIndex(compName) }; if ( index < 0 ) { std::cerr << "ERROR in LauSimpleFitModel::setAmpCoeffSet : Signal DP model doesn't contain component \"" << compName << "\"." << std::endl; return; } // Do we already have it in our list of names? if ( coeffPars_[index] != nullptr && coeffPars_[index]->name() == compName) { std::cerr << "ERROR in LauSimpleFitModel::setAmpCoeffSet : Have already set coefficients for \"" << compName << "\"." << std::endl; return; } coeffSet->index(index); std::cout << "INFO in LauSimpleFitModel::setAmpCoeffSet : Added coefficients for component A"<< index << ": \"" << compName << "\" to the fit model." << std::endl; coeffSet->printParValues(); coeffPars_[index] = std::move(coeffSet); ++nSigComp_; } void LauSimpleFitModel::initialise() { // Initialisation if (!this->useDP() && signalPdfs_.empty()) { std::cerr << "ERROR in LauSimpleFitModel::initialise : Signal model doesn't exist for any variable." << std::endl; gSystem->Exit(EXIT_FAILURE); } if (this->useDP()) { // Check that we have all the Dalitz-plot models if ( sigDPModel_ == 0 ) { std::cerr << "ERROR in LauSimpleFitModel::initialise : The pointer to the signal DP model is null.\n"; std::cerr << " : Removing the Dalitz Plot from the model." << std::endl; this->useDP(kFALSE); } if ( usingBkgnd_ ) { for (LauBkgndDPModelList::const_iterator dpmodel_iter = bkgndDPModels_.begin(); dpmodel_iter != bkgndDPModels_.end(); ++dpmodel_iter ) { if ( (*dpmodel_iter) == 0 ) { std::cerr << "ERROR in LauSimpleFitModel::initialise : The pointer to one of the background DP models is null.\n"; std::cerr << " : Removing the Dalitz Plot from the model." << std::endl; this->useDP(kFALSE); break; } } } // Need to check that the number of components we have and that the dynamics has matches up UInt_t nAmp = sigDPModel_->getnTotAmp(); if (nAmp != nSigComp_) { std::cerr << "ERROR in LauSimpleFitModel::initialise : Number of signal DP components with magnitude and phase set not right." << std::endl; gSystem->Exit(EXIT_FAILURE); } // From the initial parameter values calculate the coefficients // so they can be passed to the signal model this->updateCoeffs(); // If all is well, go ahead and initialise them this->initialiseDPModels(); } // 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 = signalPdfs_.begin(); pdf_iter != signalPdfs_.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 (useSCF_) { UInt_t nscfpdfvars(0); for ( LauPdfPList::const_iterator pdf_iter = scfPdfs_.begin(); pdf_iter != scfPdfs_.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" ) { ++nscfpdfvars; } } } if (nscfpdfvars != nsigpdfvars) { std::cerr << "ERROR in LauSimpleFitModel::initialise : There are " << nsigpdfvars << " TM signal PDF variables but " << nscfpdfvars << " SCF signal PDF variables." << std::endl; gSystem->Exit(EXIT_FAILURE); } } if (usingBkgnd_) { for (LauBkgndPdfsList::const_iterator bgclass_iter = bkgndPdfs_.begin(); bgclass_iter != bkgndPdfs_.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 LauSimpleFitModel::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 various extra PDFs this->setExtraPdfParameters(); // Set the initial bg and signal events this->setFitNEvents(); // Check that we have the expected number of fit variables const LauParameterPList& fitVars = this->fitPars(); if (fitVars.size() != (nSigDPPar_ + nExtraPdfPar_ + nNormPar_)) { std::cerr << "ERROR in LauSimpleFitModel::initialise : Number of fit parameters not of expected size." << std::endl; gSystem->Exit(EXIT_FAILURE); } this->setExtraNtupleVars(); } void LauSimpleFitModel::initialiseDPModels() { std::cout << "INFO in LauSimpleFitModel::initialiseDPModels : Initialising DP models" << std::endl; sigDPModel_->initialise(coeffs_); if (usingBkgnd_ == kTRUE) { for (LauBkgndDPModelList::iterator iter = bkgndDPModels_.begin(); iter != bkgndDPModels_.end(); ++iter) { (*iter)->initialise(); } } } void LauSimpleFitModel::recalculateNormalisation() { //std::cout << "INFO in LauSimpleFitModel::recalculateNormalizationInDPModels : Recalc Norm in DP model" << std::endl; sigDPModel_->recalculateNormalisation(); sigDPModel_->modifyDataTree(); } void LauSimpleFitModel::setSignalDPParameters() { // Set the fit parameters for the signal model. nSigDPPar_ = 0; if ( ! this->useDP() ) { return; } std::cout << "INFO in LauSimpleFitModel::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 LauParameterPList& sigDPPars = sigDPModel_->getFloatingParameters(); nSigDPPar_ += this->addResonanceParameters( sigDPPars ); } void LauSimpleFitModel::setExtraPdfParameters() { // Include all the parameters of the various PDFs 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; nExtraPdfPar_ += this->addFitParameters(signalPdfs_); if (useSCF_ == kTRUE) { nExtraPdfPar_ += this->addFitParameters(scfPdfs_); } if (usingBkgnd_ == kTRUE) { for (LauBkgndPdfsList::iterator iter = bkgndPdfs_.begin(); iter != bkgndPdfs_.end(); ++iter) { nExtraPdfPar_ += this->addFitParameters(*iter); } } } void LauSimpleFitModel::setFitNEvents() { if ( signalEvents_ == 0 ) { std::cerr << "ERROR in LauSimpleFitModel::setFitNEvents : Signal yield not defined." << std::endl; return; } nNormPar_ = 0; // initialise the total number of events to be the sum of all the hypotheses Double_t nTotEvts = signalEvents_->value(); for (LauBkgndYieldList::const_iterator iter = bkgndEvents_.begin(); iter != bkgndEvents_.end(); ++iter) { nTotEvts += (*iter)->value(); if ( (*iter) == 0 ) { std::cerr << "ERROR in LauSimpleFitModel::setFitNEvents : Background yield not defined." << std::endl; return; } } this->eventsPerExpt(TMath::FloorNint(nTotEvts)); // if doing an extended ML fit add the number of signal events into the fit parameters if (this->doEMLFit()) { std::cout << "INFO in LauSimpleFitModel::setFitNEvents : Initialising number of events for signal and background components..." << std::endl; // add the signal events to the list of fit parameters nNormPar_ += this->addFitParameters( signalEvents_ ); } else { std::cout << "INFO in LauSimpleFitModel::setFitNEvents : Initialising number of events for background components (and hence signal)..." << std::endl; } if (useSCF_ && !useSCFHist_) { nNormPar_ += this->addFitParameters( &scfFrac_ ); } if (usingBkgnd_ == kTRUE) { nNormPar_ += this->addFitParameters( bkgndEvents_ ); } } void LauSimpleFitModel::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 a fit fraction for each signal component fitFrac_ = sigDPModel_->getFitFractions(); if (fitFrac_.size() != nSigComp_) { std::cerr << "ERROR in LauSimpleFitModel::setExtraNtupleVars : Initial Fit Fraction array of unexpected dimension: " << fitFrac_.size() << std::endl; gSystem->Exit(EXIT_FAILURE); } for (UInt_t i(0); iExit(EXIT_FAILURE); } } // Add the fit fraction that has not been corrected for the efficiency for each signal component fitFracEffUnCorr_ = sigDPModel_->getFitFractionsEfficiencyUncorrected(); if (fitFracEffUnCorr_.size() != nSigComp_) { std::cerr << "ERROR in LauSimpleFitModel::setExtraNtupleVars : Initial Fit Fraction array of unexpected dimension: " << fitFracEffUnCorr_.size() << std::endl; gSystem->Exit(EXIT_FAILURE); } for (UInt_t i(0); iExit(EXIT_FAILURE); } } for (UInt_t i = 0; i < nSigComp_; i++) { for (UInt_t j = i; j < nSigComp_; j++) { extraVars.push_back(fitFrac_[i][j]); extraVars.push_back(fitFracEffUnCorr_[i][j]); } } // Store any extra parameters/quantities from the DP model (e.g. K-matrix total fit fractions) std::vector extraParams = sigDPModel_->getExtraParameters(); std::vector::iterator extraIter; for (extraIter = extraParams.begin(); extraIter != extraParams.end(); ++extraIter) { LauParameter extraParameter = (*extraIter); extraVars.push_back(extraParameter); } // Now add in the DP efficiency value Double_t initMeanEff = sigDPModel_->getMeanEff().initValue(); meanEff_.value(initMeanEff); meanEff_.initValue(initMeanEff); meanEff_.genValue(initMeanEff); extraVars.push_back(meanEff_); // Also add in the DP rate Double_t initDPRate = sigDPModel_->getDPRate().initValue(); dpRate_.value(initDPRate); dpRate_.initValue(initDPRate); dpRate_.genValue(initDPRate); extraVars.push_back(dpRate_); } void LauSimpleFitModel::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 // e.g. to make mag > 0.0 and 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 mag > 0.0, and phase in the right range coeffPars_[i]->finaliseValues(); } } // update the pulls on the events if (this->doEMLFit()) { signalEvents_->updatePull(); } if (useSCF_ && !useSCFHist_) { scfFrac_.updatePull(); } if (usingBkgnd_ == kTRUE) { for (LauBkgndYieldList::iterator iter = bkgndEvents_.begin(); iter != bkgndEvents_.end(); ++iter) { std::vector parameters = (*iter)->getPars(); for ( LauParameter* parameter : parameters ) { parameter->updatePull(); } } } // Update the pulls on all the extra PDFs' parameters this->updateFitParameters(signalPdfs_); if (useSCF_ == kTRUE) { this->updateFitParameters(scfPdfs_); } if (usingBkgnd_ == kTRUE) { for (LauBkgndPdfsList::iterator iter = bkgndPdfs_.begin(); iter != bkgndPdfs_.end(); ++iter) { this->updateFitParameters(*iter); } } // Fill the fit results to the ntuple for current experiment // update the coefficients and then calculate the fit fractions if (this->useDP() == kTRUE) { this->updateCoeffs(); sigDPModel_->updateCoeffs(coeffs_); sigDPModel_->calcExtraInfo(); LauParArray fitFrac = sigDPModel_->getFitFractions(); if (fitFrac.size() != nSigComp_) { std::cerr << "ERROR in LauSimpleFitModel::finaliseFitResults : Fit Fraction array of unexpected dimension: " << fitFrac.size() << std::endl; gSystem->Exit(EXIT_FAILURE); } for (UInt_t i(0); iExit(EXIT_FAILURE); } } LauParArray fitFracEffUnCorr = sigDPModel_->getFitFractionsEfficiencyUncorrected(); if (fitFracEffUnCorr.size() != nSigComp_) { std::cerr << "ERROR in LauSimpleFitModel::finaliseFitResults : Fit Fraction array of unexpected dimension: " << fitFracEffUnCorr.size() << std::endl; gSystem->Exit(EXIT_FAILURE); } for (UInt_t i(0); iExit(EXIT_FAILURE); } } for (UInt_t i(0); igetMeanEff().value()); dpRate_.value(sigDPModel_->getDPRate().value()); this->clearExtraVarVectors(); LauParameterList& extraVars = this->extraPars(); // Then store the final fit parameters, and any extra parameters for // the signal model (e.g. fit fractions) for (UInt_t i(0); i extraParams = sigDPModel_->getExtraParameters(); std::vector::iterator extraIter; for (extraIter = extraParams.begin(); extraIter != extraParams.end(); ++extraIter) { LauParameter extraParameter = (*extraIter); extraVars.push_back(extraParameter); } // Now add in the DP efficiency value extraVars.push_back(meanEff_); // Also add in the DP rate extraVars.push_back(dpRate_); this->printFitFractions(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 LauSimpleFitModel::printFitFractions(std::ostream& output) { // Print out Fit Fractions, total DP rate and mean efficiency for (UInt_t i = 0; i < nSigComp_; i++) { - output << "FitFraction for component " << i << " (" << coeffPars_[i]->name() << ") = " << fitFrac_[i][i] << std::endl; + output << "FitFraction for component " << i << " (" << coeffPars_[i]->name() << ") = " << fitFrac_[i][i].value() << std::endl; } - output << "Overall DP rate (integral of matrix element squared) = " << dpRate_ << std::endl; - output << "Average efficiency weighted by whole DP dynamics = " << meanEff_ << std::endl; + output << "Overall DP rate (integral of matrix element squared) = " << dpRate_.value() << std::endl; + output << "Average efficiency weighted by whole DP dynamics = " << meanEff_.value() << std::endl; } void LauSimpleFitModel::writeOutTable(const TString& outputFile) { // Write out the results of the fit to a tex-readable table // TODO - need to include the yields in this table std::ofstream fout(outputFile); LauPrint print; std::cout << "INFO in LauSimpleFitModel::writeOutTable : Writing out results of the fit to the tex file " << outputFile << std::endl; if (this->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" << std::endl; fout << "\\end{tabular}" << std::endl << std::endl; // print the fit fractions in another fout << "\\begin{tabular}{|l|c|}" << std::endl; fout << "\\hline" << std::endl; fout << "Component & FitFraction \\\\" << std::endl; fout << "\\hline" << std::endl; Double_t fitFracSum(0.0); for (UInt_t i = 0; i < nSigComp_; i++) { TString resName = coeffPars_[i]->name(); resName = resName.ReplaceAll("_", "\\_"); fout << resName << " & $"; Double_t fitFrac = fitFrac_[i][i].value(); fitFracSum += fitFrac; print.printFormat(fout, fitFrac); fout << "$ \\\\" << std::endl; } fout << "\\hline" << std::endl; // Also print out sum of fit fractions fout << "Fit Fraction Sum & $"; print.printFormat(fout, fitFracSum); fout << "$ \\\\" << std::endl; fout << "\\hline" << std::endl; fout << "DP rate & $"; print.printFormat(fout, dpRate_.value()); fout << "$ \\\\" << std::endl; fout << "\\hline" << std::endl; fout << "$< \\varepsilon >$ & $"; print.printFormat(fout, meanEff_.value()); fout << "$ \\\\" << std::endl; fout << "\\hline" << std::endl; fout << "\\end{tabular}" << std::endl << std::endl; } if (!signalPdfs_.empty()) { fout << "\\begin{tabular}{|l|c|}" << std::endl; fout << "\\hline" << std::endl; if (useSCF_ == kTRUE) { fout << "\\Extra TM Signal PDFs' Parameters: & \\\\" << std::endl; } else { fout << "\\Extra Signal PDFs' Parameters: & \\\\" << std::endl; } this->printFitParameters(signalPdfs_, fout); if (useSCF_ == kTRUE && !scfPdfs_.empty()) { fout << "\\hline" << std::endl; fout << "\\Extra SCF Signal PDFs' Parameters: & \\\\" << std::endl; this->printFitParameters(scfPdfs_, fout); } if (usingBkgnd_ == kTRUE && !bkgndPdfs_.empty()) { fout << "\\hline" << std::endl; fout << "\\Extra Background PDFs' Parameters: & \\\\" << std::endl; for (LauBkgndPdfsList::const_iterator iter = bkgndPdfs_.begin(); iter != bkgndPdfs_.end(); ++iter) { this->printFitParameters(*iter, fout); } } fout << "\\hline \n\\end{tabular}" << std::endl << std::endl; } } void LauSimpleFitModel::checkInitFitParams() { // Update the number of signal events to be total-sum(background events) this->updateSigEvents(); // Check whether we want to have randomised initial fit parameters for the signal model if (this->useRandomInitFitPars() == kTRUE) { std::cout << "INFO in LauSimpleFitModel::checkInitFitParams : Setting random parameters for the signal DP model" << std::endl; this->randomiseInitFitPars(); } } void LauSimpleFitModel::randomiseInitFitPars() { // Only randomise those parameters that are not fixed! std::cout << "INFO in LauSimpleFitModel::randomiseInitFitPars : Randomising the initial fit magnitudes and phases of the resonances..." << std::endl; for (UInt_t i = 0; i < nSigComp_; i++) { coeffPars_[i]->randomiseInitValues(); } } std::pair LauSimpleFitModel::eventsToGenerate() { // Determine the number of events to generate for each hypothesis // If we're smearing then smear each one individually LauGenInfo nEvtsGen; // Keep track of whether any yield or asymmetry parameters are blinded Bool_t blind = kFALSE; // Signal if ( signalEvents_->blind() ) { blind = kTRUE; } Double_t evtWeight(1.0); Double_t nEvts = signalEvents_->genValue(); if ( nEvts < 0 ) { evtWeight = -1.0; nEvts = TMath::Abs( nEvts ); } Int_t nEvtsToGen { static_cast(nEvts) }; if (this->doPoissonSmearing()) { nEvtsToGen = LauRandom::randomFun()->Poisson(nEvts); } nEvtsGen["signal"] = std::make_pair( nEvtsToGen, evtWeight ); // Backgrounds const UInt_t nBkgnds = this->nBkgndClasses(); for ( UInt_t bkgndID(0); bkgndID < nBkgnds; ++bkgndID ) { const LauAbsRValue* evtsPar = bkgndEvents_[bkgndID]; if ( evtsPar->blind() ) { blind = kTRUE; } evtWeight = 1.0; nEvts = evtsPar->genValue(); if ( nEvts < 0 ) { evtWeight = -1.0; nEvts = TMath::Abs( nEvts ); } nEvtsToGen = static_cast(nEvts); if (this->doPoissonSmearing()) { nEvtsToGen = LauRandom::randomFun()->Poisson(nEvts); } const TString& bkgndClass = this->bkgndClassName(bkgndID); nEvtsGen[bkgndClass] = std::make_pair( nEvtsToGen, evtWeight ); } return std::make_pair( nEvtsGen, blind ); } Bool_t LauSimpleFitModel::genExpt() { // Routine to generate toy Monte Carlo events according to the various models we have defined. // Determine the number of events to generate for each hypothesis std::pair info = this->eventsToGenerate(); LauGenInfo nEvts = info.first; const Bool_t blind = info.second; 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; } const Bool_t storeSCFTruthInfo = ( useSCF_ || ( this->enableEmbedding() && signalTree_ != 0 && signalTree_->haveBranch("mcMatch") ) ); // Loop over the hypotheses and generate the requested number of events for each one for (LauGenInfo::const_iterator iter = nEvts.begin(); iter != nEvts.end(); ++iter) { const TString& type(iter->first); Int_t nEvtsGen( iter->second.first ); Double_t evtWeight( iter->second.second ); for (Int_t iEvt(0); iEvtsetGenNtupleDoubleBranchValue( "evtWeight", evtWeight ); // Add efficiency information this->setGenNtupleDoubleBranchValue( "efficiency", 1 ); if (type == "signal") { this->setGenNtupleIntegerBranchValue("genSig",1); for ( UInt_t iBkgnd(0); iBkgnd < nBkgnds; ++iBkgnd ) { this->setGenNtupleIntegerBranchValue( bkgndClassNamesGen[iBkgnd], 0 ); } genOK = this->generateSignalEvent(); this->setGenNtupleDoubleBranchValue( "efficiency", sigDPModel_->getEvtEff() ); } else { this->setGenNtupleIntegerBranchValue("genSig",0); if ( storeSCFTruthInfo ) { this->setGenNtupleIntegerBranchValue("genTMSig",0); this->setGenNtupleIntegerBranchValue("genSCFSig",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->setDPBranchValues(); } // Store the event number (within this experiment) this->setGenNtupleIntegerBranchValue("iEvtWithinExpt",evtNum); // and then increment it ++evtNum; this->fillGenNtupleBranches(); if ( !blind && (iEvt%500 == 0) ) { std::cout << "INFO in LauSimpleFitModel::genExpt : Generated event number " << iEvt << " out of " << nEvtsGen << " " << type << " events." << std::endl; } } if (!genOK) { break; } } if (this->useDP() && genOK) { sigDPModel_->checkToyMC(kTRUE,kTRUE); // Get the fit fractions if they're to be written into the latex table if (this->writeLatexTable()) { LauParArray fitFrac = sigDPModel_->getFitFractions(); if (fitFrac.size() != nSigComp_) { std::cerr << "ERROR in LauSimpleFitModel::genExpt : Fit Fraction array of unexpected dimension: " << fitFrac.size() << std::endl; gSystem->Exit(EXIT_FAILURE); } for (UInt_t i(0); iExit(EXIT_FAILURE); } } for (UInt_t i(0); igetMeanEff().value()); dpRate_.value(sigDPModel_->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 LauSimpleFitModel::generateSignalEvent() { // Generate signal event Bool_t genOK(kTRUE); Bool_t genSCF(kFALSE); if (this->useDP()) { if (this->enableEmbedding() && signalTree_) { if (useReweighting_) { // Select a (random) event from the generated data. Then store the // reconstructed DP co-ords, together with other pdf information, // as the embedded data. genOK = signalTree_->getReweightedEvent(sigDPModel_); } else { signalTree_->getEmbeddedEvent(kinematics_); } if (signalTree_->haveBranch("mcMatch")) { Int_t match = static_cast(signalTree_->getValue("mcMatch")); if (match) { this->setGenNtupleIntegerBranchValue("genTMSig",1); this->setGenNtupleIntegerBranchValue("genSCFSig",0); genSCF = kFALSE; } else { this->setGenNtupleIntegerBranchValue("genTMSig",0); this->setGenNtupleIntegerBranchValue("genSCFSig",1); genSCF = kTRUE; } } } else { genOK = sigDPModel_->generate(); if ( genOK && useSCF_ ) { Double_t frac(0.0); if ( useSCFHist_ ) { frac = scfFracHist_->calcEfficiency( kinematics_ ); } else { frac = scfFrac_.genValue(); } if ( frac < LauRandom::randomFun()->Rndm() ) { this->setGenNtupleIntegerBranchValue("genTMSig",1); this->setGenNtupleIntegerBranchValue("genSCFSig",0); genSCF = kFALSE; } else { this->setGenNtupleIntegerBranchValue("genTMSig",0); this->setGenNtupleIntegerBranchValue("genSCFSig",1); genSCF = kTRUE; // Optionally smear the DP position // of the SCF event if ( scfMap_ != 0 ) { Double_t xCoord(0.0), yCoord(0.0); if ( kinematics_->squareDP() ) { xCoord = kinematics_->getmPrime(); yCoord = kinematics_->getThetaPrime(); } else { xCoord = kinematics_->getm13Sq(); yCoord = kinematics_->getm23Sq(); } // Find the bin number where this event is generated Int_t binNo = scfMap_->binNumber( xCoord, yCoord ); // Retrieve the migration histogram TH2* histo = scfMap_->trueHist( binNo ); const LauAbsEffModel * effModel = sigDPModel_->getEffModel(); do { // Get a random point from the histogram histo->GetRandom2( xCoord, yCoord ); // Update the kinematics if ( kinematics_->squareDP() ) { kinematics_->updateSqDPKinematics( xCoord, yCoord ); } else { kinematics_->updateKinematics( xCoord, yCoord ); } } while ( ! effModel->passVeto( kinematics_ ) ); } } } } } else { if (this->enableEmbedding() && signalTree_) { signalTree_->getEmbeddedEvent(0); if (signalTree_->haveBranch("mcMatch")) { Int_t match = static_cast(signalTree_->getValue("mcMatch")); if (match) { this->setGenNtupleIntegerBranchValue("genTMSig",1); this->setGenNtupleIntegerBranchValue("genSCFSig",0); genSCF = kFALSE; } else { this->setGenNtupleIntegerBranchValue("genTMSig",0); this->setGenNtupleIntegerBranchValue("genSCFSig",1); genSCF = kTRUE; } } } else if ( useSCF_ ) { Double_t frac = scfFrac_.genValue(); if ( frac < LauRandom::randomFun()->Rndm() ) { this->setGenNtupleIntegerBranchValue("genTMSig",1); this->setGenNtupleIntegerBranchValue("genSCFSig",0); genSCF = kFALSE; } else { this->setGenNtupleIntegerBranchValue("genTMSig",0); this->setGenNtupleIntegerBranchValue("genSCFSig",1); genSCF = kTRUE; } } } if (genOK) { if ( useSCF_ ) { if ( genSCF ) { this->generateExtraPdfValues(&scfPdfs_, signalTree_); } else { this->generateExtraPdfValues(&signalPdfs_, signalTree_); } } else { this->generateExtraPdfValues(&signalPdfs_, signalTree_); } } // Check for problems with the embedding if (this->enableEmbedding() && signalTree_ && (signalTree_->nEvents() == signalTree_->nUsedEvents())) { std::cerr << "WARNING in LauSimpleFitModel::generateSignalEvent : Source of embedded signal events used up, clearing the list of used events." << std::endl; signalTree_->clearUsedList(); } return genOK; } Bool_t LauSimpleFitModel::generateBkgndEvent(UInt_t bkgndID) { // Generate background event Bool_t genOK(kTRUE); LauAbsBkgndDPModel* model = bkgndDPModels_[bkgndID]; LauEmbeddedData* embeddedData(0); if (this->enableEmbedding()) { embeddedData = bkgndTree_[bkgndID]; } LauPdfPList* extraPdfs = &bkgndPdfs_[bkgndID]; if (this->useDP()) { if (embeddedData) { embeddedData->getEmbeddedEvent(kinematics_); } else { if (model == 0) { std::cerr << "ERROR in LauSimpleFitModel::generateBkgndEvent : Can't find the DP model for background class \"" << this->bkgndClassName(bkgndID) << "\"." << 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())) { std::cerr << "WARNING in LauSimpleFitModel::generateBkgndEvent : Source of embedded " << this->bkgndClassName(bkgndID) << " events used up, clearing the list of used events." << std::endl; embeddedData->clearUsedList(); } return genOK; } void LauSimpleFitModel::setupGenNtupleBranches() { // Setup the required ntuple branches this->addGenNtupleDoubleBranch("evtWeight"); this->addGenNtupleIntegerBranch("genSig"); this->addGenNtupleDoubleBranch("efficiency"); if ( useSCF_ || ( this->enableEmbedding() && signalTree_ != 0 && signalTree_->haveBranch("mcMatch") ) ) { this->addGenNtupleIntegerBranch("genTMSig"); this->addGenNtupleIntegerBranch("genSCFSig"); } const UInt_t nBkgnds = this->nBkgndClasses(); for ( UInt_t iBkgnd(0); iBkgnd < nBkgnds; ++iBkgnd ) { TString name( this->bkgndClassName(iBkgnd) ); name.Prepend("gen"); this->addGenNtupleIntegerBranch(name); } if (this->useDP() == kTRUE) { 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 (kinematics_->squareDP()) { this->addGenNtupleDoubleBranch("mPrime"); this->addGenNtupleDoubleBranch("thPrime"); } } for (LauPdfPList::const_iterator pdf_iter = signalPdfs_.begin(); pdf_iter != signalPdfs_.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" ) { this->addGenNtupleDoubleBranch( (*var_iter) ); } } } } void LauSimpleFitModel::setDPBranchValues() { // 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()); } } void LauSimpleFitModel::generateExtraPdfValues(LauPdfPList* extraPdfs, LauEmbeddedData* embeddedData) { // Generate from the extra PDFs if (extraPdfs) { for (LauPdfPList::iterator pdf_iter = extraPdfs->begin(); pdf_iter != extraPdfs->end(); ++pdf_iter) { LauFitData genValues; if (embeddedData) { genValues = embeddedData->getValues( (*pdf_iter)->varNames() ); } else { genValues = (*pdf_iter)->generate(kinematics_); } for ( LauFitData::const_iterator var_iter = genValues.begin(); var_iter != genValues.end(); ++var_iter ) { TString varName = var_iter->first; if ( varName != "m13Sq" && varName != "m23Sq" ) { Double_t value = var_iter->second; this->setGenNtupleDoubleBranchValue(varName,value); } } } } } void LauSimpleFitModel::propagateParUpdates() { // Update the total normalisation for the signal likelihood if (this->useDP() == kTRUE) { this->updateCoeffs(); sigDPModel_->updateCoeffs(coeffs_); } // Update the signal events from the background events if not doing an extended fit if ( !this->doEMLFit() && !signalEvents_->fixed() ) { this->updateSigEvents(); } } void LauSimpleFitModel::updateSigEvents() { // The background parameters will have been set from Minuit. // We need to update the signal events using these. Double_t nTotEvts = this->eventsPerExpt(); signalEvents_->range(-2.0*nTotEvts,2.0*nTotEvts); for (LauBkgndYieldList::iterator iter = bkgndEvents_.begin(); iter != bkgndEvents_.end(); ++iter) { LauAbsRValue* nBkgndEvents = (*iter); if ( nBkgndEvents->isLValue() ) { LauParameter* yield = dynamic_cast( nBkgndEvents ); yield->range(-2.0*nTotEvts,2.0*nTotEvts); } } if ( signalEvents_->fixed() ) { return; } // Subtract background events (if any) from signal. Double_t signalEvents = nTotEvts; if ( usingBkgnd_ == kTRUE ) { for (LauBkgndYieldList::const_iterator iter = bkgndEvents_.begin(); iter != bkgndEvents_.end(); ++iter) { signalEvents -= (*iter)->value(); } } signalEvents_->value(signalEvents); } void LauSimpleFitModel::cacheInputFitVars() { // Fill the internal data trees of the signal and backgrond models. LauFitDataTree* inputFitData = this->fitData(); // First the Dalitz plot variables (m_ij^2) if (this->useDP() == kTRUE) { // need to append SCF smearing bins before caching DP amplitudes if ( scfMap_ != 0 ) { this->appendBinCentres( inputFitData ); } sigDPModel_->fillDataTree(*inputFitData); if (usingBkgnd_ == kTRUE) { for (LauBkgndDPModelList::iterator iter = bkgndDPModels_.begin(); iter != bkgndDPModels_.end(); ++iter) { (*iter)->fillDataTree(*inputFitData); } } } // ...and then the extra PDFs this->cacheInfo(signalPdfs_, *inputFitData); this->cacheInfo(scfPdfs_, *inputFitData); for (LauBkgndPdfsList::iterator iter = bkgndPdfs_.begin(); iter != bkgndPdfs_.end(); ++iter) { this->cacheInfo((*iter), *inputFitData); } // and finally the SCF fractions and jacobians if ( useSCF_ && useSCFHist_ ) { if ( !inputFitData->haveBranch( "m13Sq" ) || !inputFitData->haveBranch( "m23Sq" ) ) { std::cerr << "ERROR in LauSimpleFitModel::cacheInputFitVars : Input data does not contain DP branches and so can't cache the SCF fraction." << std::endl; gSystem->Exit(EXIT_FAILURE); } UInt_t nEvents = inputFitData->nEvents(); recoSCFFracs_.clear(); recoSCFFracs_.reserve( nEvents ); if ( kinematics_->squareDP() ) { recoJacobians_.clear(); recoJacobians_.reserve( nEvents ); } for (UInt_t iEvt = 0; iEvt < nEvents; iEvt++) { const LauFitData& dataValues = inputFitData->getData(iEvt); LauFitData::const_iterator m13_iter = dataValues.find("m13Sq"); LauFitData::const_iterator m23_iter = dataValues.find("m23Sq"); kinematics_->updateKinematics( m13_iter->second, m23_iter->second ); Double_t scfFrac = scfFracHist_->calcEfficiency( kinematics_ ); recoSCFFracs_.push_back( scfFrac ); if ( kinematics_->squareDP() ) { recoJacobians_.push_back( kinematics_->calcSqDPJacobian() ); } } } } void LauSimpleFitModel::appendBinCentres( LauFitDataTree* inputData ) { // We'll be caching the DP amplitudes and efficiencies of the centres of the true bins. // To do so, we attach some fake points at the end of inputData, the number of the entry // minus the total number of events corresponding to the number of the histogram for that // given true bin in the LauScfMap object. (What this means is that when Laura is provided with // the LauScfMap object by the user, it's the latter who has to make sure that it contains the // right number of histograms and in exactly the right order!) // Get the x and y co-ordinates of the bin centres std::vector binCentresXCoords; std::vector binCentresYCoords; scfMap_->listBinCentres(binCentresXCoords, binCentresYCoords); // The SCF histograms could be in square Dalitz plot histograms. // The dynamics takes normal Dalitz plot coords, so we might have to convert them back. Bool_t sqDP = kinematics_->squareDP(); UInt_t nBins = binCentresXCoords.size(); fakeSCFFracs_.clear(); fakeSCFFracs_.reserve( nBins ); if ( sqDP ) { fakeJacobians_.clear(); fakeJacobians_.reserve( nBins ); } for (UInt_t iBin = 0; iBin < nBins; ++iBin) { if ( sqDP ) { kinematics_->updateSqDPKinematics(binCentresXCoords[iBin],binCentresYCoords[iBin]); binCentresXCoords[iBin] = kinematics_->getm13Sq(); binCentresYCoords[iBin] = kinematics_->getm23Sq(); fakeJacobians_.push_back( kinematics_->calcSqDPJacobian() ); } else { kinematics_->updateKinematics(binCentresXCoords[iBin],binCentresYCoords[iBin]); } fakeSCFFracs_.push_back( scfFracHist_->calcEfficiency( kinematics_ ) ); } // Set up inputFitVars_ object to hold the fake events inputData->appendFakePoints(binCentresXCoords,binCentresYCoords); } Double_t LauSimpleFitModel::getTotEvtLikelihood(UInt_t iEvt) { // Get the DP likelihood for signal and backgrounds this->getEvtDPLikelihood(iEvt); // Get the combined extra PDFs likelihood for signal and backgrounds this->getEvtExtraLikelihoods(iEvt); // If appropriate, combine the TM and SCF likelihoods Double_t sigLike = sigDPLike_ * sigExtraLike_; if ( useSCF_ ) { Double_t scfFrac(0.0); if (useSCFHist_) { scfFrac = recoSCFFracs_[iEvt]; } else { scfFrac = scfFrac_.unblindValue(); } sigLike *= (1.0 - scfFrac); if ( (scfMap_ != 0) && (this->useDP() == kTRUE) ) { // if we're smearing the SCF DP PDF then the SCF frac // is already included in the SCF DP likelihood sigLike += (scfDPLike_ * scfExtraLike_); } else { sigLike += (scfFrac * scfDPLike_ * scfExtraLike_); } } // Construct the total event likelihood Double_t likelihood = signalEvents_->unblindValue() * sigLike; const UInt_t nBkgnds = this->nBkgndClasses(); for ( UInt_t bkgndID(0); bkgndID < nBkgnds; ++bkgndID ) { likelihood += (bkgndEvents_[bkgndID]->unblindValue() * bkgndDPLike_[bkgndID] * bkgndExtraLike_[bkgndID]); } return likelihood; } Double_t LauSimpleFitModel::getEventSum() const { Double_t eventSum(0.0); eventSum += signalEvents_->unblindValue(); for (LauBkgndYieldList::const_iterator iter = bkgndEvents_.begin(); iter != bkgndEvents_.end(); ++iter) { eventSum += (*iter)->unblindValue(); } return eventSum; } void LauSimpleFitModel::getEvtDPLikelihood(UInt_t iEvt) { // Function to return the signal and background likelihoods for the // Dalitz plot for the given event evtNo. if (this->useDP() == kTRUE) { sigDPModel_->calcLikelihoodInfo(iEvt); sigDPLike_ = sigDPModel_->getEvtLikelihood(); if ( useSCF_ == kTRUE ) { if ( scfMap_ == 0 ) { // we're not smearing the SCF DP position // so the likelihood is the same as the TM scfDPLike_ = sigDPLike_; } else { // calculate the smeared SCF DP likelihood scfDPLike_ = this->getEvtSCFDPLikelihood(iEvt); } } const UInt_t nBkgnds = this->nBkgndClasses(); for ( UInt_t bkgndID(0); bkgndID < nBkgnds; ++bkgndID ) { if (usingBkgnd_ == kTRUE) { bkgndDPLike_[bkgndID] = bkgndDPModels_[bkgndID]->getLikelihood(iEvt); } else { bkgndDPLike_[bkgndID] = 0.0; } } } else { // There's always going to be a term in the likelihood for the // signal, so we'd better not zero it. sigDPLike_ = 1.0; scfDPLike_ = 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; } } } } Double_t LauSimpleFitModel::getEvtSCFDPLikelihood(UInt_t iEvt) { Double_t scfDPLike(0.0); Double_t recoJacobian(1.0); Double_t xCoord(0.0); Double_t yCoord(0.0); Bool_t squareDP = kinematics_->squareDP(); if ( squareDP ) { xCoord = sigDPModel_->getEvtmPrime(); yCoord = sigDPModel_->getEvtthPrime(); recoJacobian = recoJacobians_[iEvt]; } else { xCoord = sigDPModel_->getEvtm13Sq(); yCoord = sigDPModel_->getEvtm23Sq(); } // Find the bin that our reco event falls in Int_t recoBin = scfMap_->binNumber( xCoord, yCoord ); // Find out which true Bins contribute to the given reco bin const std::vector* trueBins = scfMap_->trueBins(recoBin); Int_t nDataEvents = this->eventsPerExpt(); // Loop over the true bins for (std::vector::const_iterator iter = trueBins->begin(); iter != trueBins->end(); ++iter) { Int_t trueBin = (*iter); // prob of a true event in the given true bin migrating to the reco bin Double_t pRecoGivenTrue = scfMap_->prob( recoBin, trueBin ); // We've cached the DP amplitudes and the efficiency for the // true bin centres, just after the data points sigDPModel_->calcLikelihoodInfo( nDataEvents + trueBin ); Double_t pTrue = sigDPModel_->getEvtLikelihood(); // Get the cached SCF fraction (and jacobian if we're using the square DP) Double_t scfFraction = fakeSCFFracs_[ trueBin ]; Double_t jacobian(1.0); if ( squareDP ) { jacobian = fakeJacobians_[ trueBin ]; } scfDPLike += pTrue * jacobian * scfFraction * pRecoGivenTrue; } // Divide by the reco jacobian scfDPLike /= recoJacobian; return scfDPLike; } void LauSimpleFitModel::getEvtExtraLikelihoods(UInt_t iEvt) { // Function to return the signal and background likelihoods for the // extra variables for the given event evtNo. sigExtraLike_ = 1.0; for (LauPdfPList::iterator iter = signalPdfs_.begin(); iter != signalPdfs_.end(); ++iter) { (*iter)->calcLikelihoodInfo(iEvt); sigExtraLike_ *= (*iter)->getLikelihood(); } if (useSCF_) { scfExtraLike_ = 1.0; for (LauPdfPList::iterator iter = scfPdfs_.begin(); iter != scfPdfs_.end(); ++iter) { (*iter)->calcLikelihoodInfo(iEvt); scfExtraLike_ *= (*iter)->getLikelihood(); } } const UInt_t nBkgnds = this->nBkgndClasses(); for ( UInt_t bkgndID(0); bkgndID < nBkgnds; ++bkgndID ) { if (usingBkgnd_) { bkgndExtraLike_[bkgndID] = 1.0; LauPdfPList& pdfList = bkgndPdfs_[bkgndID]; for (LauPdfPList::iterator pdf_iter = pdfList.begin(); pdf_iter != pdfList.end(); ++pdf_iter) { (*pdf_iter)->calcLikelihoodInfo(iEvt); bkgndExtraLike_[bkgndID] *= (*pdf_iter)->getLikelihood(); } } else { bkgndExtraLike_[bkgndID] = 0.0; } } } void LauSimpleFitModel::updateCoeffs() { coeffs_.clear(); coeffs_.reserve(nSigComp_); for (UInt_t i = 0; i < nSigComp_; i++) { coeffs_.push_back(coeffPars_[i]->particleCoeff()); } } void LauSimpleFitModel::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"); if ( sigDPModel_->usingScfModel() ) { this->addSPlotNtupleDoubleBranch("scffraction"); } } // Store the total event likelihood for each species. if (useSCF_) { this->addSPlotNtupleDoubleBranch("sigTMTotalLike"); this->addSPlotNtupleDoubleBranch("sigSCFTotalLike"); this->addSPlotNtupleDoubleBranch("sigSCFFrac"); } else { 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()) { if (useSCF_) { this->addSPlotNtupleDoubleBranch("sigTMDPLike"); this->addSPlotNtupleDoubleBranch("sigSCFDPLike"); } else { 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 if (useSCF_) { this->addSPlotNtupleBranches(&signalPdfs_, "sigTM"); this->addSPlotNtupleBranches(&scfPdfs_, "sigSCF"); } else { this->addSPlotNtupleBranches(&signalPdfs_, "sig"); } if (usingBkgnd_) { const UInt_t nBkgnds = this->nBkgndClasses(); for ( UInt_t iBkgnd(0); iBkgnd < nBkgnds; ++iBkgnd ) { const TString& bkgndClass = this->bkgndClassName(iBkgnd); const LauPdfPList* pdfList = &(bkgndPdfs_[iBkgnd]); this->addSPlotNtupleBranches(pdfList, bkgndClass); } } } void LauSimpleFitModel::addSPlotNtupleBranches(const LauPdfPList* extraPdfs, const TString& prefix) { if (extraPdfs) { // Loop through each of the PDFs for (LauPdfPList::const_iterator pdf_iter = extraPdfs->begin(); pdf_iter != extraPdfs->end(); ++pdf_iter) { // 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); 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" ) { ++nVars; } } if ( nVars == 1 ) { // If the PDF only has one variable then // simply add one branch for that variable TString varName = (*pdf_iter)->varName(); TString name(prefix); name += 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 ( std::vector::const_iterator var_iter = varNames.begin(); var_iter != varNames.end(); ++var_iter ) { allVars += (*var_iter); TString name(prefix); name += (*var_iter); name += "Like"; this->addSPlotNtupleDoubleBranch(name); } TString name(prefix); name += allVars; name += "Like"; this->addSPlotNtupleDoubleBranch(name); } else { std::cerr << "WARNING in LauSimpleFitModel::addSPlotNtupleBranches : Can't yet deal with 3D PDFs." << std::endl; } } } } Double_t LauSimpleFitModel::setSPlotNtupleBranchValues(LauPdfPList* extraPdfs, const TString& prefix, UInt_t iEvt) { // Store the PDF value for each variable in the list Double_t totalLike(1.0); Double_t extraLike(0.0); if (extraPdfs) { for (LauPdfPList::iterator pdf_iter = extraPdfs->begin(); pdf_iter != extraPdfs->end(); ++pdf_iter) { // calculate the likelihood for this event (*pdf_iter)->calcLikelihoodInfo(iEvt); extraLike = (*pdf_iter)->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); 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" ) { ++nVars; } } if ( nVars == 1 ) { // If the PDF only has one variable then // simply store the value for that variable TString varName = (*pdf_iter)->varName(); TString name(prefix); name += 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 ( std::vector::const_iterator var_iter = varNames.begin(); var_iter != varNames.end(); ++var_iter ) { allVars += (*var_iter); TString name(prefix); name += (*var_iter); name += "Like"; Double_t indivLike = (*pdf_iter)->getLikelihood( (*var_iter) ); this->setSPlotNtupleDoubleBranchValue(name, indivLike); } TString name(prefix); name += allVars; name += "Like"; this->setSPlotNtupleDoubleBranchValue(name, extraLike); } else { std::cerr << "WARNING in LauSimpleFitModel::setSPlotNtupleBranchValues : Can't yet deal with 3D PDFs." << std::endl; } } } return totalLike; } LauSPlot::NameSet LauSimpleFitModel::variableNames() const { LauSPlot::NameSet nameSet; if (this->useDP()) { nameSet.insert("DP"); } // Loop through all the signal PDFs for (LauPdfPList::const_iterator pdf_iter = signalPdfs_.begin(); pdf_iter != signalPdfs_.end(); ++pdf_iter) { // Loop over the variables involved in each PDF std::vector varNames = (*pdf_iter)->varNames(); for ( std::vector::const_iterator var_iter = varNames.begin(); var_iter != varNames.end(); ++var_iter ) { // If they are not DP coordinates then add them if ( (*var_iter) != "m13Sq" && (*var_iter) != "m23Sq" ) { nameSet.insert( (*var_iter) ); } } } return nameSet; } LauSPlot::NumbMap LauSimpleFitModel::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 LauSimpleFitModel::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 LauSimpleFitModel::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 LauSimpleFitModel::twodimPDFs() const { LauSPlot::TwoDMap twodimMap; for (LauPdfPList::const_iterator pdf_iter = signalPdfs_.begin(); pdf_iter != signalPdfs_.end(); ++pdf_iter) { // Count the number of input variables that are not DP variables UInt_t nVars(0); 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" ) { ++nVars; } } if ( nVars == 2 ) { if (useSCF_) { twodimMap.insert( std::make_pair( "sigTM", std::make_pair( varNames[0], varNames[1] ) ) ); } else { twodimMap.insert( std::make_pair( "sig", std::make_pair( varNames[0], varNames[1] ) ) ); } } } if ( useSCF_ ) { for (LauPdfPList::const_iterator pdf_iter = scfPdfs_.begin(); pdf_iter != scfPdfs_.end(); ++pdf_iter) { // Count the number of input variables that are not DP variables UInt_t nVars(0); 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" ) { ++nVars; } } if ( nVars == 2 ) { twodimMap.insert( std::make_pair( "sigSCF", 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); const LauPdfPList& pdfList = bkgndPdfs_[iBkgnd]; for (LauPdfPList::const_iterator pdf_iter = pdfList.begin(); pdf_iter != pdfList.end(); ++pdf_iter) { // Count the number of input variables that are not DP variables UInt_t nVars(0); 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" ) { ++nVars; } } if ( nVars == 2 ) { twodimMap.insert( std::make_pair( bkgndClass, std::make_pair( varNames[0], varNames[1] ) ) ); } } } } return twodimMap; } void LauSimpleFitModel::storePerEvtLlhds() { std::cout << "INFO in LauSimpleFitModel::storePerEvtLlhds : Storing per-event likelihood values..." << std::endl; // 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 LauFitDataTree* inputFitData = this->fitData(); if (!this->useDP() && this->storeDPEff()) { sigDPModel_->initialise(coeffs_); sigDPModel_->fillDataTree(*inputFitData); } UInt_t evtsPerExpt(this->eventsPerExpt()); for (UInt_t iEvt = 0; iEvt < evtsPerExpt; ++iEvt) { this->setSPlotNtupleIntegerBranchValue("iExpt",this->iExpt()); this->setSPlotNtupleIntegerBranchValue("iEvtWithinExpt",iEvt); // the DP information this->getEvtDPLikelihood(iEvt); if (this->storeDPEff()) { if (!this->useDP()) { sigDPModel_->calcLikelihoodInfo(iEvt); } this->setSPlotNtupleDoubleBranchValue("efficiency",sigDPModel_->getEvtEff()); if ( sigDPModel_->usingScfModel() ) { this->setSPlotNtupleDoubleBranchValue("scffraction",sigDPModel_->getEvtScfFraction()); } } if (this->useDP()) { sigTotalLike_ = sigDPLike_; if (useSCF_) { scfTotalLike_ = scfDPLike_; this->setSPlotNtupleDoubleBranchValue("sigTMDPLike",sigDPLike_); this->setSPlotNtupleDoubleBranchValue("sigSCFDPLike",scfDPLike_); } else { 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; if (useSCF_) { scfTotalLike_ = 1.0; } if (usingBkgnd_) { const UInt_t nBkgnds = this->nBkgndClasses(); for ( UInt_t iBkgnd(0); iBkgnd < nBkgnds; ++iBkgnd ) { bkgndTotalLike_[iBkgnd] = 1.0; } } } // the signal PDF values if ( useSCF_ ) { sigTotalLike_ *= this->setSPlotNtupleBranchValues(&signalPdfs_, "sigTM", iEvt); scfTotalLike_ *= this->setSPlotNtupleBranchValues(&scfPdfs_, "sigSCF", iEvt); } else { sigTotalLike_ *= this->setSPlotNtupleBranchValues(&signalPdfs_, "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 if (useSCF_) { Double_t scfFrac(0.0); if ( useSCFHist_ ) { scfFrac = recoSCFFracs_[iEvt]; } else { scfFrac = scfFrac_.unblindValue(); } this->setSPlotNtupleDoubleBranchValue("sigSCFFrac",scfFrac); sigTotalLike_ *= ( 1.0 - scfFrac ); if ( scfMap_ == 0 ) { scfTotalLike_ *= scfFrac; } this->setSPlotNtupleDoubleBranchValue("sigTMTotalLike",sigTotalLike_); this->setSPlotNtupleDoubleBranchValue("sigSCFTotalLike",scfTotalLike_); } else { 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 LauSimpleFitModel::storePerEvtLlhds : Finished storing per-event likelihood values." << std::endl; } void LauSimpleFitModel::embedSignal(const TString& fileName, const TString& treeName, Bool_t reuseEventsWithinEnsemble, Bool_t reuseEventsWithinExperiment, Bool_t useReweighting) { if (signalTree_) { std::cerr << "ERROR in LauSimpleFitModel::embedSignal : Already embedding signal from a file." << std::endl; return; } signalTree_ = new LauEmbeddedData(fileName,treeName,reuseEventsWithinExperiment); Bool_t dataOK = signalTree_->findBranches(); if (!dataOK) { delete signalTree_; signalTree_ = 0; std::cerr << "ERROR in LauSimpleFitModel::embedSignal : Problem creating data tree for embedding." << std::endl; return; } reuseSignal_ = reuseEventsWithinEnsemble; useReweighting_ = useReweighting; if (this->enableEmbedding() == kFALSE) { this->enableEmbedding(kTRUE); } } void LauSimpleFitModel::embedBkgnd(const TString& bkgndClass, const TString& fileName, const TString& treeName, Bool_t reuseEventsWithinEnsemble, Bool_t reuseEventsWithinExperiment) { 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 ); if (bkgndTree_[bkgndID]) { std::cerr << "ERROR in LauSimpleFitModel::embedBkgnd : Already embedding background from a file." << std::endl; return; } bkgndTree_[bkgndID] = new LauEmbeddedData(fileName,treeName,reuseEventsWithinExperiment); Bool_t dataOK = bkgndTree_[bkgndID]->findBranches(); if (!dataOK) { delete bkgndTree_[bkgndID]; bkgndTree_[bkgndID] = 0; std::cerr << "ERROR in LauSimpleFitModel::embedBkgnd : Problem creating data tree for embedding." << std::endl; return; } reuseBkgnd_[bkgndID] = reuseEventsWithinEnsemble; if (this->enableEmbedding() == kFALSE) { this->enableEmbedding(kTRUE); } } void LauSimpleFitModel::weightEvents( const TString& dataFileName, const TString& dataTreeName ) { // Routine to provide weights for events that are uniformly distributed // in the DP (or square DP) so as to reproduce the given DP model if ( kinematics_->squareDP() ) { std::cout << "INFO in LauSimpleFitModel::weightEvents : will create weights assuming events were generated flat in the square DP" << std::endl; } else { std::cout << "INFO in LauSimpleFitModel::weightEvents : will create weights assuming events were generated flat in phase space" << std::endl; } // This reads in the given dataFile and creates an input // fit data tree that stores them for all events and experiments. Bool_t dataOK = this->verifyFitData(dataFileName,dataTreeName); if (!dataOK) { std::cerr << "ERROR in LauSimpleFitModel::weightEvents : Problem caching the data." << std::endl; return; } LauFitDataTree* inputFitData = this->fitData(); if ( ! inputFitData->haveBranch( "m13Sq_MC" ) || ! inputFitData->haveBranch( "m23Sq_MC" ) ) { std::cerr << "WARNING in LauSimpleFitModel::weightEvents : Cannot find MC truth DP coordinate branches in supplied data, aborting." << std::endl; return; } // Create the ntuple to hold the DP weights TString weightsFileName( dataFileName ); Ssiz_t index = weightsFileName.Last('.'); weightsFileName.Insert( index, "_DPweights" ); LauGenNtuple * weightsTuple = new LauGenNtuple( weightsFileName, dataTreeName ); weightsTuple->addIntegerBranch("iExpt"); weightsTuple->addIntegerBranch("iEvtWithinExpt"); weightsTuple->addDoubleBranch("dpModelWeight"); UInt_t nExpmt = this->nExpt(); UInt_t firstExpmt = this->firstExpt(); for (UInt_t iExpmt = firstExpmt; iExpmt < (firstExpmt+nExpmt); ++iExpmt) { inputFitData->readExperimentData(iExpmt); UInt_t nEvents = inputFitData->nEvents(); if (nEvents < 1) { std::cerr << "WARNING in LauSimpleFitModel::weightEvents : Zero events in experiment " << iExpmt << ", skipping..." << std::endl; continue; } weightsTuple->setIntegerBranchValue( "iExpt", iExpmt ); // Calculate and store the weights for the events in this experiment for ( UInt_t iEvent(0); iEvent < nEvents; ++iEvent ) { weightsTuple->setIntegerBranchValue( "iEvtWithinExpt", iEvent ); const LauFitData& evtData = inputFitData->getData( iEvent ); Double_t m13Sq_MC = evtData.find("m13Sq_MC")->second; Double_t m23Sq_MC = evtData.find("m23Sq_MC")->second; Double_t dpModelWeight(0.0); if ( kinematics_->withinDPLimits( m13Sq_MC, m23Sq_MC ) ) { kinematics_->updateKinematics( m13Sq_MC, m23Sq_MC ); dpModelWeight = sigDPModel_->getEventWeight(); if ( kinematics_->squareDP() ) { dpModelWeight *= kinematics_->calcSqDPJacobian(); } dpModelWeight /= sigDPModel_->getDPNorm(); } weightsTuple->setDoubleBranchValue( "dpModelWeight", dpModelWeight ); weightsTuple->fillBranches(); } } weightsTuple->buildIndex( "iExpt", "iEvtWithinExpt" ); weightsTuple->addFriendTree(dataFileName, dataTreeName); weightsTuple->writeOutGenResults(); delete weightsTuple; } void LauSimpleFitModel::savePDFPlots(const TString& label) { savePDFPlotsWave(label, 0); savePDFPlotsWave(label, 1); savePDFPlotsWave(label, 2); std::cout << "LauCPFitModel::plot" << std::endl; // ((LauIsobarDynamics*)sigDPModel_)->plot(); //Double_t minm13 = sigDPModel_->getKinematics()->getm13Min(); Double_t minm13 = 0.0; Double_t maxm13 = sigDPModel_->getKinematics()->getm13Max(); //Double_t minm23 = sigDPModel_->getKinematics()->getm23Min(); Double_t minm23 = 0.0; Double_t maxm23 = sigDPModel_->getKinematics()->getm23Max(); Double_t mins13 = minm13*minm13; Double_t maxs13 = maxm13*maxm13; Double_t mins23 = minm23*minm23; Double_t maxs23 = maxm23*maxm23; Double_t s13, s23, chPdf; Int_t n13=200.00, n23=200.00; Double_t delta13, delta23; delta13 = (maxs13 - mins13)/n13; delta23 = (maxs23 - mins23)/n23; UInt_t nAmp = sigDPModel_->getnCohAmp(); for (UInt_t resID = 0; resID <= nAmp; ++resID) { TGraph2D *dt = new TGraph2D(); TString resName = "TotalAmp"; if (resID != nAmp){ TString tStrResID = Form("%d", resID); const LauIsobarDynamics* model = sigDPModel_; const LauAbsResonance* resonance = model->getResonance(resID); resName = resonance->getResonanceName(); std::cout << "resName = " << resName << std::endl; } resName.ReplaceAll("(", ""); resName.ReplaceAll(")", ""); resName.ReplaceAll("*", "Star"); TCanvas *c = new TCanvas("c"+resName+label,resName+" ("+label+")",0,0,600,400); dt->SetName(resName+label); dt->SetTitle(resName+" ("+label+")"); Int_t count=0; for (Int_t i=0; igetKinematics()->withinDPLimits2(s23, s13)) { //if (s13 > 4) continue; sigDPModel_->calcLikelihoodInfo(s13, s23); LauComplex chAmp = sigDPModel_->getEvtDPAmp(); if (resID != nAmp){ chAmp = sigDPModel_->getFullAmplitude(resID); } chPdf = chAmp.abs2(); //if ((z > 0.04)||(z < -0.03)) continue; //z = TMath::Log(z); if (sigDPModel_->getDaughters()->gotSymmetricalDP()){ Double_t sLow = s13; Double_t sHigh = s23; if (sLow>sHigh) { continue; //sLow = s23; //sHigh = s13; } //if (sLow > 3.5) continue; //if (i<10) std::cout << "SymmetricalDP" << std::endl; //if (z>0.02) z = 0.02; //if (z<-0.02) z = -0.02; dt->SetPoint(count,sHigh,sLow,chPdf); count++; } else { dt->SetPoint(count,s13,s23,chPdf); count++; } } } } gStyle->SetPalette(1); dt->GetXaxis()->SetTitle("m_{K#pi}(low)"); dt->GetYaxis()->SetTitle("m_{K#pi}(high)"); dt->Draw("SURF1"); dt->GetXaxis()->SetTitle("m_{K#pi}(low)"); dt->GetYaxis()->SetTitle("m_{K#pi}(high)"); c->SaveAs("plot_2D_"+resName + "_"+label+".C"); } } void LauSimpleFitModel::savePDFPlotsWave(const TString& label, const Int_t& spin) { std::cout << "label = "<< label << ", spin = "<< spin << std::endl; TString tStrResID = "S_Wave"; if (spin == 1) tStrResID = "P_Wave"; if (spin == 2) tStrResID = "D_Wave"; std::cout << "LauSimpleFitModel::savePDFPlotsWave: "<< tStrResID << std::endl; TCanvas *c = new TCanvas("c"+tStrResID+label,tStrResID+" ("+label+")",0,0,600,400); Double_t minm13 = 0.0; Double_t maxm13 = sigDPModel_->getKinematics()->getm13Max(); Double_t minm23 = 0.0; Double_t maxm23 = sigDPModel_->getKinematics()->getm23Max(); Double_t mins13 = minm13*minm13; Double_t maxs13 = maxm13*maxm13; Double_t mins23 = minm23*minm23; Double_t maxs23 = maxm23*maxm23; Double_t s13, s23, chPdf; TGraph2D *dt = new TGraph2D(); dt->SetName(tStrResID+label); dt->SetTitle(tStrResID+" ("+label+")"); Int_t n13=200.00, n23=200.00; Double_t delta13, delta23; delta13 = (maxs13 - mins13)/n13; delta23 = (maxs23 - mins23)/n23; UInt_t nAmp = sigDPModel_->getnCohAmp(); Int_t count=0; for (Int_t i=0; igetKinematics()->withinDPLimits2(s23, s13)) { //if (s13 > 4) continue; LauComplex chAmp(0,0); Bool_t noWaveRes = kTRUE; sigDPModel_->calcLikelihoodInfo(s13, s23); for (UInt_t resID = 0; resID < nAmp; ++resID) { const LauIsobarDynamics* model = sigDPModel_; const LauAbsResonance* resonance = model->getResonance(resID); Int_t spin_res = resonance->getSpin(); if (spin != spin_res) continue; noWaveRes = kFALSE; chAmp += sigDPModel_->getFullAmplitude(resID); } if (noWaveRes) return; chPdf = chAmp.abs2(); if (sigDPModel_->getDaughters()->gotSymmetricalDP()){ Double_t sLow = s13; Double_t sHigh = s23; if (sLow>sHigh) { continue; //sLow = s23; //sHigh = s13; } dt->SetPoint(count,sHigh,sLow,chPdf); count++; } else { dt->SetPoint(count,s13,s23,chPdf); count++; } } } } gStyle->SetPalette(1); dt->GetXaxis()->SetTitle("pipi"); dt->GetYaxis()->SetTitle("pipi"); dt->Draw("SURF1"); dt->GetXaxis()->SetTitle("pipi"); dt->GetYaxis()->SetTitle("pipi"); c->SaveAs("plot_2D_"+tStrResID+"_"+label+".C"); } diff --git a/src/LauTimeDepFitModel.cc b/src/LauTimeDepFitModel.cc index f8a36ca..b11244b 100644 --- a/src/LauTimeDepFitModel.cc +++ b/src/LauTimeDepFitModel.cc @@ -1,3312 +1,3312 @@ /* 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 #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), -2.0, 2.0, kFALSE), cosPhiMix_("cosPhiMix", TMath::Cos(2.0*LauConstants::beta), -2.0, 2.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; TString yieldName = signalEvents_->name(); if ( ! yieldName.BeginsWith("signalEvents") ) { std::cerr << "ERROR in LauTimeDepFitModel::setNSigEvents : The signal yield parameter name should start with \"signalEvents\" (plus any optional suffix)." << std::endl; gSystem->Exit(EXIT_FAILURE); } Double_t value = nSigEvents->value(); signalEvents_->range(-2.0*(TMath::Abs(value)+1.0),2.0*(TMath::Abs(value)+1.0)); TString asymName = yieldName; asymName.ReplaceAll( "Events", "Asym" ); signalAsym_ = new LauParameter(asymName,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; TString yieldName = signalEvents_->name(); if ( ! yieldName.BeginsWith("signalEvents") ) { std::cerr << "ERROR in LauTimeDepFitModel::setNSigEvents : The signal yield parameter name should start with \"signalEvents\" (plus any optional suffix)." << std::endl; gSystem->Exit(EXIT_FAILURE); } Double_t value = nSigEvents->value(); signalEvents_->range(-2.0*(TMath::Abs(value)+1.0), 2.0*(TMath::Abs(value)+1.0)); signalAsym_ = sigAsym; TString asymName = yieldName; asymName.ReplaceAll( "Events", "Asym" ); signalAsym_->name(asymName); 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); } TString yieldName = nBkgndEvents->name(); TString bkgndClassName = yieldName; if ( bkgndClassName.Contains("Events") ) { bkgndClassName.Remove( bkgndClassName.Index("Events") ); } else { yieldName += "Events"; nBkgndEvents->name( yieldName ); } if ( ! this->validBkgndClass( bkgndClassName ) ) { std::cerr << "ERROR in LauTimeDepFitModel::setNBkgndEvents : Invalid background class \"" << bkgndClassName << "\"." << 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( bkgndClassName ); 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; } 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; TString asymName = yieldName; asymName.ReplaceAll( "Events", "Asym" ); bkgndAsym_[bkgndID] = new LauParameter(asymName,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); } TString yieldName = nBkgndEvents->name(); TString bkgndClassName = yieldName; if ( bkgndClassName.Contains("Events") ) { bkgndClassName.Remove( bkgndClassName.Index("Events") ); } else { yieldName += "Events"; nBkgndEvents->name( yieldName ); } TString asymName = yieldName; asymName.ReplaceAll( "Events", "Asym" ); bkgndAsym->name( asymName ); if ( ! this->validBkgndClass( bkgndClassName ) ) { std::cerr << "ERROR in LauTimeDepFitModel::setNBkgndEvents : Invalid background class \"" << bkgndClassName << "\"." << 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( bkgndClassName ); 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; } 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; 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::blindPhiMix(const TString& blindingString, const Double_t width, const Bool_t flipSign) { phiMix_.range( -2.0*LauConstants::threePi, 2.0*LauConstants::threePi ); phiMix_.blindParameter( blindingString, width, flipSign ); } void LauTimeDepFitModel::blindPhiMix(const TString& sinBlindingString, const TString& cosBlindingString, const Double_t width, const Bool_t flipSign) { if ( ! useSinCos_ ) { std::cerr << "WARNING in LauTimeDepFitModel::blindPhiMix : not using sine/cosine parameters, so using the sine blinding string to blind the phase itself." << std::endl; this->blindPhiMix(sinBlindingString); return; } sinPhiMix_.range( -3.0, 3.0 ); cosPhiMix_.range( -3.0, 3.0 ); sinPhiMix_.blindParameter( sinBlindingString, width, flipSign ); cosPhiMix_.blindParameter( cosBlindingString, width, flipSign ); } 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(std::unique_ptr coeffSet) { // Resize the coeffPars vector if not already done if ( coeffPars_.empty() ) { const UInt_t nAmpB0bar { sigModelB0bar_->getnTotAmp() }; const UInt_t nAmpB0 { sigModelB0_->getnTotAmp() }; if ( nAmpB0bar != nAmpB0 ) { std::cerr << "ERROR in LauTimeDepFitModel::setAmpCoeffSet : Unequal number of signal DP components in the B and Bbar models: " << nAmpB0 << " != " << nAmpB0bar << std::endl; gSystem->Exit(EXIT_FAILURE); } coeffPars_.resize( nAmpB0 ); fitFracAsymm_.resize( nAmpB0 ); acp_.resize( nAmpB0 ); } // 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 ); } Int_t indexB0bar { sigModelB0bar_->resonanceIndex(compName) }; Int_t indexB0 { -1 }; if ( conjugate ) { if ( ! sigModelB0_->hasResonance(conjName) ) { std::cerr<<"ERROR in LauTimeDepFitModel::setAmpCoeffSet : B0 signal DP model doesn't contain component \""<resonanceIndex(conjName); } else { if ( ! sigModelB0_->hasResonance(compName) ) { std::cerr<<"ERROR in LauTimeDepFitModel::setAmpCoeffSet : B0 signal DP model doesn't contain component \""<resonanceIndex(compName); } if ( indexB0 != indexB0bar ) { std::cerr << "ERROR in LauTimeDepFitModel::setAmpCoeffSet : B0 signal DP model and B0bar signal DP model have different indices for component \"" << compName << "\"." << std::endl; return; } // Do we already have it in our list of names? if ( coeffPars_[indexB0] != nullptr && coeffPars_[indexB0]->name() == compName) { std::cerr<<"ERROR in LauTimeDepFitModel::setAmpCoeffSet : Have already set coefficients for \""<index(indexB0); std::cout<<"INFO in LauTimeDepFitModel::setAmpCoeffSet : Added coefficients for component \""<printParValues(); const TString parName { coeffSet->baseName() + "FitFracAsym" }; fitFracAsymm_[indexB0] = LauParameter{parName, 0.0, -1.0, 1.0}; acp_[indexB0] = coeffSet->acp(); coeffPars_[indexB0] = std::move(coeffSet); ++nSigComp_; } void LauTimeDepFitModel::calcAsymmetries(Bool_t initValues) { // Calculate the CP asymmetries // Also calculate the fit fraction asymmetries for (UInt_t i = 0; i < nSigComp_; i++) { acp_[i] = coeffPars_[i]->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()); } 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_, sendFixedYieldsToFitter_ ); } 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_, sendFixedYieldsToFitter_ ); 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 ); auto t1 = std::chrono::high_resolution_clock::now(); 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 "< ms_double = ( t2 - t1 )/nEvtsGen; std::cout<<"INFO in LauTimeDepFitModel::genExpt : Average per-event generation time for "<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; } 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(); kinematics = kinematicsB0_; } } else { // mark that the decay flavour is unknown curEvtDecayFlv_ = LauFlavTag::Flavour::Unknown; // generate the DP position BkgndDPModelsB_[bkgndID]->generate(); kinematics = kinematicsB0_; } // 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 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 }; // 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; } //Debug ASumSqMax huge size w.r.t. ASumSq for SDPs //std::cout<<"ASq "<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) // TODO - need to detect CP-eigenstate and two histos case in initialisation and abort since it doesn't make any sense 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 { // No detection asymmetry (could be QFS or CP-eigenstate - which implies slightly different normalisation) bkgndDPLike_[bkgndID] = BkgndDPModelsB_[bkgndID]->getLikelihood(iEvt); if ( cpEigenValue_ == QFS ) { bkgndDPLike_[bkgndID] *= 0.5; } } // ...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."<printPdfValues( sigExtraPdf_, " Signal" ); // Print the background information if ( usingBkgnd_ ) { const UInt_t nBkgnds = this->nBkgndClasses(); for ( UInt_t bkgndID(0); bkgndID < nBkgnds; ++bkgndID ) { const TString& bkgndName { this->bkgndClassName( bkgndID ) }; std::cerr << " " << bkgndName << " DP+t likelihood = " << bkgndDPLike_[bkgndID] << "\n"; /* TODO - not general so won't leave in - can we easily generalise? if ( bkgndName == "comb" ) { std::cerr << " comb DP likelihood = " << BkgndDPModelsB_[bkgndID]->getUnNormValue() / BkgndDPModelsB_[bkgndID]->getPdfNorm() << "\n"; std::cerr << " comb t likelihood = " << BkgndDecayTimePdfs_[bkgndID]->getHistTerm() << "\n"; std::cerr << " comb FT likelihood = " << flavTag_->getCapitalOmegaBkgnd(bkgndID, 0, LauFlavTag::Flavour::B, curEvtDecayFlv_) << "\n"; } */ this->printPdfValues( BkgndPdfs_[bkgndID], " "+bkgndName ); } } } diff --git a/src/LauTimeDepFlavModel.cc b/src/LauTimeDepFlavModel.cc index 85ea155..dec0dbf 100644 --- a/src/LauTimeDepFlavModel.cc +++ b/src/LauTimeDepFlavModel.cc @@ -1,2247 +1,2247 @@ /* Copyright 2015 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 LauTimeDepFlavModel.cc \brief File containing implementation of LauTimeDepFlavModel class. */ #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 "LauPrint.hh" #include "LauRandom.hh" #include "LauScfMap.hh" #include "LauTimeDepFlavModel.hh" ClassImp(LauTimeDepFlavModel) LauTimeDepFlavModel::LauTimeDepFlavModel(LauIsobarDynamics* modelB0bar, LauIsobarDynamics* modelB0, const Bool_t useUntaggedEvents, const TString& tagVarName, const TString& tagCatVarName) : LauAbsFitModel(), sigModelB0bar_(modelB0bar), sigModelB0_(modelB0), kinematicsB0bar_(modelB0bar ? modelB0bar->getKinematics() : 0), kinematicsB0_(modelB0 ? modelB0->getKinematics() : 0), useUntaggedEvents_(useUntaggedEvents), nSigComp_(0), nSigDPPar_(0), nDecayTimePar_(0), nExtraPdfPar_(0), nNormPar_(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), signalTagCatFrac_(), tagVarName_(tagVarName), tagCatVarName_(tagCatVarName), cpevVarName_(""), validTagCats_(), curEvtTagFlv_(0), curEvtTagCat_(0), cpEigenValue_(CPEven), evtTagFlvVals_(0), evtTagCatVals_(0), evtCPEigenVals_(0), dilution_(), deltaDilution_(), //deltaM_("deltaM",LauConstants::deltaMd), 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), -3.0, 3.0, kFALSE), cosPhiMix_("cosPhiMix", TMath::Cos(2.0*LauConstants::beta), -3.0, 3.0, kFALSE), useSinCos_(kFALSE), phiMixComplex_(TMath::Cos(-2.0*LauConstants::beta),TMath::Sin(-2.0*LauConstants::beta)), signalDecayTimePdfs_(), curEvtDecayTime_(0.0), curEvtDecayTimeErr_(0.0), sigExtraPdf_(), iterationsMax_(500000), 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) { // Add the untagged category as a valid category this->addValidTagCat(0); // Set the fraction, average dilution and dilution difference for the untagged category this->setSignalTagCatPars(0, 1.0, 0.0, 0.0, kTRUE); } LauTimeDepFlavModel::~LauTimeDepFlavModel() { // TODO - need to delete the various embedded data structures here } void LauTimeDepFlavModel::setupBkgndVectors() { } void LauTimeDepFlavModel::setNSigEvents(LauParameter* nSigEvents) { if ( nSigEvents == 0 ) { std::cerr << "ERROR in LauTimeDepFlavModel::setNSigEvents : The LauParameter pointer is null." << std::endl; gSystem->Exit(EXIT_FAILURE); } if ( signalEvents_ != 0 ) { std::cerr << "ERROR in LauTimeDepFlavModel::setNSigEvents : You are trying to overwrite the signal yield." << std::endl; return; } if ( signalAsym_ != 0 ) { std::cerr << "ERROR in LauTimeDepFlavModel::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 LauTimeDepFlavModel::setNSigEvents(LauParameter* nSigEvents, LauParameter* sigAsym) { if ( nSigEvents == 0 ) { std::cerr << "ERROR in LauTimeDepFlavModel::setNSigEvents : The event LauParameter pointer is null." << std::endl; gSystem->Exit(EXIT_FAILURE); } if ( sigAsym == 0 ) { std::cerr << "ERROR in LauTimeDepFlavModel::setNSigEvents : The asym LauParameter pointer is null." << std::endl; gSystem->Exit(EXIT_FAILURE); } if ( signalEvents_ != 0 ) { std::cerr << "ERROR in LauTimeDepFlavModel::setNSigEvents : You are trying to overwrite the signal yield." << std::endl; return; } if ( signalAsym_ != 0 ) { std::cerr << "ERROR in LauTimeDepFlavModel::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 LauTimeDepFlavModel::setNBkgndEvents(LauAbsRValue* /*nBkgndEvents*/) { std::cerr << "WARNING in LauTimeDepFlavModel::setNBkgndEvents : This model does not yet support backgrounds" << std::endl; } void LauTimeDepFlavModel::addValidTagCats(const std::vector& tagCats) { for (std::vector::const_iterator iter = tagCats.begin(); iter != tagCats.end(); ++iter) { this->addValidTagCat(*iter); } } void LauTimeDepFlavModel::addValidTagCat(Int_t tagCat) { validTagCats_.insert(tagCat); } void LauTimeDepFlavModel::setSignalTagCatPars(const Int_t tagCat, const Double_t tagCatFrac, const Double_t dilution, const Double_t deltaDilution, const Bool_t fixTCFrac) { if (!this->validTagCat(tagCat)) { std::cerr<<"ERROR in LauTimeDepFlavModel::setSignalTagCatPars : Tagging category \""<checkSignalTagCatFractions(); only when the user has //set them all up, in this->initialise(); } void LauTimeDepFlavModel::checkSignalTagCatFractions() { Double_t totalTaggedFrac(0.0); for (LauTagCatParamMap::const_iterator iter=signalTagCatFrac_.begin(); iter!=signalTagCatFrac_.end(); ++iter) { if (iter->first != 0) { const LauParameter& par = iter->second; totalTaggedFrac += par.value(); } } if ( ((totalTaggedFrac < (1.0-1.0e-8))&&!useUntaggedEvents_) || (totalTaggedFrac > (1.0+1.0e-8)) ) { std::cerr<<"WARNING in LauTimeDepFlavModel::checkSignalTagCatFractions : Tagging category fractions add up to "<second; Double_t newVal = par.value() / totalTaggedFrac; par.value(newVal); par.initValue(newVal); par.genValue(newVal); } } else if (useUntaggedEvents_) { Double_t tagCatFrac = 1.0 - totalTaggedFrac; TString tagCatFracName("signalTagCatFrac0"); signalTagCatFrac_[0].name(tagCatFracName); signalTagCatFrac_[0].range(0.0,1.0); signalTagCatFrac_[0].value(tagCatFrac); signalTagCatFrac_[0].initValue(tagCatFrac); signalTagCatFrac_[0].genValue(tagCatFrac); signalTagCatFrac_[0].fixed(kTRUE); TString dilutionName("dilution0"); dilution_[0].name(dilutionName); dilution_[0].range(0.0,1.0); dilution_[0].value(0.0); dilution_[0].initValue(0.0); dilution_[0].genValue(0.0); TString deltaDilutionName("deltaDilution0"); deltaDilution_[0].name(deltaDilutionName); deltaDilution_[0].range(-2.0,2.0); deltaDilution_[0].value(0.0); deltaDilution_[0].initValue(0.0); deltaDilution_[0].genValue(0.0); } for (LauTagCatParamMap::const_iterator iter=dilution_.begin(); iter!=dilution_.end(); ++iter) { - std::cout<<"INFO in LauTimeDepFlavModel::checkSignalTagCatFractions : Setting dilution for tagging category "<<(*iter).first<<" to "<<(*iter).second<validTagCat(tagCat)) { std::cerr<<"ERROR in LauTimeDepFlavModel::setSignalDtPdf : Tagging category \""<validTagCat(tagCat)) { std::cerr<<"ERROR in LauTimeDepFlavModel::setSignalPdfs : Tagging category \""<updateCoeffs(); // Initialisation if (this->useDP() == kTRUE) { this->initialiseDPModels(); } if (!this->useDP() && sigExtraPdf_.empty()) { std::cerr<<"ERROR in LauTimeDepFlavModel::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 LauTimeDepFlavModel::initialise : the pointer to one (particle or anti-particle) of the signal DP models is null."<Exit(EXIT_FAILURE); } } // Check here that the tagging category fractions add up to 1, otherwise "normalise". Also set up the untagged cat. // NB this has to be done early in the initialization as other methods access the tagCats map. this->checkSignalTagCatFractions(); // 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(); // Check that we have the expected number of fit variables const LauParameterPList& fitVars = this->fitPars(); if (fitVars.size() != (nSigDPPar_ + nDecayTimePar_ + nExtraPdfPar_ + nNormPar_)) { std::cerr<<"ERROR in LauTimeDepFlavModel::initialise : Number of fit parameters not of expected size."<Exit(EXIT_FAILURE); } this->setExtraNtupleVars(); } void LauTimeDepFlavModel::recalculateNormalisation() { sigModelB0bar_->recalculateNormalisation(); sigModelB0_->recalculateNormalisation(); sigModelB0bar_->modifyDataTree(); sigModelB0_->modifyDataTree(); this->calcInterferenceTermIntegrals(); } void LauTimeDepFlavModel::initialiseDPModels() { if (sigModelB0bar_ == 0) { std::cerr<<"ERROR in LauTimeDepFlavModel::initialiseDPModels : B0bar signal DP model doesn't exist"<Exit(EXIT_FAILURE); } if (sigModelB0_ == 0) { std::cerr<<"ERROR in LauTimeDepFlavModel::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_->getnAmp(); //const UInt_t nAmpB0 = sigModelB0_->getnAmp(); const UInt_t nAmpB0bar = sigModelB0bar_->getnTotAmp(); const UInt_t nAmpB0 = sigModelB0_->getnTotAmp(); if ( nAmpB0bar != nAmpB0 ) { std::cerr << "ERROR in LauTimeDepFlavModel::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 LauTimeDepFlavModel::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 LauTimeDepFlavModel::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->calcInterTermNorm(); } void LauTimeDepFlavModel::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 LauTimeDepFlavModel::calcInterTermNorm() { 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 LauTimeDepFlavModel::setAmpCoeffSet(std::unique_ptr coeffSet) { // Resize the coeffPars vector if not already done if ( coeffPars_.empty() ) { const UInt_t nAmpB0bar { sigModelB0bar_->getnTotAmp() }; const UInt_t nAmpB0 { sigModelB0_->getnTotAmp() }; if ( nAmpB0bar != nAmpB0 ) { std::cerr << "ERROR in LauTimeDepFlavModel::setAmpCoeffSet : Unequal number of signal DP components in the B and Bbar models: " << nAmpB0 << " != " << nAmpB0bar << std::endl; gSystem->Exit(EXIT_FAILURE); } coeffPars_.resize( nAmpB0 ); fitFracAsymm_.resize( nAmpB0 ); acp_.resize( nAmpB0 ); } // 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 LauTimeDepFlavModel::setAmpCoeffSet : B0bar signal DP model doesn't contain component \""<name( compName ); } Int_t indexB0bar { sigModelB0bar_->resonanceIndex(compName) }; Int_t indexB0 { -1 }; if ( conjugate ) { if ( ! sigModelB0_->hasResonance(conjName) ) { std::cerr<<"ERROR in LauTimeDepFlavModel::setAmpCoeffSet : B0 signal DP model doesn't contain component \""<resonanceIndex(conjName); } else { if ( ! sigModelB0_->hasResonance(compName) ) { std::cerr<<"ERROR in LauTimeDepFlavModel::setAmpCoeffSet : B0 signal DP model doesn't contain component \""<resonanceIndex(compName); } if ( indexB0 != indexB0bar ) { std::cerr << "ERROR in LauTimeDepFlavModel::setAmpCoeffSet : B0 signal DP model and B0bar signal DP model have different indices for component \"" << compName << "\"." << std::endl; return; } // Do we already have it in our list of names? if ( coeffPars_[indexB0] != nullptr && coeffPars_[indexB0]->name() == compName) { std::cerr<<"ERROR in LauTimeDepFlavModel::setAmpCoeffSet : Have already set coefficients for \""<index(indexB0); std::cout<<"INFO in LauTimeDepFlavModel::setAmpCoeffSet : Added coefficients for component \""<printParValues(); const TString parName { coeffSet->baseName() + "FitFracAsym" }; fitFracAsymm_[indexB0] = LauParameter{parName, 0.0, -1.0, 1.0}; acp_[indexB0] = coeffSet->acp(); coeffPars_[indexB0] = std::move(coeffSet); ++nSigComp_; } void LauTimeDepFlavModel::calcAsymmetries(Bool_t initValues) { // Calculate the CP asymmetries // Also calculate the fit fraction asymmetries for (UInt_t i = 0; i < nSigComp_; i++) { acp_[i] = coeffPars_[i]->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 LauTimeDepFlavModel::setSignalDPParameters() { // Set the fit parameters for the signal model. nSigDPPar_ = 0; if ( ! this->useDP() ) { return; } std::cout << "INFO in LauTimeDepFlavModel::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 LauTimeDepFlavModel::addParametersToFitList(LauTagCatDtPdfMap& theMap) { UInt_t counter(0); // loop through the map for (LauTagCatDtPdfMap::iterator iter = theMap.begin(); iter != theMap.end(); ++iter) { // grab the pdf and then its parameters LauDecayTimePdf* thePdf = (*iter).second; // The first one is the tagging category LauAbsRValuePList& rvalues = thePdf->getParameters(); counter += this->addFitParameters(rvalues); } return counter; } UInt_t LauTimeDepFlavModel::addParametersToFitList(LauTagCatPdfMap& theMap) { UInt_t counter(0); // loop through the map for (LauTagCatPdfMap::iterator iter = theMap.begin(); iter != theMap.end(); ++iter) { counter += this->addFitParameters(iter->second); // first is the tagging category } return counter; } void LauTimeDepFlavModel::setDecayTimeParameters() { nDecayTimePar_ = 0; // Loop over the Dt PDFs nDecayTimePar_ += this->addParametersToFitList(signalDecayTimePdfs_); if (useSinCos_) { nDecayTimePar_ += this->addFitParameters( &sinPhiMix_ ); nDecayTimePar_ += this->addFitParameters( &cosPhiMix_ ); } else { nDecayTimePar_ += this->addFitParameters( &phiMix_ ); } } void LauTimeDepFlavModel::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; nExtraPdfPar_ += this->addParametersToFitList(sigExtraPdf_); } void LauTimeDepFlavModel::setFitNEvents() { nNormPar_ = 0; // 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 LauTimeDepFlavModel::setFitNEvents : Initialising number of events for signal and background components..."<addFitParameters( signalEvents_ ); } else { std::cout<<"INFO in LauTimeDepFlavModel::setFitNEvents : Initialising number of events for background components (and hence signal)..."<useDP() == kFALSE) { nNormPar_ += this->addFitParameters( signalAsym_ ); } // 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); nNormPar_ += this->addFitParameters( par ); } } void LauTimeDepFlavModel::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 LauTimeDepFlavModel::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 LauTimeDepFlavModel::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 LauTimeDepFlavModel::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 for (LauTagCatDtPdfMap::iterator iter = signalDecayTimePdfs_.begin(); iter != signalDecayTimePdfs_.end(); ++iter) { LauDecayTimePdf* pdf = (*iter).second; pdf->updatePulls(); } if (useSinCos_) { cosPhiMix_.updatePull(); sinPhiMix_.updatePull(); } else { this->checkMixingPhase(); } // Update the pulls on all the extra PDFs' parameters for (LauTagCatPdfMap::iterator iter = sigExtraPdf_.begin(); iter != sigExtraPdf_.end(); ++iter) { this->updateFitParameters(iter->second); } // Tagging-category fractions for signal and background events Double_t firstCatFrac(1.0); Int_t firstCat(0); for (LauTagCatParamMap::iterator iter = signalTagCatFrac_.begin(); iter != signalTagCatFrac_.end(); ++iter) { if (iter == signalTagCatFrac_.begin()) { firstCat = iter->first; continue; } LauParameter& par = (*iter).second; firstCatFrac -= par.value(); // update the parameter pull par.updatePull(); } signalTagCatFrac_[firstCat].value(firstCatFrac); signalTagCatFrac_[firstCat].updatePull(); // 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 LauTimeDepFlavModel::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 LauTimeDepFlavModel::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 LauTimeDepFlavModel::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(iter->second, 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 LauTimeDepFlavModel::randomiseInitFitPars() { // Only randomise those parameters that are not fixed! std::cout<<"INFO in LauTimeDepFlavModel::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())); } } LauTimeDepFlavModel::LauGenInfo LauTimeDepFlavModel::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; LauTagCatGenInfo eventsB0, eventsB0bar; // 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 ); } Double_t sigAsym(0.0); if (this->useDP() == kFALSE) { sigAsym = signalAsym_->genValue(); for (LauTagCatParamMap::const_iterator iter = signalTagCatFrac_.begin(); iter != signalTagCatFrac_.end(); ++iter) { const LauParameter& par = iter->second; Double_t eventsbyTagCat = par.value() * nEvts; Double_t eventsB0byTagCat = TMath::Nint(eventsbyTagCat/2.0 * (1.0 - sigAsym)); Double_t eventsB0barbyTagCat = TMath::Nint(eventsbyTagCat/2.0 * (1.0 + sigAsym)); if (this->doPoissonSmearing()) { eventsB0byTagCat = LauRandom::randomFun()->Poisson(eventsB0byTagCat); eventsB0barbyTagCat = LauRandom::randomFun()->Poisson(eventsB0barbyTagCat); } eventsB0[iter->first] = std::make_pair( TMath::Nint(eventsB0byTagCat), evtWeight ); eventsB0bar[iter->first] = std::make_pair( TMath::Nint(eventsB0barbyTagCat), evtWeight ); } nEvtsGen[std::make_pair("signal",-1)] = eventsB0; nEvtsGen[std::make_pair("signal",+1)] = eventsB0bar; } 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. } std::cout<<"INFO in LauTimeDepFlavModel::eventsToGenerate : Generating toy MC with:"<setGenNtupleIntegerBranchValue("genSig",1); // 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 { genOK = kFALSE; } 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_); this->setGenNtupleIntegerBranchValue("tagCat",curEvtTagCat_); this->setGenNtupleIntegerBranchValue("tagFlv",curEvtTagFlv_); // 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 LauTimeDepFlavModel::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 LauTimeDepFlavModel::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 (!signalTree_.empty() && (reuseSignal_ || !genOK)) { if (reuseSignal_ || !genOK) { for(LauTagCatEmbDataMap::const_iterator iter = signalTree_.begin(); iter != signalTree_.end(); ++iter) { (iter->second)->clearUsedList(); } } return genOK; } Bool_t LauTimeDepFlavModel::generateSignalEvent() { // Generate signal event, including SCF if necessary. // DP:DecayTime generation follows. // If it's ok, we then generate mES, DeltaE, Fisher/NN... Bool_t genOK(kTRUE); Bool_t generatedEvent(kFALSE); Bool_t doSquareDP = kinematicsB0bar_->squareDP(); doSquareDP &= kinematicsB0_->squareDP(); LauKinematics* kinematics(kinematicsB0bar_); // find the right decay time PDF for the current tagging category LauTagCatDtPdfMap::const_iterator dt_iter = signalDecayTimePdfs_.find(curEvtTagCat_); LauDecayTimePdf* decayTimePdf = (dt_iter != signalDecayTimePdfs_.end()) ? dt_iter->second : 0; // find the right embedded data for the current tagging category LauTagCatEmbDataMap::const_iterator emb_iter = signalTree_.find(curEvtTagCat_); LauEmbeddedData* embeddedData = (emb_iter != signalTree_.end()) ? emb_iter->second : 0; // find the right extra PDFs for the current tagging category LauTagCatPdfMap::iterator extra_iter = sigExtraPdf_.find(curEvtTagCat_); LauPdfPList* extraPdfs = (extra_iter != sigExtraPdf_.end()) ? &(extra_iter->second) : 0; if (this->useDP()) { if (embeddedData) { embeddedData->getEmbeddedEvent(kinematics); curEvtTagFlv_ = TMath::Nint(embeddedData->getValue("tagFlv")); curEvtDecayTimeErr_ = embeddedData->getValue(decayTimePdf->varErrName()); curEvtDecayTime_ = embeddedData->getValue(decayTimePdf->varName()); if (embeddedData->haveBranch("mcMatch")) { Int_t match = TMath::Nint(embeddedData->getValue("mcMatch")); if (match) { this->setGenNtupleIntegerBranchValue("genTMSig",1); this->setGenNtupleIntegerBranchValue("genSCFSig",0); } else { this->setGenNtupleIntegerBranchValue("genTMSig",0); this->setGenNtupleIntegerBranchValue("genSCFSig",1); } } } else { nGenLoop_ = 0; // generate the decay time error (NB the kTRUE forces the generation of a new value) curEvtDecayTimeErr_ = decayTimePdf->generateError(kTRUE); while (generatedEvent == kFALSE && nGenLoop_ < iterationsMax_) { // Calculate the unnormalised truth-matched signal likelihood // First let define the tag flavour Double_t randNo = LauRandom::randomFun()->Rndm(); if (randNo < 0.5) { curEvtTagFlv_ = +1; // B0 tag } else { curEvtTagFlv_ = -1; // B0bar tag } // Calculate event quantities that depend only on the tagCat and tagFlv Double_t qD = curEvtTagFlv_*dilution_[curEvtTagCat_].unblindValue(); Double_t qDDo2 = curEvtTagFlv_*0.5*deltaDilution_[curEvtTagCat_].unblindValue(); // 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); // Retrieve the amplitudes and efficiency from the dynamics const LauComplex& Abar = sigModelB0bar_->getEvtDPAmp(); const LauComplex& A = sigModelB0_->getEvtDPAmp(); Double_t eff = sigModelB0bar_->getEvtEff(); // Next calculate the DP terms Double_t aSqSum = A.abs2() + Abar.abs2(); Double_t aSqDif = A.abs2() - Abar.abs2(); LauComplex inter = Abar * A.conj() * phiMixComplex_; Double_t interTermIm = 2.0 * inter.im(); Double_t interTermRe = 2.0 * inter.re(); // Generate decay time const Double_t tMin = decayTimePdf->minAbscissa(); const Double_t tMax = decayTimePdf->maxAbscissa(); curEvtDecayTime_ = LauRandom::randomFun()->Rndm()*(tMax-tMin) + tMin; // Calculate all the decay time info decayTimePdf->calcLikelihoodInfo(curEvtDecayTime_, curEvtDecayTimeErr_); // First get all the decay time terms //Double_t dtExp = decayTimePdf->getExpTerm(); Double_t dtCos = decayTimePdf->getCosTerm(); Double_t dtSin = decayTimePdf->getSinTerm(); Double_t dtCosh = decayTimePdf->getCoshTerm(); Double_t dtSinh = decayTimePdf->getSinhTerm(); // Combine all terms Double_t cosTerm = dtCos * qD * aSqDif; Double_t sinTerm = dtSin * qD * interTermIm; Double_t coshTerm = dtCosh * (1.0 + qDDo2) * aSqSum; Double_t sinhTerm = dtSinh * (1.0 + qDDo2) * interTermRe; if ( cpEigenValue_ == CPOdd ) { sinTerm *= -1.0; sinhTerm *= -1.0; } // ... to get the total and multiply by the efficiency Double_t ASq = coshTerm + cosTerm - sinTerm + sinhTerm; //ASq /= decayTimePdf->getNormTerm(); ASq *= eff; //Finally we throw the dice to see whether this event should be generated //We make a distinction between the likelihood of TM and SCF to tag the SCF events as such randNo = LauRandom::randomFun()->Rndm(); if (randNo <= ASq/aSqMaxSet_ ) { generatedEvent = kTRUE; nGenLoop_ = 0; if (ASq > aSqMaxVar_) {aSqMaxVar_ = ASq;} } else { nGenLoop_++; } } // end of while !generatedEvent loop } // end of if (embeddedData) else control } else { if ( embeddedData ) { embeddedData->getEmbeddedEvent(0); curEvtTagFlv_ = TMath::Nint(embeddedData->getValue("tagFlv")); curEvtDecayTimeErr_ = embeddedData->getValue(decayTimePdf->varErrName()); curEvtDecayTime_ = embeddedData->getValue(decayTimePdf->varName()); } } // Check whether we have generated the toy MC OK. if (nGenLoop_ >= iterationsMax_) { aSqMaxSet_ = 1.01 * aSqMaxVar_; genOK = kFALSE; std::cerr<<"WARNING in LauTimeDepFlavModel::generateSignalEvent : Hit max iterations: setting aSqMaxSet_ to "< aSqMaxSet_) { aSqMaxSet_ = 1.01 * aSqMaxVar_; genOK = kFALSE; std::cerr<<"WARNING in LauTimeDepFlavModel::generateSignalEvent : Found a larger ASq value: setting aSqMaxSet_ to "<updateKinematics(kinematicsB0bar_->getm13Sq(), kinematicsB0bar_->getm23Sq() ); this->generateExtraPdfValues(extraPdfs, embeddedData); } // Check for problems with the embedding if (embeddedData && (embeddedData->nEvents() == embeddedData->nUsedEvents())) { std::cerr<<"WARNING in LauTimeDepFlavModel::generateSignalEvent : Source of embedded signal events used up, clearing the list of used events."<clearUsedList(); } return genOK; } void LauTimeDepFlavModel::setupGenNtupleBranches() { // Setup the required ntuple branches this->addGenNtupleDoubleBranch("evtWeight"); this->addGenNtupleIntegerBranch("genSig"); this->addGenNtupleIntegerBranch("cpEigenvalue"); this->addGenNtupleIntegerBranch("tagFlv"); this->addGenNtupleIntegerBranch("tagCat"); if (this->useDP() == kTRUE) { // Let's add the decay time variables. if (signalDecayTimePdfs_.begin() != signalDecayTimePdfs_.end()) { LauDecayTimePdf* pdf = signalDecayTimePdfs_.begin()->second; this->addGenNtupleDoubleBranch(pdf->varName()); this->addGenNtupleDoubleBranch(pdf->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 if ( ! sigExtraPdf_.empty() ) { const LauPdfPList& oneTagCatPdfList { sigExtraPdf_.begin()->second }; for ( const LauAbsPdf* pdf : oneTagCatPdfList ) { const std::vector varNames{ pdf->varNames() }; for ( const TString& varName : varNames ) { if ( varName != "m13Sq" && varName != "m23Sq" ) { this->addGenNtupleDoubleBranch( varName ); } } } } } void LauTimeDepFlavModel::setDPDtBranchValues() { // Store the decay time variables. if (signalDecayTimePdfs_.begin() != signalDecayTimePdfs_.end()) { LauDecayTimePdf* pdf = signalDecayTimePdfs_.begin()->second; this->setGenNtupleDoubleBranchValue(pdf->varName(),curEvtDecayTime_); this->setGenNtupleDoubleBranchValue(pdf->varErrName(),curEvtDecayTimeErr_); } LauKinematics* kinematics(0); if (curEvtTagFlv_<0) { 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 LauTimeDepFlavModel::generateExtraPdfValues(LauPdfPList* extraPdfs, LauEmbeddedData* embeddedData) { LauKinematics* kinematics(0); if (curEvtTagFlv_<0) { kinematics = kinematicsB0_; } else { kinematics = kinematicsB0bar_; } // Generate from the extra PDFs if (extraPdfs) { for (LauPdfPList::iterator pdf_iter = extraPdfs->begin(); pdf_iter != extraPdfs->end(); ++pdf_iter) { LauFitData genValues; if (embeddedData) { genValues = embeddedData->getValues( (*pdf_iter)->varNames() ); } else { genValues = (*pdf_iter)->generate(kinematics); } for ( LauFitData::const_iterator var_iter = genValues.begin(); var_iter != genValues.end(); ++var_iter ) { TString varName = var_iter->first; if ( varName != "m13Sq" && varName != "m23Sq" ) { Double_t value = var_iter->second; this->setGenNtupleDoubleBranchValue(varName,value); } } } } } void LauTimeDepFlavModel::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->calcInterTermNorm(); } // Update the signal events from the background numbers if not doing an extended fit if (!this->doEMLFit()) { this->updateSigEvents(); } } void LauTimeDepFlavModel::updateSigEvents() { // The background parameters will have been set from Minuit. // We need to update the signal events using these. Double_t nTotEvts = this->eventsPerExpt(); Double_t signalEvents = nTotEvts; // tagging-category fractions for signal events this->setFirstTagCatFrac(signalTagCatFrac_); signalEvents_->range(-2.0*nTotEvts,2.0*nTotEvts); if ( ! signalEvents_->fixed() ) { signalEvents_->value(signalEvents); } } void LauTimeDepFlavModel::setFirstTagCatFrac(LauTagCatParamMap& theMap) { Double_t firstCatFrac = 1.0; Int_t firstCat(0); for (LauTagCatParamMap::iterator iter = theMap.begin(); iter != theMap.end(); ++iter) { if (iter == theMap.begin()) { firstCat = iter->first; continue; } LauParameter& par = iter->second; firstCatFrac -= par.unblindValue(); } theMap[firstCat].value(firstCatFrac); } void LauTimeDepFlavModel::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(); // Start by caching the tagging and CP-eigenstate information evtTagCatVals_.clear(); evtTagFlvVals_.clear(); evtCPEigenVals_.clear(); if ( ! inputFitData->haveBranch( tagCatVarName_ ) ) { std::cerr << "ERROR in LauTimeDepFlavModel::cacheInputFitVars : Input data does not contain branch \"" << tagCatVarName_ << "\"." << std::endl; gSystem->Exit(EXIT_FAILURE); } if ( ! inputFitData->haveBranch( tagVarName_ ) ) { std::cerr << "ERROR in LauTimeDepFlavModel::cacheInputFitVars : Input data does not contain branch \"" << tagVarName_ << "\"." << std::endl; gSystem->Exit(EXIT_FAILURE); } const Bool_t hasCPEV = ( (cpevVarName_ != "") && inputFitData->haveBranch( cpevVarName_ ) ); UInt_t nEvents = inputFitData->nEvents(); evtTagCatVals_.reserve( nEvents ); evtTagFlvVals_.reserve( nEvents ); evtCPEigenVals_.reserve( nEvents ); LauFitData::const_iterator fitdata_iter; for (UInt_t iEvt = 0; iEvt < nEvents; iEvt++) { const LauFitData& dataValues = inputFitData->getData(iEvt); fitdata_iter = dataValues.find( tagCatVarName_ ); curEvtTagCat_ = static_cast( fitdata_iter->second ); if ( ! this->validTagCat( curEvtTagCat_ ) ) { std::cerr << "WARNING in LauTimeDepFlavModel::cacheInputFitVars : Invalid tagging category " << curEvtTagCat_ << " for event " << iEvt << ", setting it to untagged" << std::endl; curEvtTagCat_ = 0; } evtTagCatVals_.push_back( curEvtTagCat_ ); fitdata_iter = dataValues.find( tagVarName_ ); curEvtTagFlv_ = static_cast( fitdata_iter->second ); if ( TMath::Abs( curEvtTagFlv_ ) != 1 ) { if ( curEvtTagFlv_ > 0 ) { std::cerr << "WARNING in LauTimeDepFlavModel::cacheInputFitVars : Invalid tagging output " << curEvtTagFlv_ << " for event " << iEvt << ", setting it to +1" << std::endl; curEvtTagFlv_ = +1; } else { std::cerr << "WARNING in LauTimeDepFlavModel::cacheInputFitVars : Invalid tagging output " << curEvtTagFlv_ << " for event " << iEvt << ", setting it to -1" << std::endl; curEvtTagFlv_ = -1; } } evtTagFlvVals_.push_back( curEvtTagFlv_ ); // 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 { std::cerr<<"WARNING in LauTimeDepFlavModel::cacheInputFitVars : Unknown value: "<useDP() == kTRUE) { // DecayTime and SigmaDecayTime for (LauTagCatDtPdfMap::iterator dt_iter = signalDecayTimePdfs_.begin(); dt_iter != signalDecayTimePdfs_.end(); ++dt_iter) { (*dt_iter).second->cacheInfo(*inputFitData); } } // ...and then the extra PDFs for (LauTagCatPdfMap::iterator pdf_iter = sigExtraPdf_.begin(); pdf_iter != sigExtraPdf_.end(); ++pdf_iter) { this->cacheInfo(pdf_iter->second, *inputFitData); } if (this->useDP() == kTRUE) { sigModelB0bar_->fillDataTree(*inputFitData); sigModelB0_->fillDataTree(*inputFitData); } } Double_t LauTimeDepFlavModel::getTotEvtLikelihood(const UInt_t iEvt) { // Find out whether the tag-side B was a B0 or a B0bar. curEvtTagFlv_ = evtTagFlvVals_[iEvt]; // Also get the tagging category. curEvtTagCat_ = evtTagCatVals_[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(); if (this->useDP() == kFALSE) { signalEvents *= 0.5 * (1.0 + curEvtTagFlv_ * signalAsym_->unblindValue()); } // Construct the total event likelihood Double_t likelihood(sigLike*signalTagCatFrac_[curEvtTagCat_].unblindValue()); if ( ! signalEvents_->fixed() ) { likelihood *= signalEvents; } return likelihood; } Double_t LauTimeDepFlavModel::getEventSum() const { Double_t eventSum(0.0); eventSum += signalEvents_->unblindValue(); return eventSum; } void LauTimeDepFlavModel::getEvtDPDtLikelihood(const UInt_t iEvt) { // Function to return the signal and background likelihoods for the // Dalitz plot for the given event evtNo. sigDPLike_ = 1.0; //There's always a likelihood term for signal, so we better not zero it. if ( this->useDP() == kFALSE ) { return; } // Mistag probabilities. Defined as: omega = prob of the tagging B0 being reported as B0bar // Whether we want omega or omegaBar depends on q_tag, hence curEvtTagFlv_*... in the previous lines //Double_t misTagFrac = 0.5 * (1.0 - dilution_[curEvtTagCat_] - qDDo2); //Double_t misTagFracBar = 0.5 * (1.0 - dilution_[curEvtTagCat_] + qDDo2); // Calculate event quantities Double_t qD = curEvtTagFlv_*dilution_[curEvtTagCat_].unblindValue(); Double_t qDDo2 = curEvtTagFlv_*0.5*deltaDilution_[curEvtTagCat_].unblindValue(); // Get the dynamics to calculate everything required for the likelihood calculation sigModelB0bar_->calcLikelihoodInfo(iEvt); sigModelB0_->calcLikelihoodInfo(iEvt); // Retrieve the amplitudes and efficiency from the dynamics const LauComplex& Abar = sigModelB0bar_->getEvtDPAmp(); const LauComplex& A = sigModelB0_->getEvtDPAmp(); Double_t eff = sigModelB0bar_->getEvtEff(); // Next calculate the DP terms Double_t aSqSum = A.abs2() + Abar.abs2(); Double_t aSqDif = A.abs2() - Abar.abs2(); LauComplex inter = Abar * A.conj() * phiMixComplex_; Double_t interTermIm = 2.0 * inter.im(); Double_t interTermRe = 2.0 * inter.re(); // First get all the decay time terms //LauDecayTimePdf* signalDtPdf = signalDecayTimePdfs_[curEvtTagCat_]; LauDecayTimePdf* decayTimePdf = signalDecayTimePdfs_[curEvtTagCat_]; decayTimePdf->calcLikelihoodInfo(static_cast(iEvt)); // First get all the decay time terms Double_t dtCos = decayTimePdf->getCosTerm(); Double_t dtSin = decayTimePdf->getSinTerm(); Double_t dtCosh = decayTimePdf->getCoshTerm(); Double_t dtSinh = decayTimePdf->getSinhTerm(); Double_t cosTerm = dtCos * qD * aSqDif; Double_t sinTerm = dtSin * qD * interTermIm; Double_t coshTerm = dtCosh * (1.0 + qDDo2) * aSqSum; Double_t sinhTerm = dtSinh * (1.0 + qDDo2) * interTermRe; if ( cpEigenValue_ == CPOdd ) { sinTerm *= -1.0; sinhTerm *= -1.0; } // ... to get the total and multiply by the efficiency Double_t ASq = coshTerm + cosTerm - sinTerm + sinhTerm; ASq *= eff; // Calculate the DP and time normalisation Double_t normTermIndep = sigModelB0bar_->getDPNorm() + sigModelB0_->getDPNorm(); Double_t normTermCosh = decayTimePdf->getNormTermCosh(); Double_t normTermDep = interTermReNorm_; Double_t normTermSinh = decayTimePdf->getNormTermSinh(); Double_t norm = normTermIndep*normTermCosh + normTermDep*normTermSinh; // Calculate the normalised signal likelihood sigDPLike_ = ASq / norm; } void LauTimeDepFlavModel::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 LauTagCatPdfMap::iterator sig_iter = sigExtraPdf_.find(curEvtTagCat_); LauPdfPList* pdfList = (sig_iter != sigExtraPdf_.end())? &(sig_iter->second) : 0; if (pdfList) { sigExtraLike_ = this->prodPdfValue( *pdfList, iEvt ); } } void LauTimeDepFlavModel::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()); } } Bool_t LauTimeDepFlavModel::validTagCat(Int_t tagCat) const { return (validTagCats_.find(tagCat) != validTagCats_.end()); } Bool_t LauTimeDepFlavModel::checkTagCatFracMap(const LauTagCatParamMap& theMap) const { // First check that there is an entry for each tagging category. // NB an entry won't have been added if it isn't a valid category // so don't need to check for that here. if (theMap.size() != signalTagCatFrac_.size()) { std::cerr<<"ERROR in LauTimeDepFlavModel::checkTagCatFracMap : Not all tagging categories present."< 1E-10) { std::cerr<<"ERROR in LauTimeDepFlavModel::checkTagCatFracMap : Tagging category event fractions do not sum to unity."< -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 LauTimeDepFlavModel::embedSignal(Int_t tagCat, const TString& fileName, const TString& treeName, Bool_t reuseEventsWithinEnsemble, Bool_t reuseEventsWithinExperiment) { if (signalTree_[tagCat]) { std::cerr<<"ERROR in LauTimeDepFlavModel::embedSignal : Already embedding signal from file for tagging category "<findBranches(); if (!dataOK) { delete signalTree_[tagCat]; signalTree_[tagCat] = 0; std::cerr<<"ERROR in LauTimeDepFlavModel::embedSignal : Problem creating data tree for embedding."<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"); // Store the DP likelihoods if (this->useDP()) { this->addSPlotNtupleDoubleBranch("sigDPLike"); } // Store the likelihoods for each extra PDF const LauPdfPList* pdfList( &(sigExtraPdf_.begin()->second) ); this->addSPlotNtupleBranches(pdfList, "sig"); } void LauTimeDepFlavModel::addSPlotNtupleBranches(const LauPdfPList* extraPdfs, const TString& prefix) { if (!extraPdfs) { return; } // 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 varName = pdf->varName(); TString name(prefix); name += 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 ) { 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 LauTimeDepFlavModel::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 varName = pdf->varName(); TString name(prefix); name += 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 ) { allVars += varName; TString name(prefix); name += varName; name += "Like"; 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"); } LauPdfPList pdfList( (sigExtraPdf_.begin()->second) ); for ( const LauAbsPdf* pdf : pdfList ) { // 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 LauTimeDepFlavModel::freeSpeciesNames() const { LauSPlot::NumbMap numbMap; if (!signalEvents_->fixed() && this->doEMLFit()) { numbMap["sig"] = signalEvents_->genValue(); } return numbMap; } LauSPlot::NumbMap LauTimeDepFlavModel::fixdSpeciesNames() const { LauSPlot::NumbMap numbMap; if (signalEvents_->fixed() && this->doEMLFit()) { numbMap["sig"] = signalEvents_->genValue(); } return numbMap; } LauSPlot::TwoDMap LauTimeDepFlavModel::twodimPDFs() const { LauSPlot::TwoDMap twodimMap; const LauPdfPList& pdfList { sigExtraPdf_.begin()->second }; for ( const LauAbsPdf* pdf : pdfList ) { // 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] ) ) ); } } return twodimMap; } void LauTimeDepFlavModel::storePerEvtLlhds() { std::cout<<"INFO in LauTimeDepFlavModel::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 curEvtTagFlv_ = evtTagFlvVals_[iEvt]; curEvtTagCat_ = evtTagCatVals_[iEvt]; LauTagCatPdfMap::iterator sig_iter = sigExtraPdf_.find(curEvtTagCat_); LauPdfPList* sigPdfs = (sig_iter != sigExtraPdf_.end())? &(sig_iter->second) : 0; // 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_); } else { sigTotalLike_ = 1.0; } // the signal PDF values sigTotalLike_ *= this->setSPlotNtupleBranchValues(sigPdfs, "sig", iEvt); // the total likelihoods this->setSPlotNtupleDoubleBranchValue("sigTotalLike",sigTotalLike_); // fill the tree this->fillSPlotNtupleBranches(); } std::cout<<"INFO in LauTimeDepFlavModel::storePerEvtLlhds : Finished storing per-event likelihood values."< #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 "LauPrint.hh" #include "LauRandom.hh" #include "LauScfMap.hh" #include "LauTimeDepNonFlavModel.hh" ClassImp(LauTimeDepNonFlavModel) LauTimeDepNonFlavModel::LauTimeDepNonFlavModel(LauIsobarDynamics* modelB0bar_f, LauIsobarDynamics* modelB0_f, LauIsobarDynamics* modelB0bar_fbar, LauIsobarDynamics* modelB0_fbar, const Bool_t useUntaggedEvents, const TString& tagVarName, const TString& tagCatVarName) : LauAbsFitModel(), sigModelB0bar_f_(modelB0bar_f), sigModelB0_f_(modelB0_f), sigModelB0bar_fbar_(modelB0bar_fbar), sigModelB0_fbar_(modelB0_fbar), kinematicsB0bar_f_(modelB0bar_f ? modelB0bar_f->getKinematics() : 0), kinematicsB0_f_(modelB0_f ? modelB0_f->getKinematics() : 0), kinematicsB0bar_fbar_(modelB0bar_fbar ? modelB0bar_fbar->getKinematics() : 0), kinematicsB0_fbar_(modelB0_fbar ? modelB0_fbar->getKinematics() : 0), useUntaggedEvents_(useUntaggedEvents), nSigComp_(0), nSigDPPar_(0), nDecayTimePar_(0), nExtraPdfPar_(0), nNormPar_(0), coeffsB0bar_f_(0), coeffsB0_f_(0), coeffsB0bar_fbar_(0), coeffsB0_fbar_(0), coeffPars_B0f_B0barfbar_(0), coeffPars_B0fbar_B0barf_(0), interTermReNorm_f_(0), interTermReNorm_fbar_(0), interTermImNorm_f_(0), interTermImNorm_fbar_(0), fitFracB0bar_f_(0), fitFracB0_f_(0), fitFracB0bar_fbar_(0), fitFracB0_fbar_(0), fitFracAsymm_B0f_B0barfbar_(0), fitFracAsymm_B0fbar_B0barf_(0), acp_B0f_B0barfbar_(0), acp_B0fbar_B0barf_(0), meanEffB0bar_f_("meanEffB0bar_f",0.0,0.0,1.0), meanEffB0_f_("meanEffB0_f",0.0,0.0,1.0), meanEffB0bar_fbar_("meanEffB0bar_fbar",0.0,0.0,1.0), meanEffB0_fbar_("meanEffB0_fbar",0.0,0.0,1.0), DPRateB0bar_f_("DPRateB0bar_f",0.0,0.0,100.0), DPRateB0_f_("DPRateB0_f",0.0,0.0,100.0), DPRateB0bar_fbar_("DPRateB0bar_fbar",0.0,0.0,100.0), DPRateB0_fbar_("DPRateB0_fbar",0.0,0.0,100.0), signalEvents_(0), signalAsym_(0), signalTagCatFrac_(), tagVarName_(tagVarName), tagCatVarName_(tagCatVarName), cpevVarName_(""), validTagCats_(), curEvtTagFlv_(0), curEvtTagCat_(0), cpEigenValue_(CPEven), evtTagFlvVals_(0), evtTagCatVals_(0), evtCPEigenVals_(0), dilution_(), deltaDilution_(), 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), -3.0, 3.0, kFALSE), cosPhiMix_("cosPhiMix", TMath::Cos(2.0*LauConstants::beta), -3.0, 3.0, kFALSE), useSinCos_(kFALSE), phiMixComplex_(TMath::Cos(-2.0*LauConstants::beta),TMath::Sin(-2.0*LauConstants::beta)), signalDecayTimePdfs_(), curEvtDecayTime_(0.0), curEvtDecayTimeErr_(0.0), qD_(0.0), qDDo2_(0.0), sigExtraPdf_(), finalState_(0.0), iterationsMax_(500000), nGenLoop_(0), ASq_(0.0), aSqMaxVar_(0.0), aSqMaxSet_(1.25), normTimeDP_f_(0.0), normTimeDP_fbar_(0.0), storeGenAmpInfo_(kFALSE), signalTree_(), reuseSignal_(kFALSE), sigDPLike_(0.0), sigExtraLike_(0.0), sigTotalLike_(0.0) { // Add the untagged category as a valid category this->addValidTagCat(0); // Set the fraction, average dilution and dilution difference for the untagged category this->setSignalTagCatPars(0, 1.0, 0.0, 0.0, kTRUE); } LauTimeDepNonFlavModel::~LauTimeDepNonFlavModel() { // TODO - need to delete the various embedded data structures here } void LauTimeDepNonFlavModel::setupBkgndVectors() { } void LauTimeDepNonFlavModel::setNSigEvents(LauParameter* nSigEvents) { if ( nSigEvents == 0 ) { std::cerr << "ERROR in LauTimeDepNonFlavModel::setNSigEvents : The LauParameter pointer is null." << std::endl; gSystem->Exit(EXIT_FAILURE); } if ( signalEvents_ != 0 ) { std::cerr << "ERROR in LauTimeDepNonFlavModel::setNSigEvents : You are trying to overwrite the signal yield." << std::endl; return; } if ( signalAsym_ != 0 ) { std::cerr << "ERROR in LauTimeDepNonFlavModel::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 LauTimeDepNonFlavModel::setNSigEvents(LauParameter* nSigEvents, LauParameter* sigAsym) { if ( nSigEvents == 0 ) { std::cerr << "ERROR in LauTimeDepNonFlavModel::setNSigEvents : The event LauParameter pointer is null." << std::endl; gSystem->Exit(EXIT_FAILURE); } if ( sigAsym == 0 ) { std::cerr << "ERROR in LauTimeDepNonFlavModel::setNSigEvents : The asym LauParameter pointer is null." << std::endl; gSystem->Exit(EXIT_FAILURE); } if ( signalEvents_ != 0 ) { std::cerr << "ERROR in LauTimeDepNonFlavModel::setNSigEvents : You are trying to overwrite the signal yield." << std::endl; return; } if ( signalAsym_ != 0 ) { std::cerr << "ERROR in LauTimeDepNonFlavModel::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 LauTimeDepNonFlavModel::setNBkgndEvents(LauAbsRValue* /*nBkgndEvents*/) { std::cerr << "WARNING in LauTimeDepNonFlavModel::setNBkgndEvents : This model does not yet support backgrounds" << std::endl; } void LauTimeDepNonFlavModel::addValidTagCats(const std::vector& tagCats) { for (std::vector::const_iterator iter = tagCats.begin(); iter != tagCats.end(); ++iter) { this->addValidTagCat(*iter); } } void LauTimeDepNonFlavModel::addValidTagCat(Int_t tagCat) { validTagCats_.insert(tagCat); } void LauTimeDepNonFlavModel::setSignalTagCatPars(const Int_t tagCat, const Double_t tagCatFrac, const Double_t dilution, const Double_t deltaDilution, const Bool_t fixTCFrac) { if (!this->validTagCat(tagCat)) { std::cerr<<"ERROR in LauTimeDepNonFlavModel::setSignalTagCatPars : Tagging category \""<checkSignalTagCatFractions(); only when the user has //set them all up, in this->initialise(); } void LauTimeDepNonFlavModel::checkSignalTagCatFractions() { Double_t totalTaggedFrac(0.0); for (LauTagCatParamMap::const_iterator iter=signalTagCatFrac_.begin(); iter!=signalTagCatFrac_.end(); ++iter) { if (iter->first != 0) { const LauParameter& par = iter->second; totalTaggedFrac += par.value(); } } if ( ((totalTaggedFrac < (1.0-1.0e-8))&&!useUntaggedEvents_) || (totalTaggedFrac > (1.0+1.0e-8)) ) { std::cerr<<"WARNING in LauTimeDepNonFlavModel::checkSignalTagCatFractions : Tagging category fractions add up to "<second; Double_t newVal = par.value() / totalTaggedFrac; par.value(newVal); par.initValue(newVal); par.genValue(newVal); } } else if (useUntaggedEvents_) { Double_t tagCatFrac = 1.0 - totalTaggedFrac; TString tagCatFracName("signalTagCatFrac0"); signalTagCatFrac_[0].name(tagCatFracName); signalTagCatFrac_[0].range(0.0,1.0); signalTagCatFrac_[0].value(tagCatFrac); signalTagCatFrac_[0].initValue(tagCatFrac); signalTagCatFrac_[0].genValue(tagCatFrac); signalTagCatFrac_[0].fixed(kTRUE); TString dilutionName("dilution0"); dilution_[0].name(dilutionName); dilution_[0].range(0.0,1.0); dilution_[0].value(0.0); dilution_[0].initValue(0.0); dilution_[0].genValue(0.0); TString deltaDilutionName("deltaDilution0"); deltaDilution_[0].name(deltaDilutionName); deltaDilution_[0].range(-2.0,2.0); deltaDilution_[0].value(0.0); deltaDilution_[0].initValue(0.0); deltaDilution_[0].genValue(0.0); } for (LauTagCatParamMap::const_iterator iter=dilution_.begin(); iter!=dilution_.end(); ++iter) { - std::cout<<"INFO in LauTimeDepNonFlavModel::checkSignalTagCatFractions : Setting dilution for tagging category "<<(*iter).first<<" to "<<(*iter).second<validTagCat(tagCat)) { std::cerr<<"ERROR in LauTimeDepNonFlavModel::setSignalDtPdf : Tagging category \""<validTagCat(tagCat)) { std::cerr<<"ERROR in LauTimeDepNonFlavModel::setSignalPdfs : Tagging category \""<updateCoeffs(); // Initialisation if (this->useDP() == kTRUE) { this->initialiseDPModels(); } if (!this->useDP() && sigExtraPdf_.empty()) { std::cerr<<"ERROR in LauTimeDepNonFlavModel::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_f_ == 0) || (sigModelB0_f_ == 0) || (sigModelB0bar_fbar_ == 0) || (sigModelB0bar_fbar_ == 0)) { std::cerr<<"ERROR in LauTimeDepNonFlavModel::initialise : the pointer to one (particle or anti-particle) of the signal DP models is null."<Exit(EXIT_FAILURE); } } // Check here that the tagging category fractions add up to 1, otherwise "normalise". Also set up the untagged cat. // NB this has to be done early in the initialization as other methods access the tagCats map. this->checkSignalTagCatFractions(); // 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(); // Check that we have the expected number of fit variables const LauParameterPList& fitVars = this->fitPars(); if (fitVars.size() != (nSigDPPar_ + nDecayTimePar_ + nExtraPdfPar_ + nNormPar_)) { std::cerr<<"ERROR in LauTimeDepNonFlavModel::initialise : Number of fit parameters not of expected size."<Exit(EXIT_FAILURE); } this->setExtraNtupleVars(); } void LauTimeDepNonFlavModel::recalculateNormalisation() { sigModelB0bar_f_->recalculateNormalisation(); sigModelB0_f_->recalculateNormalisation(); sigModelB0bar_fbar_->recalculateNormalisation(); sigModelB0_fbar_->recalculateNormalisation(); sigModelB0bar_f_->modifyDataTree(); sigModelB0_f_->modifyDataTree(); sigModelB0bar_fbar_->modifyDataTree(); sigModelB0_fbar_->modifyDataTree(); this->calcInterferenceTermIntegrals(); } void LauTimeDepNonFlavModel::initialiseDPModels() { if (sigModelB0bar_f_ == 0) { std::cerr<<"ERROR in LauTimeDepNonFlavModel::initialiseDPModels : B0bar -> f signal DP model doesn't exist"<Exit(EXIT_FAILURE); } if (sigModelB0_f_ == 0) { std::cerr<<"ERROR in LauTimeDepNonFlavModel::initialiseDPModels : B0 -> f signal DP model doesn't exist"<Exit(EXIT_FAILURE); } if (sigModelB0bar_fbar_ == 0) { std::cerr<<"ERROR in LauTimeDepNonFlavModel::initialiseDPModels : B0bar -> fbar signal DP model doesn't exist"<Exit(EXIT_FAILURE); } if (sigModelB0_fbar_ == 0) { std::cerr<<"ERROR in LauTimeDepNonFlavModel::initialiseDPModels : B0 -> fbar 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_f = sigModelB0bar_f_->getnAmp(); //const UInt_t nAmpB0_f = sigModelB0_f_->getnAmp(); //const UInt_t nAmpB0bar_fbar = sigModelB0bar_fbar_->getnAmp(); //const UInt_t nAmpB0_fbar = sigModelB0_fbar_->getnAmp(); const UInt_t nAmpB0bar_f = sigModelB0bar_f_->getnTotAmp(); const UInt_t nAmpB0_f = sigModelB0_f_->getnTotAmp(); const UInt_t nAmpB0bar_fbar = sigModelB0bar_fbar_->getnTotAmp(); const UInt_t nAmpB0_fbar = sigModelB0_fbar_->getnTotAmp(); if ( nAmpB0bar_f != nAmpB0_f ){ std::cerr << "ERROR in LauTimeDepNonFlavModel::initialiseDPModels : Unequal number of signal DP components in the particle and anti-particle models: " << nAmpB0bar_f << " != " << nAmpB0_f << std::endl; gSystem->Exit(EXIT_FAILURE); } else if ( nAmpB0bar_fbar != nAmpB0_fbar ) { std::cerr << "ERROR in LauTimeDepNonFlavModel::initialiseDPModels : Unequal number of signal DP components in the particle and anti-particle models: " << nAmpB0bar_fbar << " != " << nAmpB0_fbar << std::endl; gSystem->Exit(EXIT_FAILURE); } if ( nAmpB0bar_f != nSigComp_ ) { std::cerr << "ERROR in LauTimeDepNonFlavModel::initialiseDPModels : Number of signal DP components in the model (" << nAmpB0bar_f << ") not equal to number of coefficients supplied (" << nSigComp_ << ")." << std::endl; gSystem->Exit(EXIT_FAILURE); } std::cout<<"INFO in LauTimeDepNonFlavModel::initialiseDPModels : Initialising signal DP model"<initialise(coeffsB0bar_f_); sigModelB0_f_->initialise(coeffsB0_f_); sigModelB0bar_fbar_->initialise(coeffsB0bar_fbar_); sigModelB0_fbar_->initialise(coeffsB0_fbar_); fifjEffSum_f_.clear(); fifjEffSum_fbar_.clear(); fifjEffSum_f_.resize(nSigComp_); fifjEffSum_fbar_.resize(nSigComp_); for (UInt_t iAmp = 0; iAmp < nSigComp_; ++iAmp) { fifjEffSum_f_[iAmp].resize(nSigComp_); fifjEffSum_fbar_[iAmp].resize(nSigComp_); } // calculate the integrals of the A*Abar terms this->calcInterferenceTermIntegrals(); this->calcInterTermNorm(); } void LauTimeDepNonFlavModel::calcInterferenceTermIntegrals() { const std::vector& integralInfoListB0bar_f = sigModelB0bar_f_->getIntegralInfos(); const std::vector& integralInfoListB0_f = sigModelB0_f_->getIntegralInfos(); const std::vector& integralInfoListB0bar_fbar = sigModelB0bar_fbar_->getIntegralInfos(); const std::vector& integralInfoListB0_fbar = sigModelB0_fbar_->getIntegralInfos(); LauComplex A_f, Abar_f, A_fbar, Abar_fbar, fifjEffSumTerm_f, fifjEffSumTerm_fbar; for (UInt_t iAmp = 0; iAmp < nSigComp_; ++iAmp) { for (UInt_t jAmp = 0; jAmp < nSigComp_; ++jAmp) { fifjEffSum_f_[iAmp][jAmp].zero(); fifjEffSum_fbar_[iAmp][jAmp].zero(); } } const UInt_t nIntegralRegions_f = integralInfoListB0bar_f.size(); for ( UInt_t iRegion(0); iRegion < nIntegralRegions_f; ++iRegion ) { const LauDPPartialIntegralInfo* integralInfoB0bar_f = integralInfoListB0bar_f[iRegion]; const LauDPPartialIntegralInfo* integralInfoB0_f = integralInfoListB0_f[iRegion]; const UInt_t nm13Points = integralInfoB0bar_f->getnm13Points(); const UInt_t nm23Points = integralInfoB0bar_f->getnm23Points(); for (UInt_t m13 = 0; m13 < nm13Points; ++m13) { for (UInt_t m23 = 0; m23 < nm23Points; ++m23) { const Double_t weight_f = integralInfoB0bar_f->getWeight(m13,m23); const Double_t eff_f = integralInfoB0bar_f->getEfficiency(m13,m23); const Double_t effWeight_f = eff_f*weight_f; for (UInt_t iAmp = 0; iAmp < nSigComp_; ++iAmp) { A_f = integralInfoB0_f->getAmplitude(m13, m23, iAmp); for (UInt_t jAmp = 0; jAmp < nSigComp_; ++jAmp) { Abar_f = integralInfoB0bar_f->getAmplitude(m13, m23, jAmp); fifjEffSumTerm_f = Abar_f*A_f.conj(); fifjEffSumTerm_f.rescale(effWeight_f); fifjEffSum_f_[iAmp][jAmp] += fifjEffSumTerm_f; } } } } } const UInt_t nIntegralRegions_fbar = integralInfoListB0bar_fbar.size(); for ( UInt_t iRegion(0); iRegion < nIntegralRegions_fbar; ++iRegion ) { const LauDPPartialIntegralInfo* integralInfoB0bar_fbar = integralInfoListB0bar_fbar[iRegion]; const LauDPPartialIntegralInfo* integralInfoB0_fbar = integralInfoListB0_fbar[iRegion]; const UInt_t nm13Points = integralInfoB0bar_fbar->getnm13Points(); const UInt_t nm23Points = integralInfoB0bar_fbar->getnm23Points(); for (UInt_t m13 = 0; m13 < nm13Points; ++m13) { for (UInt_t m23 = 0; m23 < nm23Points; ++m23) { const Double_t weight_fbar = integralInfoB0bar_fbar->getWeight(m13,m23); const Double_t eff_fbar = integralInfoB0bar_fbar->getEfficiency(m13,m23); const Double_t effWeight_fbar = eff_fbar*weight_fbar; for (UInt_t iAmp = 0; iAmp < nSigComp_; ++iAmp) { A_fbar = integralInfoB0_fbar->getAmplitude(m13, m23, iAmp); for (UInt_t jAmp = 0; jAmp < nSigComp_; ++jAmp) { Abar_fbar = integralInfoB0bar_fbar->getAmplitude(m13, m23, jAmp); fifjEffSumTerm_fbar = Abar_fbar*A_fbar.conj(); fifjEffSumTerm_fbar.rescale(effWeight_fbar); fifjEffSum_fbar_[iAmp][jAmp] += fifjEffSumTerm_fbar; } } } } } } void LauTimeDepNonFlavModel::calcInterTermNorm() { const std::vector fNormB0bar_f = sigModelB0bar_f_->getFNorm(); const std::vector fNormB0_f = sigModelB0_f_->getFNorm(); const std::vector fNormB0bar_fbar = sigModelB0bar_fbar_->getFNorm(); const std::vector fNormB0_fbar = sigModelB0_fbar_->getFNorm(); LauComplex norm_f; LauComplex norm_fbar; for (UInt_t iAmp = 0; iAmp < nSigComp_; ++iAmp) { for (UInt_t jAmp = 0; jAmp < nSigComp_; ++jAmp) { LauComplex coeffTerm_f = coeffsB0bar_f_[jAmp]*coeffsB0_f_[iAmp].conj(); LauComplex coeffTerm_fbar = coeffsB0bar_fbar_[jAmp]*coeffsB0_fbar_[iAmp].conj(); coeffTerm_f *= fifjEffSum_f_[iAmp][jAmp]; coeffTerm_fbar *= fifjEffSum_fbar_[iAmp][jAmp]; coeffTerm_f.rescale(fNormB0bar_f[jAmp] * fNormB0_f[iAmp]); coeffTerm_fbar.rescale(fNormB0bar_fbar[jAmp] * fNormB0_fbar[iAmp]); norm_f += coeffTerm_f; norm_fbar += coeffTerm_fbar; } } norm_f *= phiMixComplex_; norm_fbar *= phiMixComplex_; interTermReNorm_f_ = 2.0*norm_f.re(); interTermImNorm_f_ = 2.0*norm_f.im(); interTermReNorm_fbar_ = 2.0*norm_fbar.re(); interTermImNorm_fbar_ = 2.0*norm_fbar.im(); } void LauTimeDepNonFlavModel::setAmpCoeffSet(std::unique_ptr coeffSet) { std::cerr<<"ERROR in LauTimeDepNonFlavModel::setAmpCoeffSet : Set of coefficients for B0/B0bar -> f,fbar contains only component for f final state \""<name()<<"\"."< coeffSet_B0f_B0barfbar, std::unique_ptr coeffSet_B0fbar_B0barf) { // Define the signal model for each of the particle/antiparticle and f/fbar final states const TString compName_B0f_B0barfbar { coeffSet_B0f_B0barfbar->name() }; const TString compName_B0fbar_B0barf { coeffSet_B0fbar_B0barf->name() }; const TString conjName_B0f_B0barfbar { sigModelB0bar_fbar_->getConjResName(compName_B0f_B0barfbar) }; const TString conjName_B0fbar_B0barf { sigModelB0bar_f_->getConjResName(compName_B0fbar_B0barf) }; //std::cout << "Values are: " << std::endl; //std::cout << "CompName: " << compName_B0f_B0barfbar << " " << compName_B0fbar_B0barf << std::endl; //std::cout << "ComjName: " << conjName_B0f_B0barfbar << " " << conjName_B0fbar_B0barf << std::endl; // Define each daughter configuration const LauDaughters* daughtersB0bar_f { sigModelB0bar_f_->getDaughters() }; const LauDaughters* daughtersB0_f { sigModelB0_f_->getDaughters() }; const LauDaughters* daughtersB0bar_fbar { sigModelB0bar_fbar_->getDaughters() }; const LauDaughters* daughtersB0_fbar { sigModelB0_fbar_->getDaughters() }; const Bool_t conjugateB0_f { daughtersB0_f->isConjugate( daughtersB0bar_fbar ) }; const Bool_t conjugateB0_fbar { daughtersB0_fbar->isConjugate( daughtersB0bar_f ) }; if ( ! sigModelB0_f_->hasResonance(compName_B0f_B0barfbar) ) { if ( ! sigModelB0_f_->hasResonance(conjName_B0f_B0barfbar) ) { std::cerr<<"ERROR in LauTimeDepNonFlavModel::setAmpCoeffSet : B0 -> f signal DP model doesn't contain component \""<< compName_B0f_B0barfbar <<"\"."<hasResonance(compName_B0fbar_B0barf) ) { if ( ! sigModelB0_fbar_->hasResonance(conjName_B0fbar_B0barf) ) { std::cerr<<"ERROR in LauTimeDepNonFlavModel::setAmpCoeffSet : B0 -> fbar signal DP model doesn't contain component \""<< compName_B0fbar_B0barf<<"\"."<hasResonance(conjName_B0f_B0barfbar) ) { std::cerr<<"ERROR in LauTimeDepNonFlavModel::setAmpCoeffSet : signal DP model doesn't contain component \""<hasResonance(conjName_B0fbar_B0barf) ) { std::cerr<<"ERROR in LauTimeDepNonFlavModel::setAmpCoeffSet : signal DP model doesn't contain component \""<hasResonance(compName_B0f_B0barfbar) ) { std::cerr<<"ERROR in LauTimeDepNonFlavModel::setAmpCoeffSet : signal DP model doesn't contain component \""<hasResonance(compName_B0fbar_B0barf) ) { std::cerr<<"ERROR in LauTimeDepNonFlavModel::setAmpCoeffSet : signal DP model doesn't contain component \""<resonanceIndex(compName_B0fbar_B0barf) }; const Int_t index_B0_f { sigModelB0_f_->resonanceIndex(compName_B0f_B0barfbar) }; const Int_t index_B0bar_fbar { sigModelB0bar_fbar_->resonanceIndex(compName_B0f_B0barfbar) }; const Int_t index_B0_fbar { sigModelB0_fbar_->resonanceIndex(compName_B0fbar_B0barf) }; if ( index_B0bar_f != index_B0_f || index_B0bar_f != index_B0bar_fbar || index_B0bar_f != index_B0_fbar ) { std::cerr << "ERROR in LauTimeDepNonFlavModel::setAmpCoeffSet : signal DP models have different indices for component \"" << compName_B0fbar_B0barf << " / " << compName_B0f_B0barfbar << "\"." << std::endl; return; } // Do we already have it in our list of names? if ( coeffPars_B0f_B0barfbar_[index_B0_f] != nullptr && coeffPars_B0f_B0barfbar_[index_B0_f]->name() == compName_B0f_B0barfbar ) { std::cerr<<"ERROR in LauTimeDepNonFlavModel::setAmpCoeffSet : Have already set coefficients for \""<name() == compName_B0fbar_B0barf ) { std::cerr<<"ERROR in LauTimeDepNonFlavModel::setAmpCoeffSet : Have already set coefficients for \""<index(nSigComp_); coeffSet_B0fbar_B0barf->index(nSigComp_); std::cout<<"INFO in LauTimeDepNonFlavModel::setAmpCoeffSet : Added coefficients for components \""<f, B0bar->fbar) and \""<fbar, B0bar->f)"<printParValues(); coeffSet_B0fbar_B0barf->printParValues(); const TString parName_B0f_B0barfbar { coeffSet_B0f_B0barfbar->baseName() + "FitFracAsym" }; const TString parName_B0fbar_B0barf { coeffSet_B0fbar_B0barf->baseName() + "FitFracAsym" }; fitFracAsymm_B0f_B0barfbar_[index_B0_f] = LauParameter{parName_B0f_B0barfbar, 0.0, -1.0, 1.0}; fitFracAsymm_B0fbar_B0barf_[index_B0_fbar] = LauParameter{parName_B0fbar_B0barf, 0.0, -1.0, 1.0}; acp_B0f_B0barfbar_[index_B0_f] = coeffSet_B0f_B0barfbar->acp(); acp_B0fbar_B0barf_[index_B0_fbar] = coeffSet_B0fbar_B0barf->acp(); coeffPars_B0f_B0barfbar_[index_B0_f] = std::move(coeffSet_B0f_B0barfbar); coeffPars_B0fbar_B0barf_[index_B0_fbar] = std::move(coeffSet_B0fbar_B0barf); ++nSigComp_; } void LauTimeDepNonFlavModel::calcAsymmetries(Bool_t initValues) { // Calculate the CP asymmetries between B0_f(B0_fbar) and B0bar_fbar(B0bar_f) // Also calculate the fit fraction asymmetries for (UInt_t i = 0; i < nSigComp_; i++) { acp_B0f_B0barfbar_[i] = coeffPars_B0f_B0barfbar_[i]->acp(); acp_B0fbar_B0barf_[i] = coeffPars_B0fbar_B0barf_[i]->acp(); LauAsymmCalc asymmCalc_B0f_B0barfbar(fitFracB0bar_fbar_[i][i].value(), fitFracB0_f_[i][i].value()); LauAsymmCalc asymmCalc_B0fbar_B0barf(fitFracB0bar_f_[i][i].value(), fitFracB0_fbar_[i][i].value()); Double_t asym_B0f_B0barfbar = asymmCalc_B0f_B0barfbar.getAsymmetry(); Double_t asym_B0fbar_B0barf = asymmCalc_B0fbar_B0barf.getAsymmetry(); fitFracAsymm_B0f_B0barfbar_[i].value(asym_B0f_B0barfbar); fitFracAsymm_B0fbar_B0barf_[i].value(asym_B0fbar_B0barf); if (initValues) { fitFracAsymm_B0f_B0barfbar_[i].genValue(asym_B0f_B0barfbar); fitFracAsymm_B0fbar_B0barf_[i].genValue(asym_B0fbar_B0barf); fitFracAsymm_B0f_B0barfbar_[i].initValue(asym_B0f_B0barfbar); fitFracAsymm_B0fbar_B0barf_[i].initValue(asym_B0fbar_B0barf); } } } void LauTimeDepNonFlavModel::setSignalDPParameters() { // Set the fit parameters for the signal model. nSigDPPar_ = 0; if ( ! this->useDP() ) { return; } std::cout << "INFO in LauTimeDepNonFlavModel::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_B0f_B0barfbar = coeffPars_B0f_B0barfbar_[i]->getParameters(); LauParameterPList pars_B0fbar_B0barf = coeffPars_B0fbar_B0barf_[i]->getParameters(); nSigDPPar_ += this->addFitParameters( pars_B0f_B0barfbar, kTRUE ); nSigDPPar_ += this->addFitParameters( pars_B0fbar_B0barf, 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_f = sigModelB0bar_f_->getFloatingParameters(); LauParameterPList& sigDPParsB0_f = sigModelB0_f_->getFloatingParameters(); LauParameterPList& sigDPParsB0bar_fbar = sigModelB0bar_fbar_->getFloatingParameters(); LauParameterPList& sigDPParsB0_fbar = sigModelB0_fbar_->getFloatingParameters(); nSigDPPar_ += this->addResonanceParameters( sigDPParsB0bar_f ); nSigDPPar_ += this->addResonanceParameters( sigDPParsB0_f ); nSigDPPar_ += this->addResonanceParameters( sigDPParsB0bar_fbar ); nSigDPPar_ += this->addResonanceParameters( sigDPParsB0_fbar ); } UInt_t LauTimeDepNonFlavModel::addParametersToFitList(LauTagCatDtPdfMap& theMap) { UInt_t counter(0); // loop through the map for (LauTagCatDtPdfMap::iterator iter = theMap.begin(); iter != theMap.end(); ++iter) { // grab the pdf and then its parameters LauDecayTimePdf* thePdf = (*iter).second; // The first one is the tagging category LauAbsRValuePList& rvalues = thePdf->getParameters(); counter += this->addFitParameters(rvalues); } return counter; } UInt_t LauTimeDepNonFlavModel::addParametersToFitList(LauTagCatPdfMap& theMap) { UInt_t counter(0); // loop through the map for (LauTagCatPdfMap::iterator iter = theMap.begin(); iter != theMap.end(); ++iter) { counter += this->addFitParameters(iter->second); // first is the tagging category } return counter; } void LauTimeDepNonFlavModel::setDecayTimeParameters() { nDecayTimePar_ = 0; // Loop over the Dt PDFs nDecayTimePar_ += this->addParametersToFitList(signalDecayTimePdfs_); if (useSinCos_) { nDecayTimePar_ += this->addFitParameters( &sinPhiMix_ ); nDecayTimePar_ += this->addFitParameters( &cosPhiMix_ ); } else { nDecayTimePar_ += this->addFitParameters( &phiMix_ ); } } void LauTimeDepNonFlavModel::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; nExtraPdfPar_ += this->addParametersToFitList(sigExtraPdf_); } void LauTimeDepNonFlavModel::setFitNEvents() { nNormPar_ = 0; // 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 LauTimeDepNonFlavModel::setFitNEvents : Initialising number of events for signal and background components..."<addFitParameters( signalEvents_ ); } else { std::cout<<"INFO in LauTimeDepNonFlavModel::setFitNEvents : Initialising number of events for background components (and hence signal)..."<useDP() == kFALSE) { nNormPar_ += this->addFitParameters( signalAsym_ ); } // 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); nNormPar_ += this->addFitParameters( par ); } } void LauTimeDepNonFlavModel::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 (f/fbar) and B0bar (f/fbar) fit fractions for each signal component fitFracB0bar_f_ = sigModelB0bar_f_->getFitFractions(); if (fitFracB0bar_f_.size() != nSigComp_) { std::cerr<<"ERROR in LauTimeDepNonFlavModel::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_f_.size() != nSigComp_) { std::cerr<<"ERROR in LauTimeDepNonFlavModel::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 (fitFracB0bar_fbar_.size() != nSigComp_) { std::cerr<<"ERROR in LauTimeDepNonFlavModel::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_fbar_.size() != nSigComp_) { std::cerr<<"ERROR in LauTimeDepNonFlavModel::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_B0f_B0barfbar_[i]); extraVars.push_back(fitFracAsymm_B0fbar_B0barf_[i]); } // Add the calculated CP asymmetry for each signal component for (UInt_t i = 0; i < nSigComp_; i++) { extraVars.push_back(acp_B0f_B0barfbar_[i]); extraVars.push_back(acp_B0fbar_B0barf_[i]); } // Now add in the DP efficiency values Double_t initMeanEffB0bar_f = sigModelB0bar_f_->getMeanEff().initValue(); meanEffB0bar_f_.value(initMeanEffB0bar_f); meanEffB0bar_f_.initValue(initMeanEffB0bar_f); meanEffB0bar_f_.genValue(initMeanEffB0bar_f); extraVars.push_back(meanEffB0bar_f_); Double_t initMeanEffB0_f = sigModelB0_f_->getMeanEff().initValue(); meanEffB0_f_.value(initMeanEffB0_f); meanEffB0_f_.initValue(initMeanEffB0_f); meanEffB0_f_.genValue(initMeanEffB0_f); extraVars.push_back(meanEffB0_f_); Double_t initMeanEffB0bar_fbar = sigModelB0bar_fbar_->getMeanEff().initValue(); meanEffB0bar_fbar_.value(initMeanEffB0bar_fbar); meanEffB0bar_fbar_.initValue(initMeanEffB0bar_fbar); meanEffB0bar_fbar_.genValue(initMeanEffB0bar_fbar); extraVars.push_back(meanEffB0bar_fbar_); Double_t initMeanEffB0_fbar = sigModelB0_fbar_->getMeanEff().initValue(); meanEffB0_fbar_.value(initMeanEffB0_fbar); meanEffB0_fbar_.initValue(initMeanEffB0_fbar); meanEffB0_fbar_.genValue(initMeanEffB0_fbar); extraVars.push_back(meanEffB0_fbar_); // Also add in the DP rates Double_t initDPRateB0bar_f = sigModelB0bar_f_->getDPRate().initValue(); DPRateB0bar_f_.value(initDPRateB0bar_f); DPRateB0bar_f_.initValue(initDPRateB0bar_f); DPRateB0bar_f_.genValue(initDPRateB0bar_f); extraVars.push_back(DPRateB0bar_f_); Double_t initDPRateB0_f = sigModelB0_f_->getDPRate().initValue(); DPRateB0_f_.value(initDPRateB0_f); DPRateB0_f_.initValue(initDPRateB0_f); DPRateB0_f_.genValue(initDPRateB0_f); extraVars.push_back(DPRateB0_f_); Double_t initDPRateB0bar_fbar = sigModelB0bar_fbar_->getDPRate().initValue(); DPRateB0bar_fbar_.value(initDPRateB0bar_fbar); DPRateB0bar_fbar_.initValue(initDPRateB0bar_fbar); DPRateB0bar_fbar_.genValue(initDPRateB0bar_fbar); extraVars.push_back(DPRateB0bar_fbar_); Double_t initDPRateB0_fbar = sigModelB0_fbar_->getDPRate().initValue(); DPRateB0_fbar_.value(initDPRateB0_fbar); DPRateB0_fbar_.initValue(initDPRateB0_fbar); DPRateB0_fbar_.genValue(initDPRateB0_fbar); extraVars.push_back(DPRateB0_fbar_); } void LauTimeDepNonFlavModel::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_B0f_B0barfbar_[i]->finaliseValues(); coeffPars_B0fbar_B0barf_[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 for (LauTagCatDtPdfMap::iterator iter = signalDecayTimePdfs_.begin(); iter != signalDecayTimePdfs_.end(); ++iter) { LauDecayTimePdf* pdf = (*iter).second; pdf->updatePulls(); } if (useSinCos_) { cosPhiMix_.updatePull(); sinPhiMix_.updatePull(); } else { this->checkMixingPhase(); } // Update the pulls on all the extra PDFs' parameters for (LauTagCatPdfMap::iterator iter = sigExtraPdf_.begin(); iter != sigExtraPdf_.end(); ++iter) { this->updateFitParameters(iter->second); } // Tagging-category fractions for signal and background events Double_t firstCatFrac(1.0); Int_t firstCat(0); for (LauTagCatParamMap::iterator iter = signalTagCatFrac_.begin(); iter != signalTagCatFrac_.end(); ++iter) { if (iter == signalTagCatFrac_.begin()) { firstCat = iter->first; continue; } LauParameter& par = (*iter).second; firstCatFrac -= par.value(); // update the parameter pull par.updatePull(); } signalTagCatFrac_[firstCat].value(firstCatFrac); signalTagCatFrac_[firstCat].updatePull(); // 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_f_->updateCoeffs(coeffsB0bar_f_); sigModelB0bar_f_->calcExtraInfo(); sigModelB0_f_->updateCoeffs(coeffsB0_f_); sigModelB0_f_->calcExtraInfo(); sigModelB0bar_fbar_->updateCoeffs(coeffsB0bar_fbar_); sigModelB0bar_fbar_->calcExtraInfo(); sigModelB0_fbar_->updateCoeffs(coeffsB0_fbar_); sigModelB0_fbar_->calcExtraInfo(); LauParArray fitFracB0bar_f = sigModelB0bar_f_->getFitFractions(); if (fitFracB0bar_f.size() != nSigComp_) { std::cerr<<"ERROR in LauTimeDepNonFlavModel::finaliseFitResults : Fit Fraction array of unexpected dimension: "<Exit(EXIT_FAILURE); } for (UInt_t i(0); iExit(EXIT_FAILURE); } } LauParArray fitFracB0_f = sigModelB0_f_->getFitFractions(); if (fitFracB0_f.size() != nSigComp_) { std::cerr<<"ERROR in LauTimeDepNonFlavModel::finaliseFitResults : Fit Fraction array of unexpected dimension: "<Exit(EXIT_FAILURE); } for (UInt_t i(0); iExit(EXIT_FAILURE); } } LauParArray fitFracB0bar_fbar = sigModelB0bar_fbar_->getFitFractions(); if (fitFracB0bar_fbar.size() != nSigComp_) { std::cerr<<"ERROR in LauTimeDepNonFlavModel::finaliseFitResults : Fit Fraction array of unexpected dimension: "<Exit(EXIT_FAILURE); } for (UInt_t i(0); iExit(EXIT_FAILURE); } } LauParArray fitFracB0_fbar = sigModelB0_fbar_->getFitFractions(); if (fitFracB0_fbar.size() != nSigComp_) { std::cerr<<"ERROR in LauTimeDepNonFlavModel::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_f_.value(sigModelB0_f_->getMeanEff().value()); meanEffB0bar_fbar_.value(sigModelB0bar_fbar_->getMeanEff().value()); meanEffB0_fbar_.value(sigModelB0_fbar_->getMeanEff().value()); DPRateB0bar_f_.value(sigModelB0bar_f_->getDPRate().value()); DPRateB0_f_.value(sigModelB0_f_->getDPRate().value()); DPRateB0bar_fbar_.value(sigModelB0bar_fbar_->getDPRate().value()); DPRateB0_fbar_.value(sigModelB0_fbar_->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 LauTimeDepNonFlavModel::printFitFractions(std::ostream& output) { // Print out Fit Fractions, total DP rate and mean efficiency // B0 -> f events for (UInt_t i = 0; i < nSigComp_; i++) { const TString compName(coeffPars_B0f_B0barfbar_[i]->name()); - output<<"B0bar FitFraction for component "< f overall DP rate (integral of matrix element squared) = "< f average efficiency weighted by whole DP dynamics = "< f overall DP rate (integral of matrix element squared) = "< f average efficiency weighted by whole DP dynamics = "< fbar sample for (UInt_t i = 0; i < nSigComp_; i++) { const TString compName(coeffPars_B0f_B0barfbar_[i]->name()); const TString conjName(sigModelB0_f_->getConjResName(compName)); - output<<"B0 FitFraction for component "< fbar overall DP rate (integral of matrix element squared) = "< fbar average efficiency weighted by whole DP dynamics = "< fbar overall DP rate (integral of matrix element squared) = "< fbar average efficiency weighted by whole DP dynamics = "< fbar events for (UInt_t i = 0; i < nSigComp_; i++) { const TString compName(coeffPars_B0fbar_B0barf_[i]->name()); - output<<"B0bar FitFraction for component "< fbar overall DP rate (integral of matrix element squared) = "< fbar average efficiency weighted by whole DP dynamics = "< fbar overall DP rate (integral of matrix element squared) = "< fbar average efficiency weighted by whole DP dynamics = "< f sample for (UInt_t i = 0; i < nSigComp_; i++) { const TString compName(coeffPars_B0fbar_B0barf_[i]->name()); const TString conjName(sigModelB0_fbar_->getConjResName(compName)); - output<<"B0 FitFraction for component "< f overall DP rate (integral of matrix element squared) = "< f average efficiency weighted by whole DP dynamics = "< f overall DP rate (integral of matrix element squared) = "< f average efficiency weighted by whole DP dynamics = "<name()); - output<<"Fit Fraction for B0(B0bar) -> f(fbar) asymmetry for component "< f(fbar) asymmetry for component "< fbar(f) asymmetry for component "< fbar(f) asymmetry for component "< f(fbar) component "<name()); output<<"ACP for B0(B0bar) -> fbar(f) component "<useDP() == kTRUE) { // print the fit coefficients in one table coeffPars_B0f_B0barfbar_.front()->printTableHeading(fout); for (UInt_t i = 0; i < nSigComp_; i++) { coeffPars_B0f_B0barfbar_[i]->printTableRow(fout); } fout<<"\\hline"<printTableHeading(fout); for (UInt_t i = 0; i < nSigComp_; i++) { coeffPars_B0fbar_B0barf_[i]->printTableRow(fout); } fout<<"\\hline"< f(fbar) fout<<"\\begin{tabular}{|l|c|c|c|c|}"< fbar \\ Fit Fraction & \\Bz ->f \\ Fit Fraction & Fit Fraction Asymmetry & $A_{\\CP}$ \\\\"<name(); resName = resName.ReplaceAll("_", "\\_"); fout< =$ & $"; print.printFormat(fout, meanEffB0bar_fbar_.value()); fout << "$ & $"; print.printFormat(fout, meanEffB0_f_.value()); fout << "$ & & \\\\" << std::endl; 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; // Another combination for B0(B0bar) -> fbar(f) fout<<"\\begin{tabular}{|l|c|c|c|c|}"< f \\ Fit Fraction & \\Bz ->fbar \\ Fit Fraction & Fit Fraction Asymmetry & $A_{\\CP}$ \\\\"<name(); resName = resName.ReplaceAll("_", "\\_"); fout< =$ & $"; print.printFormat(fout, meanEffB0bar_f_.value()); fout << "$ & $"; print.printFormat(fout, meanEffB0_fbar_.value()); fout << "$ & & \\\\" << std::endl; 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(iter->second, 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 LauTimeDepNonFlavModel::randomiseInitFitPars() { // Only randomise those parameters that are not fixed! std::cout<<"INFO in LauTimeDepNonFlavModel::randomiseInitFitPars : Randomising the initial values of the coefficients of the DP components (and phiMix)..."<randomiseInitValues(); coeffPars_B0fbar_B0barf_[i]->randomiseInitValues(); } phiMix_.randomiseValue(-LauConstants::pi, LauConstants::pi); if (useSinCos_) { sinPhiMix_.initValue(TMath::Sin(phiMix_.initValue())); cosPhiMix_.initValue(TMath::Cos(phiMix_.initValue())); } } LauTimeDepNonFlavModel::LauGenInfo LauTimeDepNonFlavModel::eventsToGenerate() { // TODO : Check whether in this bit we keep the same procedure or not // 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; LauTagCatGenInfo eventsB0, eventsB0bar; // 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 ); } Double_t sigAsym(0.0); if (this->useDP() == kFALSE) { sigAsym = signalAsym_->genValue(); for (LauTagCatParamMap::const_iterator iter = signalTagCatFrac_.begin(); iter != signalTagCatFrac_.end(); ++iter) { const LauParameter& par = iter->second; Double_t eventsbyTagCat = par.value() * nEvts; Double_t eventsB0byTagCat = TMath::Nint(eventsbyTagCat/2.0 * (1.0 - sigAsym)); Double_t eventsB0barbyTagCat = TMath::Nint(eventsbyTagCat/2.0 * (1.0 + sigAsym)); if (this->doPoissonSmearing()) { eventsB0byTagCat = LauRandom::randomFun()->Poisson(eventsB0byTagCat); eventsB0barbyTagCat = LauRandom::randomFun()->Poisson(eventsB0barbyTagCat); } eventsB0[iter->first] = std::make_pair( TMath::Nint(eventsB0byTagCat), evtWeight ); eventsB0bar[iter->first] = std::make_pair( TMath::Nint(eventsB0barbyTagCat), evtWeight ); } nEvtsGen[std::make_pair("signal",-1)] = eventsB0; nEvtsGen[std::make_pair("signal",+1)] = eventsB0bar; } else { Double_t rateB0bar = sigModelB0bar_f_->getDPRate().value(); Double_t rateB0 = sigModelB0_f_->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. } std::cout<<"INFO in LauTimeDepNonFlavModel::eventsToGenerate : Generating toy MC with:"<setGenNtupleIntegerBranchValue("genSig",1); // 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 { genOK = kFALSE; } 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_); this->setGenNtupleIntegerBranchValue("tagCat",curEvtTagCat_); this->setGenNtupleIntegerBranchValue("tagFlv",curEvtTagFlv_); // 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 LauTimeDepNonFlavModel::genExpt : Generated event number "<useDP() && genOK) { sigModelB0bar_f_->checkToyMC(kTRUE); sigModelB0_f_->checkToyMC(kTRUE); sigModelB0bar_fbar_->checkToyMC(kTRUE); sigModelB0_fbar_->checkToyMC(kTRUE); std::cout<<"aSqMaxSet = "<Exit(EXIT_FAILURE); } for (UInt_t i(0); iExit(EXIT_FAILURE); } } LauParArray fitFracB0_f = sigModelB0_f_->getFitFractions(); if (fitFracB0_f.size() != nSigComp_) { std::cerr<<"ERROR in LauTimeDepNonFlavModel::generate : Fit Fraction array of unexpected dimension: "<Exit(EXIT_FAILURE); } for (UInt_t i(0); iExit(EXIT_FAILURE); } } LauParArray fitFracB0bar_fbar = sigModelB0bar_fbar_->getFitFractions(); if (fitFracB0bar_fbar.size() != nSigComp_) { std::cerr<<"ERROR in LauTimeDepNonFlavModel::generate : Fit Fraction array of unexpected dimension: "<Exit(EXIT_FAILURE); } for (UInt_t i(0); iExit(EXIT_FAILURE); } } LauParArray fitFracB0_fbar = sigModelB0_fbar_->getFitFractions(); if (fitFracB0_fbar.size() != nSigComp_) { std::cerr<<"ERROR in LauTimeDepNonFlavModel::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_f_.value(sigModelB0_f_->getMeanEff().value()); meanEffB0bar_fbar_.value(sigModelB0bar_fbar_->getMeanEff().value()); meanEffB0_fbar_.value(sigModelB0_fbar_->getMeanEff().value()); DPRateB0bar_f_.value(sigModelB0bar_f_->getDPRate().value()); DPRateB0_f_.value(sigModelB0_f_->getDPRate().value()); DPRateB0bar_fbar_.value(sigModelB0bar_fbar_->getDPRate().value()); DPRateB0_fbar_.value(sigModelB0_fbar_->getDPRate().value()); } } // If we're reusing embedded events or if the generation is being // reset then clear the lists of used events //if (!signalTree_.empty() && (reuseSignal_ || !genOK)) { if (reuseSignal_ || !genOK) { for(LauTagCatEmbDataMap::const_iterator iter = signalTree_.begin(); iter != signalTree_.end(); ++iter) { (iter->second)->clearUsedList(); } } return genOK; } Bool_t LauTimeDepNonFlavModel::generateSignalEvent() { // Generate signal event, including SCF if necessary. // DP:DecayTime generation follows. // If it's ok, we then generate mES, DeltaE, Fisher/NN... Bool_t genOK(kTRUE); Bool_t generatedEvent(kFALSE); Bool_t doSquareDP = kinematicsB0bar_f_->squareDP(); doSquareDP &= kinematicsB0_f_->squareDP(); doSquareDP &= kinematicsB0bar_fbar_->squareDP(); doSquareDP &= kinematicsB0_fbar_->squareDP(); LauKinematics* kinematics = 0; //(kinematicsB0bar_); // find the right decay time PDF for the current tagging category LauTagCatDtPdfMap::const_iterator dt_iter = signalDecayTimePdfs_.find(curEvtTagCat_); LauDecayTimePdf* decayTimePdf = (dt_iter != signalDecayTimePdfs_.end()) ? dt_iter->second : 0; // find the right embedded data for the current tagging category LauTagCatEmbDataMap::const_iterator emb_iter = signalTree_.find(curEvtTagCat_); LauEmbeddedData* embeddedData = (emb_iter != signalTree_.end()) ? emb_iter->second : 0; // find the right extra PDFs for the current tagging category LauTagCatPdfMap::iterator extra_iter = sigExtraPdf_.find(curEvtTagCat_); LauPdfPList* extraPdfs = (extra_iter != sigExtraPdf_.end()) ? &(extra_iter->second) : 0; if (this->useDP()) { if (embeddedData) { // TODO : correct the kinematic term to the two possible final state // This option is not allowed in the moment kinematics = kinematicsB0bar_f_; embeddedData->getEmbeddedEvent(kinematics); curEvtTagFlv_ = TMath::Nint(embeddedData->getValue("tagFlv")); curEvtDecayTimeErr_ = embeddedData->getValue(decayTimePdf->varErrName()); curEvtDecayTime_ = embeddedData->getValue(decayTimePdf->varName()); if (embeddedData->haveBranch("mcMatch")) { Int_t match = TMath::Nint(embeddedData->getValue("mcMatch")); if (match) { this->setGenNtupleIntegerBranchValue("genTMSig",1); this->setGenNtupleIntegerBranchValue("genSCFSig",0); } else { this->setGenNtupleIntegerBranchValue("genTMSig",0); this->setGenNtupleIntegerBranchValue("genSCFSig",1); } } } else { nGenLoop_ = 0; // generate the decay time error (NB the kTRUE forces the generation of a new value) curEvtDecayTimeErr_ = decayTimePdf->generateError(kTRUE); while (generatedEvent == kFALSE && nGenLoop_ < iterationsMax_) { // Calculate the unnormalised truth-matched signal likelihood // First let define the tag flavour Double_t randNo = LauRandom::randomFun()->Rndm(); if (randNo < 0.5) { curEvtTagFlv_ = +1; // B0 tag } else { curEvtTagFlv_ = -1; // B0bar tag } // Calculate event quantities that depend only on the tagCat and tagFlv qD_ = curEvtTagFlv_*dilution_[curEvtTagCat_].unblindValue(); qDDo2_ = curEvtTagFlv_*0.5*deltaDilution_[curEvtTagCat_].unblindValue(); // Generate decay time const Double_t tMin = decayTimePdf->minAbscissa(); const Double_t tMax = decayTimePdf->maxAbscissa(); curEvtDecayTime_ = LauRandom::randomFun()->Rndm()*(tMax-tMin) + tMin; // Calculate all the decay time info decayTimePdf->calcLikelihoodInfo(curEvtDecayTime_, curEvtDecayTimeErr_); // Calculate the relevant amplitude normalisation for the two DP's this->calculateAmplitudeNorm(decayTimePdf); // DP variables Double_t m13Sq(0.0), m23Sq(0.0); Double_t randNo_finalState = LauRandom::randomFun()->Rndm(); if (randNo_finalState < normTimeDP_f_/(normTimeDP_f_+normTimeDP_fbar_)) { finalState_ = +1; // A(Abar) -> f // Generate DP position kinematicsB0bar_f_->genFlatPhaseSpace(m13Sq, m23Sq); kinematicsB0_f_->updateKinematics(kinematicsB0bar_f_->getm13Sq(), kinematicsB0bar_f_->getm23Sq() ); // Calculate the total A and Abar for the given DP position sigModelB0_f_->calcLikelihoodInfo(m13Sq, m23Sq); sigModelB0bar_f_->calcLikelihoodInfo(m13Sq, m23Sq); // Calculate DP terms this->calculateDPterms(decayTimePdf, sigModelB0bar_f_, sigModelB0_f_); } else { finalState_ = -1; // A(Abar) -> fbar // Generate DP position kinematicsB0bar_fbar_->genFlatPhaseSpace(m13Sq, m23Sq); kinematicsB0_fbar_->updateKinematics(kinematicsB0bar_fbar_->getm13Sq(), kinematicsB0bar_fbar_->getm23Sq() ); // Calculate the total A and Abar for the given DP position sigModelB0_fbar_->calcLikelihoodInfo(m13Sq, m23Sq); sigModelB0bar_fbar_->calcLikelihoodInfo(m13Sq, m23Sq); // Calculate DP terms this->calculateDPterms(decayTimePdf, sigModelB0bar_fbar_, sigModelB0_fbar_); } //Finally we throw the dice to see whether this event should be generated //We make a distinction between the likelihood of TM and SCF to tag the SCF events as such randNo = LauRandom::randomFun()->Rndm(); if (randNo <= ASq_/aSqMaxSet_ ) { generatedEvent = kTRUE; nGenLoop_ = 0; if (ASq_ > aSqMaxVar_) {aSqMaxVar_ = ASq_;} } else { nGenLoop_++; } } // end of while !generatedEvent loop } // end of if (embeddedData) else control } else { if ( embeddedData ) { embeddedData->getEmbeddedEvent(0); curEvtTagFlv_ = TMath::Nint(embeddedData->getValue("tagFlv")); curEvtDecayTimeErr_ = embeddedData->getValue(decayTimePdf->varErrName()); curEvtDecayTime_ = embeddedData->getValue(decayTimePdf->varName()); } } // Check whether we have generated the toy MC OK. if (nGenLoop_ >= iterationsMax_) { aSqMaxSet_ = 1.01 * aSqMaxVar_; genOK = kFALSE; std::cerr<<"WARNING in LauTimeDepNonFlavModel::generateSignalEvent : Hit max iterations: setting aSqMaxSet_ to "< aSqMaxSet_) { aSqMaxSet_ = 1.01 * aSqMaxVar_; genOK = kFALSE; std::cerr<<"WARNING in LauTimeDepNonFlavModel::generateSignalEvent : Found a larger ASq value: setting aSqMaxSet_ to "<generateExtraPdfValues(extraPdfs, embeddedData); } // Check for problems with the embedding if (embeddedData && (embeddedData->nEvents() == embeddedData->nUsedEvents())) { std::cerr<<"WARNING in LauTimeDepNonFlavModel::generateSignalEvent : Source of embedded signal events used up, clearing the list of used events."<clearUsedList(); } return genOK; } void LauTimeDepNonFlavModel::calculateDPterms(LauDecayTimePdf* decayTimePdf, LauIsobarDynamics* sigModelB0bar, LauIsobarDynamics* sigModelB0) { // Retrieve the amplitudes and efficiency from the dynamics const LauComplex& Abar = sigModelB0bar->getEvtDPAmp(); const LauComplex& A = sigModelB0->getEvtDPAmp(); Double_t eff = sigModelB0bar->getEvtEff(); // Calculate the DP terms Double_t aSqSum = A.abs2() + Abar.abs2(); Double_t aSqDif = A.abs2() - Abar.abs2(); LauComplex inter = Abar * A.conj() * phiMixComplex_; Double_t interTermIm = 2.0 * inter.im(); Double_t interTermRe = 2.0 * inter.re(); // Decay time pdf terms Double_t dtCos = decayTimePdf->getCosTerm(); Double_t dtSin = decayTimePdf->getSinTerm(); Double_t dtCosh = decayTimePdf->getCoshTerm(); Double_t dtSinh = decayTimePdf->getSinhTerm(); // Combine all terms Double_t cosTerm = dtCos * qD_ * aSqDif; Double_t sinTerm = dtSin * qD_ * interTermIm; Double_t coshTerm = dtCosh * (1.0 + qDDo2_) * aSqSum; Double_t sinhTerm = dtSinh * (1.0 + qDDo2_) * interTermRe; if ( cpEigenValue_ == CPOdd ) { sinTerm *= -1.0; sinhTerm *= -1.0; } // Total amplitude and multiply by the efficiency ASq_ = coshTerm + cosTerm - sinTerm + sinhTerm; ASq_ *= eff; } void LauTimeDepNonFlavModel::calculateAmplitudeNorm(LauDecayTimePdf* decayTimePdf) { // Integrals of the sum of the ampltudes to the f(fbar) integral( |A|^2 + |Abar|^2 ) dP Double_t normTermNonDep_f = sigModelB0bar_f_->getDPNorm() + sigModelB0_f_->getDPNorm(); Double_t normTermNonDep_fbar = sigModelB0bar_fbar_->getDPNorm() + sigModelB0_fbar_->getDPNorm(); // Integrals of cross terms |Abar|*|Aconj| Double_t normTermDep_f = interTermReNorm_f_; Double_t normTermDep_fbar = interTermReNorm_fbar_; // Decay time constant integrals Double_t normTermCosh = decayTimePdf->getNormTermCosh(); Double_t normTermSinh = decayTimePdf->getNormTermSinh(); // Time-dependent DP normalisation terms normTimeDP_f_ = normTermNonDep_f*normTermCosh + normTermDep_f*normTermSinh; normTimeDP_fbar_ = normTermNonDep_fbar*normTermCosh + normTermDep_fbar*normTermSinh; } void LauTimeDepNonFlavModel::setupGenNtupleBranches() { // Setup the required ntuple branches this->addGenNtupleDoubleBranch("evtWeight"); this->addGenNtupleIntegerBranch("genSig"); this->addGenNtupleIntegerBranch("cpEigenvalue"); this->addGenNtupleIntegerBranch("tagFlv"); this->addGenNtupleIntegerBranch("tagCat"); if (this->useDP() == kTRUE) { // Let's add the decay time variables. if (signalDecayTimePdfs_.begin() != signalDecayTimePdfs_.end()) { LauDecayTimePdf* pdf = signalDecayTimePdfs_.begin()->second; this->addGenNtupleDoubleBranch(pdf->varName()); this->addGenNtupleDoubleBranch(pdf->varErrName()); } this->addGenNtupleDoubleBranch("m12_f"); this->addGenNtupleDoubleBranch("m23_f"); this->addGenNtupleDoubleBranch("m13_f"); this->addGenNtupleDoubleBranch("m12Sq_f"); this->addGenNtupleDoubleBranch("m23Sq_f"); this->addGenNtupleDoubleBranch("m13Sq_f"); this->addGenNtupleDoubleBranch("cosHel12_f"); this->addGenNtupleDoubleBranch("cosHel23_f"); this->addGenNtupleDoubleBranch("cosHel13_f"); if (kinematicsB0bar_f_->squareDP() && kinematicsB0_f_->squareDP()) { this->addGenNtupleDoubleBranch("mPrime_f"); this->addGenNtupleDoubleBranch("thPrime_f"); } this->addGenNtupleDoubleBranch("m12_fbar"); this->addGenNtupleDoubleBranch("m23_fbar"); this->addGenNtupleDoubleBranch("m13_fbar"); this->addGenNtupleDoubleBranch("m12Sq_fbar"); this->addGenNtupleDoubleBranch("m23Sq_fbar"); this->addGenNtupleDoubleBranch("m13Sq_fbar"); this->addGenNtupleDoubleBranch("cosHel12_fbar"); this->addGenNtupleDoubleBranch("cosHel23_fbar"); this->addGenNtupleDoubleBranch("cosHel13_fbar"); if (kinematicsB0bar_fbar_->squareDP() && kinematicsB0_fbar_->squareDP()) { this->addGenNtupleDoubleBranch("mPrime_fbar"); this->addGenNtupleDoubleBranch("thPrime_fbar"); } // 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("reB0fAmp"); this->addGenNtupleDoubleBranch("imB0fAmp"); this->addGenNtupleDoubleBranch("reB0barfAmp"); this->addGenNtupleDoubleBranch("imB0barfAmp"); this->addGenNtupleDoubleBranch("reB0fbarAmp"); this->addGenNtupleDoubleBranch("imB0fbarAmp"); this->addGenNtupleDoubleBranch("reB0barfbarAmp"); this->addGenNtupleDoubleBranch("imB0barfbarAmp"); } } // Let's look at the extra variables for signal in one of the tagging categories if ( ! sigExtraPdf_.empty() ) { const LauPdfPList& oneTagCatPdfList { sigExtraPdf_.begin()->second }; for ( const LauAbsPdf* pdf : oneTagCatPdfList ) { const std::vector varNames{ pdf->varNames() }; for ( const TString& varName : varNames ) { if ( varName != "m13Sq" && varName != "m23Sq" ) { this->addGenNtupleDoubleBranch( varName ); } } } } } void LauTimeDepNonFlavModel::setDPDtBranchValues() { // Store the decay time variables. if (signalDecayTimePdfs_.begin() != signalDecayTimePdfs_.end()) { LauDecayTimePdf* pdf = signalDecayTimePdfs_.begin()->second; this->setGenNtupleDoubleBranchValue(pdf->varName(),curEvtDecayTime_); this->setGenNtupleDoubleBranchValue(pdf->varErrName(),curEvtDecayTimeErr_); } LauKinematics* kinematics_f(0); LauKinematics* kinematics_fbar(0); if (curEvtTagFlv_<0) { kinematics_f = kinematicsB0_f_; kinematics_fbar = kinematicsB0_fbar_; } else { kinematics_f = kinematicsB0bar_f_; kinematics_fbar = kinematicsB0bar_fbar_; } // Store all the DP information this->setGenNtupleDoubleBranchValue("m12_f", kinematics_f->getm12()); this->setGenNtupleDoubleBranchValue("m23_f", kinematics_f->getm23()); this->setGenNtupleDoubleBranchValue("m13_f", kinematics_f->getm13()); this->setGenNtupleDoubleBranchValue("m12Sq_f", kinematics_f->getm12Sq()); this->setGenNtupleDoubleBranchValue("m23Sq_f", kinematics_f->getm23Sq()); this->setGenNtupleDoubleBranchValue("m13Sq_f", kinematics_f->getm13Sq()); this->setGenNtupleDoubleBranchValue("cosHel12_f", kinematics_f->getc12()); this->setGenNtupleDoubleBranchValue("cosHel23_f", kinematics_f->getc23()); this->setGenNtupleDoubleBranchValue("cosHel13_f", kinematics_f->getc13()); if (kinematics_f->squareDP()) { this->setGenNtupleDoubleBranchValue("mPrime_f", kinematics_f->getmPrime()); this->setGenNtupleDoubleBranchValue("thPrime_f", kinematics_f->getThetaPrime()); } this->setGenNtupleDoubleBranchValue("m12_fbar", kinematics_fbar->getm12()); this->setGenNtupleDoubleBranchValue("m23_fbar", kinematics_fbar->getm23()); this->setGenNtupleDoubleBranchValue("m13_fbar", kinematics_fbar->getm13()); this->setGenNtupleDoubleBranchValue("m12Sq_fbar", kinematics_fbar->getm12Sq()); this->setGenNtupleDoubleBranchValue("m23Sq_fbar", kinematics_fbar->getm23Sq()); this->setGenNtupleDoubleBranchValue("m13Sq_fbar", kinematics_fbar->getm13Sq()); this->setGenNtupleDoubleBranchValue("cosHel12_fbar", kinematics_fbar->getc12()); this->setGenNtupleDoubleBranchValue("cosHel23_fbar", kinematics_fbar->getc23()); this->setGenNtupleDoubleBranchValue("cosHel13_fbar", kinematics_fbar->getc13()); if (kinematics_fbar->squareDP()) { this->setGenNtupleDoubleBranchValue("mPrime_fbar", kinematics_fbar->getmPrime()); this->setGenNtupleDoubleBranchValue("thPrime_fbar", kinematics_fbar->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_f = sigModelB0bar_f_->getEvtDPAmp(); LauComplex A_f = sigModelB0_f_->getEvtDPAmp(); LauComplex Abar_fbar = sigModelB0bar_fbar_->getEvtDPAmp(); LauComplex A_fbar = sigModelB0_fbar_->getEvtDPAmp(); this->setGenNtupleDoubleBranchValue("reB0fAmp", A_f.re()); this->setGenNtupleDoubleBranchValue("imB0fAmp", A_f.im()); this->setGenNtupleDoubleBranchValue("reB0barfAmp", Abar_f.re()); this->setGenNtupleDoubleBranchValue("imB0barfAmp", Abar_f.im()); this->setGenNtupleDoubleBranchValue("reB0fbarAmp", A_fbar.re()); this->setGenNtupleDoubleBranchValue("imB0fbarAmp", A_fbar.im()); this->setGenNtupleDoubleBranchValue("reB0barfbarAmp", Abar_fbar.re()); this->setGenNtupleDoubleBranchValue("imB0barfbarAmp", Abar_fbar.im()); } else { this->setGenNtupleDoubleBranchValue("reB0fAmp", 0.0); this->setGenNtupleDoubleBranchValue("imB0fAmp", 0.0); this->setGenNtupleDoubleBranchValue("reB0barfAmp", 0.0); this->setGenNtupleDoubleBranchValue("imB0barfAmp", 0.0); this->setGenNtupleDoubleBranchValue("reB0fbarAmp", 0.0); this->setGenNtupleDoubleBranchValue("imB0fbarAmp", 0.0); this->setGenNtupleDoubleBranchValue("reB0barfbarAmp", 0.0); this->setGenNtupleDoubleBranchValue("imB0barfbarAmp", 0.0); } } } void LauTimeDepNonFlavModel::generateExtraPdfValues(LauPdfPList* extraPdfs, LauEmbeddedData* embeddedData) { // TODO : need to add the additional DP LauKinematics* kinematics_f(0); //LauKinematics* kinematics_fbar(0); if (curEvtTagFlv_<0) { kinematics_f = kinematicsB0_f_; //kinematics_fbar = kinematicsB0_fbar_; } else { kinematics_f = kinematicsB0bar_f_; //kinematics_fbar = kinematicsB0bar_fbar_; } // Generate from the extra PDFs if (extraPdfs) { for (LauPdfPList::iterator pdf_iter = extraPdfs->begin(); pdf_iter != extraPdfs->end(); ++pdf_iter) { LauFitData genValues; if (embeddedData) { genValues = embeddedData->getValues( (*pdf_iter)->varNames() ); } else { genValues = (*pdf_iter)->generate(kinematics_f); } for ( LauFitData::const_iterator var_iter = genValues.begin(); var_iter != genValues.end(); ++var_iter ) { TString varName = var_iter->first; if ( varName != "m13Sq" && varName != "m23Sq" ) { Double_t value = var_iter->second; this->setGenNtupleDoubleBranchValue(varName,value); } } } } } void LauTimeDepNonFlavModel::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_f_->updateCoeffs(coeffsB0bar_f_); sigModelB0_f_->updateCoeffs(coeffsB0_f_); sigModelB0bar_fbar_->updateCoeffs(coeffsB0bar_fbar_); sigModelB0_fbar_->updateCoeffs(coeffsB0_fbar_); this->calcInterTermNorm(); } // Update the signal events from the background numbers if not doing an extended fit if (!this->doEMLFit()) { this->updateSigEvents(); } } void LauTimeDepNonFlavModel::updateSigEvents() { // The background parameters will have been set from Minuit. // We need to update the signal events using these. Double_t nTotEvts = this->eventsPerExpt(); Double_t signalEvents = nTotEvts; // tagging-category fractions for signal events this->setFirstTagCatFrac(signalTagCatFrac_); signalEvents_->range(-2.0*nTotEvts,2.0*nTotEvts); if ( ! signalEvents_->fixed() ) { signalEvents_->value(signalEvents); } } void LauTimeDepNonFlavModel::setFirstTagCatFrac(LauTagCatParamMap& theMap) { Double_t firstCatFrac = 1.0; Int_t firstCat(0); for (LauTagCatParamMap::iterator iter = theMap.begin(); iter != theMap.end(); ++iter) { if (iter == theMap.begin()) { firstCat = iter->first; continue; } LauParameter& par = iter->second; firstCatFrac -= par.unblindValue(); } theMap[firstCat].value(firstCatFrac); } void LauTimeDepNonFlavModel::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(); // Start by caching the tagging and CP-eigenstate information evtTagCatVals_.clear(); evtTagFlvVals_.clear(); evtCPEigenVals_.clear(); if ( ! inputFitData->haveBranch( tagCatVarName_ ) ) { std::cerr << "ERROR in LauTimeDepNonFlavModel::cacheInputFitVars : Input data does not contain branch \"" << tagCatVarName_ << "\"." << std::endl; gSystem->Exit(EXIT_FAILURE); } if ( ! inputFitData->haveBranch( tagVarName_ ) ) { std::cerr << "ERROR in LauTimeDepNonFlavModel::cacheInputFitVars : Input data does not contain branch \"" << tagVarName_ << "\"." << std::endl; gSystem->Exit(EXIT_FAILURE); } const Bool_t hasCPEV = ( (cpevVarName_ != "") && inputFitData->haveBranch( cpevVarName_ ) ); UInt_t nEvents = inputFitData->nEvents(); evtTagCatVals_.reserve( nEvents ); evtTagFlvVals_.reserve( nEvents ); evtCPEigenVals_.reserve( nEvents ); LauFitData::const_iterator fitdata_iter; for (UInt_t iEvt = 0; iEvt < nEvents; iEvt++) { const LauFitData& dataValues = inputFitData->getData(iEvt); fitdata_iter = dataValues.find( tagCatVarName_ ); curEvtTagCat_ = static_cast( fitdata_iter->second ); if ( ! this->validTagCat( curEvtTagCat_ ) ) { std::cerr << "WARNING in LauTimeDepNonFlavModel::cacheInputFitVars : Invalid tagging category " << curEvtTagCat_ << " for event " << iEvt << ", setting it to untagged" << std::endl; curEvtTagCat_ = 0; } evtTagCatVals_.push_back( curEvtTagCat_ ); fitdata_iter = dataValues.find( tagVarName_ ); curEvtTagFlv_ = static_cast( fitdata_iter->second ); if ( TMath::Abs( curEvtTagFlv_ ) != 1 ) { if ( curEvtTagFlv_ > 0 ) { std::cerr << "WARNING in LauTimeDepNonFlavModel::cacheInputFitVars : Invalid tagging output " << curEvtTagFlv_ << " for event " << iEvt << ", setting it to +1" << std::endl; curEvtTagFlv_ = +1; } else { std::cerr << "WARNING in LauTimeDepNonFlavModel::cacheInputFitVars : Invalid tagging output " << curEvtTagFlv_ << " for event " << iEvt << ", setting it to -1" << std::endl; curEvtTagFlv_ = -1; } } evtTagFlvVals_.push_back( curEvtTagFlv_ ); // 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 { std::cerr<<"WARNING in LauTimeDepNonFlavModel::cacheInputFitVars : Unknown value: "<useDP() == kTRUE) { // DecayTime and SigmaDecayTime for (LauTagCatDtPdfMap::iterator dt_iter = signalDecayTimePdfs_.begin(); dt_iter != signalDecayTimePdfs_.end(); ++dt_iter) { (*dt_iter).second->cacheInfo(*inputFitData); } } // ...and then the extra PDFs for (LauTagCatPdfMap::iterator pdf_iter = sigExtraPdf_.begin(); pdf_iter != sigExtraPdf_.end(); ++pdf_iter) { this->cacheInfo(pdf_iter->second, *inputFitData); } if (this->useDP() == kTRUE) { sigModelB0bar_f_->fillDataTree(*inputFitData); sigModelB0_f_->fillDataTree(*inputFitData); sigModelB0bar_fbar_->fillDataTree(*inputFitData); sigModelB0_fbar_->fillDataTree(*inputFitData); } } Double_t LauTimeDepNonFlavModel::getTotEvtLikelihood(const UInt_t iEvt) { // Find out whether the tag-side B was a B0 or a B0bar. curEvtTagFlv_ = evtTagFlvVals_[iEvt]; // Also get the tagging category. curEvtTagCat_ = evtTagCatVals_[iEvt]; // Get the CP eigenvalue of the current event cpEigenValue_ = evtCPEigenVals_[iEvt]; // Get the DP and DecayTime likelihood for signal this->getEvtDPDtLikelihood(iEvt); // Get the combined extra PDFs likelihood for signal this->getEvtExtraLikelihoods(iEvt); // Construct the total likelihood for signal, qqbar and BBbar backgrounds Double_t sigLike = sigDPLike_ * sigExtraLike_; Double_t signalEvents = signalEvents_->unblindValue(); if (this->useDP() == kFALSE) { signalEvents *= 0.5 * (1.0 + curEvtTagFlv_ * signalAsym_->unblindValue()); } // Construct the total event likelihood Double_t likelihood(sigLike*signalTagCatFrac_[curEvtTagCat_].unblindValue()); if ( ! signalEvents_->fixed() ) { likelihood *= signalEvents; } return likelihood; } Double_t LauTimeDepNonFlavModel::getEventSum() const { Double_t eventSum(0.0); eventSum += signalEvents_->unblindValue(); return eventSum; } void LauTimeDepNonFlavModel::getEvtDPDtLikelihood(const UInt_t iEvt) { // Function to return the signal and background likelihoods for the // Dalitz plot for the given event evtNo. sigDPLike_ = 1.0; //There's always a likelihood term for signal, so we better not zero it. if ( this->useDP() == kFALSE ) { return; } // Mistag probabilities. Defined as: omega = prob of the tagging B0 being reported as B0bar // Whether we want omega or omegaBar depends on q_tag, hence curEvtTagFlv_*... in the previous lines //Double_t misTagFrac = 0.5 * (1.0 - dilution_[curEvtTagCat_] - qDDo2); //Double_t misTagFracBar = 0.5 * (1.0 - dilution_[curEvtTagCat_] + qDDo2); // Calculate event quantities qD_ = curEvtTagFlv_*dilution_[curEvtTagCat_].unblindValue(); qDDo2_ = curEvtTagFlv_*0.5*deltaDilution_[curEvtTagCat_].unblindValue(); //LauDecayTimePdf* signalDtPdf = signalDecayTimePdfs_[curEvtTagCat_]; LauDecayTimePdf* decayTimePdf = signalDecayTimePdfs_[curEvtTagCat_]; decayTimePdf->calcLikelihoodInfo(static_cast(iEvt)); // Calculate the relevant amplitude normalisation for the two DP's this->calculateAmplitudeNorm(decayTimePdf); Double_t randNo = LauRandom::randomFun()->Rndm(); if (randNo < normTimeDP_f_/(normTimeDP_f_+normTimeDP_fbar_)) { finalState_ = +1; // A(Abar) -> f // Calculate the likelihood for the f final state sigModelB0bar_f_->calcLikelihoodInfo(iEvt); sigModelB0_f_->calcLikelihoodInfo(iEvt); // Calculate DP terms this->calculateDPterms(decayTimePdf, sigModelB0bar_f_, sigModelB0_f_); } else { finalState_ = -1; // A(Abar) -> fbar // Calculate the likelihood for the fbar final state sigModelB0bar_fbar_->calcLikelihoodInfo(iEvt); sigModelB0_fbar_->calcLikelihoodInfo(iEvt); // Calculate DP terms this->calculateDPterms(decayTimePdf, sigModelB0bar_fbar_, sigModelB0_fbar_); } // Calculate the normalised signal likelihood sigDPLike_ = ASq_ / (normTimeDP_f_+normTimeDP_fbar_); } void LauTimeDepNonFlavModel::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 LauTagCatPdfMap::iterator sig_iter = sigExtraPdf_.find(curEvtTagCat_); LauPdfPList* pdfList = (sig_iter != sigExtraPdf_.end())? &(sig_iter->second) : 0; if (pdfList) { sigExtraLike_ = this->prodPdfValue( *pdfList, iEvt ); } } void LauTimeDepNonFlavModel::updateCoeffs() { coeffsB0bar_f_.clear(); coeffsB0_f_.clear(); coeffsB0bar_fbar_.clear(); coeffsB0_fbar_.clear(); coeffsB0bar_f_.reserve(nSigComp_); coeffsB0_f_.reserve(nSigComp_); coeffsB0bar_fbar_.reserve(nSigComp_); coeffsB0_fbar_.reserve(nSigComp_); for (UInt_t i = 0; i < nSigComp_; ++i) { coeffsB0bar_f_.push_back(coeffPars_B0fbar_B0barf_[i]->antiparticleCoeff()); coeffsB0_f_.push_back(coeffPars_B0f_B0barfbar_[i]->particleCoeff()); coeffsB0bar_fbar_.push_back(coeffPars_B0f_B0barfbar_[i]->antiparticleCoeff()); coeffsB0_fbar_.push_back(coeffPars_B0fbar_B0barf_[i]->particleCoeff()); } } Bool_t LauTimeDepNonFlavModel::validTagCat(Int_t tagCat) const { return (validTagCats_.find(tagCat) != validTagCats_.end()); } Bool_t LauTimeDepNonFlavModel::checkTagCatFracMap(const LauTagCatParamMap& theMap) const { // First check that there is an entry for each tagging category. // NB an entry won't have been added if it isn't a valid category // so don't need to check for that here. if (theMap.size() != signalTagCatFrac_.size()) { std::cerr<<"ERROR in LauTimeDepNonFlavModel::checkTagCatFracMap : Not all tagging categories present."< 1E-10) { std::cerr<<"ERROR in LauTimeDepNonFlavModel::checkTagCatFracMap : Tagging category event fractions do not sum to unity."< -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 LauTimeDepNonFlavModel::embedSignal(Int_t tagCat, const TString& fileName, const TString& treeName, Bool_t reuseEventsWithinEnsemble, Bool_t reuseEventsWithinExperiment) { if (signalTree_[tagCat]) { std::cerr<<"ERROR in LauTimeDepNonFlavModel::embedSignal : Already embedding signal from file for tagging category "<findBranches(); if (!dataOK) { delete signalTree_[tagCat]; signalTree_[tagCat] = 0; std::cerr<<"ERROR in LauTimeDepNonFlavModel::embedSignal : Problem creating data tree for embedding."<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"); // Store the DP likelihoods if (this->useDP()) { this->addSPlotNtupleDoubleBranch("sigDPLike"); } // Store the likelihoods for each extra PDF const LauPdfPList* pdfList( &(sigExtraPdf_.begin()->second) ); this->addSPlotNtupleBranches(pdfList, "sig"); } void LauTimeDepNonFlavModel::addSPlotNtupleBranches(const LauPdfPList* extraPdfs, const TString& prefix) { if (!extraPdfs) { return; } // 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 varName = pdf->varName(); TString name(prefix); name += 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 ) { 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 LauTimeDepNonFlavModel::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 varName = pdf->varName(); TString name(prefix); name += 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"; 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"); } LauPdfPList pdfList( (sigExtraPdf_.begin()->second) ); for ( const LauAbsPdf* pdf : pdfList ) { // 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 LauTimeDepNonFlavModel::freeSpeciesNames() const { LauSPlot::NumbMap numbMap; if (!signalEvents_->fixed() && this->doEMLFit()) { numbMap["sig"] = signalEvents_->genValue(); } return numbMap; } LauSPlot::NumbMap LauTimeDepNonFlavModel::fixdSpeciesNames() const { LauSPlot::NumbMap numbMap; if (signalEvents_->fixed() && this->doEMLFit()) { numbMap["sig"] = signalEvents_->genValue(); } return numbMap; } LauSPlot::TwoDMap LauTimeDepNonFlavModel::twodimPDFs() const { LauSPlot::TwoDMap twodimMap; const LauPdfPList& pdfList { sigExtraPdf_.begin()->second }; for ( const LauAbsPdf* pdf : pdfList ) { // 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] ) ) ); } } return twodimMap; } void LauTimeDepNonFlavModel::storePerEvtLlhds() { std::cout<<"INFO in LauTimeDepNonFlavModel::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_f_->initialise(coeffsB0bar_f_); sigModelB0_f_->initialise(coeffsB0_f_); sigModelB0bar_fbar_->initialise(coeffsB0bar_fbar_); sigModelB0_fbar_->initialise(coeffsB0_fbar_); sigModelB0bar_f_->fillDataTree(*inputFitData); sigModelB0_f_->fillDataTree(*inputFitData); sigModelB0bar_fbar_->fillDataTree(*inputFitData); sigModelB0_fbar_->fillDataTree(*inputFitData); } UInt_t evtsPerExpt(this->eventsPerExpt()); LauIsobarDynamics* sigModel(sigModelB0bar_f_); for (UInt_t iEvt = 0; iEvt < evtsPerExpt; ++iEvt) { // Find out whether we have B0bar or B0 curEvtTagFlv_ = evtTagFlvVals_[iEvt]; curEvtTagCat_ = evtTagCatVals_[iEvt]; LauTagCatPdfMap::iterator sig_iter = sigExtraPdf_.find(curEvtTagCat_); LauPdfPList* sigPdfs = (sig_iter != sigExtraPdf_.end())? &(sig_iter->second) : 0; // 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_); } else { sigTotalLike_ = 1.0; } // the signal PDF values sigTotalLike_ *= this->setSPlotNtupleBranchValues(sigPdfs, "sig", iEvt); // the total likelihoods this->setSPlotNtupleDoubleBranchValue("sigTotalLike",sigTotalLike_); // fill the tree this->fillSPlotNtupleBranches(); } std::cout<<"INFO in LauTimeDepNonFlavModel::storePerEvtLlhds : Finished storing per-event likelihood values."< + +#include +#include +#include + +int main() +{ + /* + const std::string filename {"coeffset.json"}; + std::ifstream in(filename, std::ios_base::in); + if ( not in ) { + std::cerr << "ERROR : couldn't open file \"" << filename << "\"" << std::endl; + return 1; + } + + nlohmann::json j; + in >> j; + + std::cout << j.dump(4) << std::endl; + + auto coeffset = j.get(); + for ( const LauParameter* par : coeffset.getParameters() ) { + std::cout << *par << std::endl; + } + */ + + + std::vector> coeffs { LauAbsCoeffSet::readFromJson( "coeffset.json" ) }; + + std::cout << "Read " << coeffs.size() << " coeffs from file" << std::endl; + + for ( const auto& coeff : coeffs ) { + std::cout << coeff->type() << std::endl; + } +} diff --git a/test/TestWriteCoeffSetToJson.cc b/test/TestWriteCoeffSetToJson.cc new file mode 100644 index 0000000..283e19d --- /dev/null +++ b/test/TestWriteCoeffSetToJson.cc @@ -0,0 +1,53 @@ +#include "LauAbsCoeffSet.hh" +#include "LauBelleCPCoeffSet.hh" +#include "LauCartesianCPCoeffSet.hh" +#include "LauCartesianGammaCPCoeffSet.hh" +#include "LauCleoCPCoeffSet.hh" +#include "LauMagPhaseCoeffSet.hh" +#include "LauMagPhaseCPCoeffSet.hh" +#include "LauNSCCartesianCPCoeffSet.hh" +#include "LauPolarGammaCPCoeffSet.hh" +#include "LauRealImagCoeffSet.hh" +#include "LauRealImagCPCoeffSet.hh" +#include "LauRealImagGammaCPCoeffSet.hh" + +#include + +#include +#include +#include + +int main() +{ + std::vector> coeffs; + coeffs.push_back( std::make_unique("K*0(892)", 1.00, 0.00, 0.00, 0.00, kTRUE, kTRUE, kTRUE, kTRUE, kTRUE, kTRUE) ); + coeffs.push_back( std::make_unique("K*0(892)", 1.00, 0.00, 0.00, 0.00, kTRUE, kTRUE, kTRUE, kTRUE, kTRUE, kTRUE) ); + coeffs.push_back( std::make_unique("K*0(892)", 1.00, 0.00, 0.00, 0.00, 0.00, 0.00, kTRUE, kTRUE, kTRUE, kTRUE, kTRUE, kTRUE, kTRUE, kTRUE) ); + coeffs.push_back( std::make_unique("K*0(892)", 1.00, 0.00, 0.00, 0.00, kTRUE, kTRUE, kTRUE, kTRUE, kTRUE, kTRUE) ); + coeffs.push_back( std::make_unique("K*0(892)", 1.00, 0.00, kTRUE, kTRUE) ); + coeffs.push_back( std::make_unique("K*0(892)", 1.00, 0.00, 1.00, 0.00, kTRUE, kTRUE, kTRUE, kTRUE) ); + coeffs.push_back( std::make_unique("K*0(892)", kTRUE, 1.00, 0.00, 0.00, 0.00, kTRUE, kTRUE, kTRUE, kTRUE, kTRUE, kTRUE, 1.00, 0.00, 0.00, 0.00, kTRUE, kTRUE, kTRUE, kTRUE, kTRUE, kTRUE) ); + coeffs.push_back( std::make_unique("K*0(892)", LauPolarGammaCPCoeffSet::DecayType::ADS_Favoured, 1.00, 0.00, 0.10, 0.00, 1.20, 0.10, 1.60, kTRUE, kTRUE, kTRUE, kTRUE, kTRUE, kTRUE, kTRUE, kTRUE, kTRUE, kTRUE, kTRUE, kTRUE, kTRUE, kTRUE) ); + coeffs.push_back( std::make_unique("K*0(892)", 1.00, 0.00, kTRUE, kTRUE) ); + coeffs.push_back( std::make_unique("K*0(892)", 1.00, 0.00, 1.00, 0.00, kTRUE, kTRUE, kTRUE, kTRUE) ); + coeffs.push_back( std::make_unique("K*0(892)", 1.00, 0.00, 0.00, 0.00, 0.00, 0.00, kTRUE, kTRUE, kTRUE, kTRUE, kTRUE, kTRUE) ); + + LauAbsCoeffSet::writeToJson( "coeffset.json", coeffs ); + + for ( auto& coeffset : coeffs ) { + + nlohmann::json j; + + j = *coeffset; + + const std::string filename {j.at("type").get()+".json"}; + std::ofstream out{filename, std::ios_base::out}; + if ( ! out ) { + std::cerr << "ERROR : couldn't open file \"" << filename << "\" for writing. No file will be written!" << std::endl; + return 1; + } + + out << j.dump(4); + out << std::endl; + } +}