diff --git a/ThirdParty/RootMinimizers/inc/Fit/BinData.h b/ThirdParty/RootMinimizers/inc/Fit/BinData.h index 7f978dea96fac4df60d79054d929b11c9acb4842..14d2cd2f582c5aaebcd6a194adf5206df3e67b74 100644 --- a/ThirdParty/RootMinimizers/inc/Fit/BinData.h +++ b/ThirdParty/RootMinimizers/inc/Fit/BinData.h @@ -27,44 +27,44 @@ #endif -namespace ROOT { +namespace ROOT { - namespace Fit { + namespace Fit { //___________________________________________________________________________________ -/** - Class describing the binned data sets : - vectors of x coordinates, y values and optionally error on y values and error on coordinates +/** + Class describing the binned data sets : + vectors of x coordinates, y values and optionally error on y values and error on coordinates The dimension of the coordinate is free - There are 4 different options: - - only coordinates and values (for binned likelihood fits) : kNoError + There are 4 different options: + - only coordinates and values (for binned likelihood fits) : kNoError - coordinate, values and error on values (for normal least square fits) : kValueError - coordinate, values, error on values and coordinates (for effective least square fits) : kCoordError - corrdinate, values, error on coordinates and asymmettric error on valyes : kAsymError - In addition there is the option to construct Bindata copying the data in (using the DataVector class) - or using pointer to external data (DataWrapper) class. - In general is found to be more efficient to copy the data. + In addition there is the option to construct Bindata copying the data in (using the DataVector class) + or using pointer to external data (DataWrapper) class. + In general is found to be more efficient to copy the data. In case of really large data sets for limiting memory consumption then the other option can be used - Specialized constructor exists for data up to 3 dimensions. + Specialized constructor exists for data up to 3 dimensions. - When the data are copying in the number of points can be set later (or re-set) using Initialize and - the data are inserted one by one using the Add method. - It is mandatory to set the size before using the Add method. + When the data are copying in the number of points can be set later (or re-set) using Initialize and + the data are inserted one by one using the Add method. + It is mandatory to set the size before using the Add method. - @ingroup FitData -*/ + @ingroup FitData +*/ -class BinData : public FitData { +class BinData : public FitData { -public : +public : enum ErrorType { kNoError, kValueError, kCoordError, kAsymError }; - static unsigned int GetPointSize(ErrorType err, unsigned int dim) { + static unsigned int GetPointSize(ErrorType err, unsigned int dim) { if (dim == 0 || dim > MaxSize() ) return 0; if (err == kNoError) return dim + 1; // no errors if (err == kValueError) return dim + 2; // error only on the value @@ -72,22 +72,22 @@ public : return 2 * dim + 3; // error on value (low and high) and error on coordinate } - ErrorType GetErrorType() const { - if (fPointSize == fDim + 1) return kNoError; - if (fPointSize == fDim + 2) return kValueError; - if (fPointSize == 2 * fDim + 2) return kCoordError; - assert( fPointSize == 2 * fDim + 3 ) ; - return kAsymError; + ErrorType GetErrorType() const { + if (fPointSize == fDim + 1) return kNoError; + if (fPointSize == fDim + 2) return kValueError; + if (fPointSize == 2 * fDim + 2) return kCoordError; + assert( fPointSize == 2 * fDim + 3 ) ; + return kAsymError; } - + /** constructor from dimension of point and max number of points (to pre-allocate vector) Give a zero value and then use Initialize later one if the size is not known */ - explicit BinData(unsigned int maxpoints = 0, unsigned int dim = 1, ErrorType err = kValueError); + explicit BinData(unsigned int maxpoints = 0, unsigned int dim = 1, ErrorType err = kValueError); /** constructor from option and default range @@ -98,19 +98,19 @@ public : constructor from options and range efault is 1D and value errors */ - BinData (const DataOptions & opt, const DataRange & range, unsigned int maxpoints = 0, unsigned int dim = 1, ErrorType err = kValueError ); + BinData (const DataOptions & opt, const DataRange & range, unsigned int maxpoints = 0, unsigned int dim = 1, ErrorType err = kValueError ); /** constructurs using external data */ - + /** constructor from external data for 1D with errors on coordinate and value */ - BinData(unsigned int n, const double * dataX, const double * val, const double * ex , const double * eval ); - + BinData(unsigned int n, const double * dataX, const double * val, const double * ex , const double * eval ); + /** constructor from external data for 2D with errors on coordinate and value */ - BinData(unsigned int n, const double * dataX, const double * dataY, const double * val, const double * ex , const double * ey, const double * eval ); + BinData(unsigned int n, const double * dataX, const double * dataY, const double * val, const double * ex , const double * ey, const double * eval ); /** constructor from external data for 3D with errors on coordinate and value @@ -118,61 +118,61 @@ public : BinData(unsigned int n, const double * dataX, const double * dataY, const double * dataZ, const double * val, const double * ex , const double * ey , const double * ez , const double * eval ); /** - copy constructors + copy constructors */ BinData(const BinData &); - /** - assignment operator - */ + /** + assignment operator + */ BinData & operator= (const BinData &); /** destructor */ - virtual ~BinData(); + virtual ~BinData(); /** preallocate a data set with given size , dimension and error type (to get the full point size) - If the data set already exists and it is having the compatible point size space for the new points - is created in the data sets, while if not compatible the old data are erased and new space of - new size is allocated. - (i.e if exists initialize is equivalent to a resize( NPoints() + maxpoints) + If the data set already exists and it is having the compatible point size space for the new points + is created in the data sets, while if not compatible the old data are erased and new space of + new size is allocated. + (i.e if exists initialize is equivalent to a resize( NPoints() + maxpoints) */ - void Initialize(unsigned int maxpoints, unsigned int dim = 1, ErrorType err = kValueError ); + void Initialize(unsigned int maxpoints, unsigned int dim = 1, ErrorType err = kValueError ); /** - return the size of a fit point (is the coordinate dimension + 1 for the value and eventually + return the size of a fit point (is the coordinate dimension + 1 for the value and eventually the number of all errors */ - unsigned int PointSize() const { - return fPointSize; + unsigned int PointSize() const { + return fPointSize; } /** return the size of internal data (number of fit points) if data are not copied in but used externally the size is 0 */ - unsigned int DataSize() const { - if (fDataVector) return fDataVector->Size(); - return 0; + unsigned int DataSize() const { + if (fDataVector) return fDataVector->Size(); + return 0; } /** flag to control if data provides error on the coordinates */ - bool HaveCoordErrors() const { - if (fPointSize > fDim +2) return true; + bool HaveCoordErrors() const { + if (fPointSize > fDim +2) return true; return false; } /** flag to control if data provides asymmetric errors on the value */ - bool HaveAsymErrors() const { - if (fPointSize > 2 * fDim +2) return true; + bool HaveAsymErrors() const { + if (fPointSize > 2 * fDim +2) return true; return false; } @@ -180,7 +180,7 @@ public : /** add one dim data with only coordinate and values */ - void Add(double x, double y ); + void Add(double x, double y ); /** add one dim data with no error in the coordinate (x) @@ -190,98 +190,98 @@ public : /** add one dim data with error in the coordinate (x) - in this case store the value (y) error and not the inverse + in this case store the value (y) error and not the inverse */ void Add(double x, double y, double ex, double ey); /** add one dim data with error in the coordinate (x) and asymmetric errors in the value (y) - in this case store the y errors and not the inverse + in this case store the y errors and not the inverse */ void Add(double x, double y, double ex, double eyl , double eyh); /** add multi-dim coordinate data with only value (no errors) */ - void Add(const double *x, double val); + void Add(const double *x, double val); /** - add multi-dim coordinate data with only error in value + add multi-dim coordinate data with only error in value */ - void Add(const double *x, double val, double eval); + void Add(const double *x, double val, double eval); /** - add multi-dim coordinate data with both error in coordinates and value + add multi-dim coordinate data with both error in coordinates and value */ - void Add(const double *x, double val, const double * ex, double eval); + void Add(const double *x, double val, const double * ex, double eval); /** - add multi-dim coordinate data with both error in coordinates and value + add multi-dim coordinate data with both error in coordinates and value */ - void Add(const double *x, double val, const double * ex, double elval, double ehval); + void Add(const double *x, double val, const double * ex, double elval, double ehval); /** - return a pointer to the coordinates data for the given fit point + return a pointer to the coordinates data for the given fit point */ - const double * Coords(unsigned int ipoint) const { - if (fDataVector) + const double * Coords(unsigned int ipoint) const { + if (fDataVector) return &((fDataVector->Data())[ ipoint*fPointSize ] ); - + return fDataWrapper->Coords(ipoint); } /** return the value for the given fit point */ - double Value(unsigned int ipoint) const { - if (fDataVector) + double Value(unsigned int ipoint) const { + if (fDataVector) return (fDataVector->Data())[ ipoint*fPointSize + fDim ]; - + return fDataWrapper->Value(ipoint); } /** return error on the value for the given fit point - Safe (but slower) method returning correctly the error on the value + Safe (but slower) method returning correctly the error on the value in case of asymm errors return the average 0.5(eu + el) - */ - double Error(unsigned int ipoint) const { - if (fDataVector) { - ErrorType type = GetErrorType(); - if (type == kNoError ) return 1; + */ + double Error(unsigned int ipoint) const { + if (fDataVector) { + ErrorType type = GetErrorType(); + if (type == kNoError ) return 1; // error on the value is the last element in the point structure double eval = (fDataVector->Data())[ (ipoint+1)*fPointSize - 1]; - if (type == kValueError ) // need to invert (inverror is stored) - return eval != 0 ? 1.0/eval : 0; - else if (type == kAsymError) { // return 1/2(el + eh) + if (type == kValueError ) // need to invert (inverror is stored) + return eval != 0 ? 1.0/eval : 0; + else if (type == kAsymError) { // return 1/2(el + eh) double el = (fDataVector->Data())[ (ipoint+1)*fPointSize - 2]; - return 0.5 * (el+eval); + return 0.5 * (el+eval); } return eval; // case of coord errors } return fDataWrapper->Error(ipoint); - } + } /** Return the inverse of error on the value for the given fit point - useful when error in the coordinates are not stored and then this is used directly this as the weight in + useful when error in the coordinates are not stored and then this is used directly this as the weight in the least square function */ double InvError(unsigned int ipoint) const { - if (fDataVector) { + if (fDataVector) { // error on the value is the last element in the point structure double eval = (fDataVector->Data())[ (ipoint+1)*fPointSize - 1]; - return eval; -// if (!fWithCoordError) return eval; -// // when error in the coordinate is stored, need to invert it -// return eval != 0 ? 1.0/eval : 0; + return eval; +// if (!fWithCoordError) return eval; +// // when error in the coordinate is stored, need to invert it +// return eval != 0 ? 1.0/eval : 0; } - //case data wrapper + //case data wrapper double eval = fDataWrapper->Error(ipoint); - return eval != 0 ? 1.0/eval : 0; + return eval != 0 ? 1.0/eval : 0; } @@ -289,7 +289,7 @@ public : Return a pointer to the errors in the coordinates for the given fit point */ const double * CoordErrors(unsigned int ipoint) const { - if (fDataVector) { + if (fDataVector) { // error on the value is the last element in the point structure return &(fDataVector->Data())[ (ipoint)*fPointSize + fDim + 1]; } @@ -302,25 +302,25 @@ public : More efficient than calling Coords(i) and Value(i) */ const double * GetPoint(unsigned int ipoint, double & value) const { - if (fDataVector) { + if (fDataVector) { unsigned int j = ipoint*fPointSize; const std::vector<double> & v = (fDataVector->Data()); const double * x = &v[j]; value = v[j+fDim]; return x; - } + } value = fDataWrapper->Value(ipoint); return fDataWrapper->Coords(ipoint); } /** - retrieve in a single call a pointer to the coordinate data, value and inverse error for - the given fit point. - To be used only when type is kValueError or kNoError. In the last case the value 1 is returned - for the error. + retrieve in a single call a pointer to the coordinate data, value and inverse error for + the given fit point. + To be used only when type is kValueError or kNoError. In the last case the value 1 is returned + for the error. */ const double * GetPoint(unsigned int ipoint, double & value, double & invError) const { - if (fDataVector) { + if (fDataVector) { const std::vector<double> & v = (fDataVector->Data()); unsigned int j = ipoint*fPointSize; const double * x = &v[j]; @@ -330,46 +330,46 @@ public : invError = 1; else if (fPointSize == fDim +2) // value error (type=kNoError) invError = v[j+1]; - else + else assert(0); // cannot be here return x; - } + } value = fDataWrapper->Value(ipoint); double e = fDataWrapper->Error(ipoint); - invError = ( e > 0 ) ? 1.0/e : 1.0; + invError = ( e > 0 ) ? 1.0/e : 1.0; return fDataWrapper->Coords(ipoint); } /** Retrieve the errors on the point (coordinate and value) for the given fit point - It must be called only when the coordinate errors are stored otherwise it will produce an + It must be called only when the coordinate errors are stored otherwise it will produce an assert. */ const double * GetPointError(unsigned int ipoint, double & errvalue) const { - if (fDataVector) { - assert(fPointSize > fDim + 2); + if (fDataVector) { + assert(fPointSize > fDim + 2); unsigned int j = ipoint*fPointSize; const std::vector<double> & v = (fDataVector->Data()); const double * ex = &v[j+fDim+1]; errvalue = v[j + 2*fDim +1]; return ex; - } + } errvalue = fDataWrapper->Error(ipoint); return fDataWrapper->CoordErrors(ipoint); } /** - Get errors on the point (coordinate errors and asymmetric value errors) for the - given fit point. - It must be called only when the coordinate errors and asymmetric errors are stored + Get errors on the point (coordinate errors and asymmetric value errors) for the + given fit point. + It must be called only when the coordinate errors and asymmetric errors are stored otherwise it will produce an assert. */ const double * GetPointError(unsigned int ipoint, double & errlow, double & errhigh) const { // external data is not supported for asymmetric errors - assert(fDataVector); + assert(fDataVector); - assert(fPointSize > 2 * fDim + 2); + assert(fPointSize > 2 * fDim + 2); unsigned int j = ipoint*fPointSize; const std::vector<double> & v = (fDataVector->Data()); const double * ex = &v[j+fDim+1]; @@ -380,8 +380,8 @@ public : #ifdef USE_BINPOINT_CLASS - const BinPoint & GetPoint(unsigned int ipoint) const { - if (fDataVector) { + const BinPoint & GetPoint(unsigned int ipoint) const { + if (fDataVector) { unsigned int j = ipoint*fPointSize; const std::vector<double> & v = (fDataVector->Data()); const double * x = &v[j]; @@ -390,87 +390,87 @@ public : const double * ex = &v[j+fDim+1]; double err = v[j + 2*fDim +1]; fPoint.Set(x,value,ex,err); - } + } else { double invError = v[j+fDim+1]; fPoint.Set(x,value,invError); } - } - else { + } + else { double value = fDataWrapper->Value(ipoint); double e = fDataWrapper->Error(ipoint); if (fPointSize > fDim + 2) { fPoint.Set(fDataWrapper->Coords(ipoint), value, fDataWrapper->CoordErrors(ipoint), e); - } else { - double invError = ( e != 0 ) ? 1.0/e : 0; + } else { + double invError = ( e != 0 ) ? 1.0/e : 0; fPoint.Set(fDataWrapper->Coords(ipoint), value, invError); } } - return fPoint; - } + return fPoint; + } - const BinPoint & GetPointError(unsigned int ipoint) const { - if (fDataVector) { + const BinPoint & GetPointError(unsigned int ipoint) const { + if (fDataVector) { unsigned int j = ipoint*fPointSize; const std::vector<double> & v = (fDataVector->Data()); const double * x = &v[j]; double value = v[j+fDim]; double invError = v[j+fDim+1]; fPoint.Set(x,value,invError); - } - else { + } + else { double value = fDataWrapper->Value(ipoint); double e = fDataWrapper->Error(ipoint); - double invError = ( e != 0 ) ? 1.0/e : 0; + double invError = ( e != 0 ) ? 1.0/e : 0; fPoint.Set(fDataWrapper->Coords(ipoint), value, invError); } - return fPoint; - } + return fPoint; + } #endif /** resize the vector to the new given npoints if vector does not exists is created using existing point size */ - void Resize (unsigned int npoints); + void Resize (unsigned int npoints); /** return number of fit points */ - unsigned int NPoints() const { return fNPoints; } + unsigned int NPoints() const { return fNPoints; } /** - return number of fit points - */ + return number of fit points + */ unsigned int Size() const { return fNPoints; } /** return coordinate data dimension */ - unsigned int NDim() const { return fDim; } + unsigned int NDim() const { return fDim; } /** - apply a Log transformation of the data values + apply a Log transformation of the data values can be used for example when fitting an exponential or gaussian Transform the data in place need to copy if want to preserve original data - The data sets must not contain negative values. IN case it does, + The data sets must not contain negative values. IN case it does, an empty data set is returned */ BinData & LogTransform(); - /** + /** return an array containing the upper edge of the bin for coordinate i In case of empty bin they could be merged in a single larger bin - Return a NULL pointer if the bin width is not stored + Return a NULL pointer if the bin width is not stored */ - const double * BinUpEdge(unsigned int icoord) const { - if (fBinEdge.size() == 0 || icoord*fDim > fBinEdge.size() ) return 0; + const double * BinUpEdge(unsigned int icoord) const { + if (fBinEdge.size() == 0 || icoord*fDim > fBinEdge.size() ) return 0; return &fBinEdge[ icoord * fDim]; } - + /** query if the data store the bin edges instead of the center */ @@ -478,17 +478,17 @@ public : return fBinEdge.size() > 0 && fBinEdge.size() == fDim*fNPoints; } - /** + /** add the bin width data, a pointer to an array with the bin upper edge information. This is needed when fitting with integral options - The information is added for the previously inserted point. + The information is added for the previously inserted point. BinData::Add must be called before */ - void AddBinUpEdge(const double * xup); + void AddBinUpEdge(const double * xup); - /** + /** retrieve the reference volume used to normalize the data when the option bin volume is set - */ + */ double RefVolume() const { return fRefVolume; } /** @@ -501,42 +501,42 @@ public : compute the total sum of the data content (sum of weights in cse of weighted data set) */ - double SumOfContent() const { return fSumContent; } + double SumOfContent() const { return fSumContent; } /** compute the total sum of the error square (sum of weight square in case of a weighted data set) */ double SumOfError2() const { return fSumError2;} - -protected: + +protected: void SetNPoints(unsigned int n) { fNPoints = n; } -private: +private: unsigned int fDim; // coordinate dimension - unsigned int fPointSize; // total point size including value and errors (= fDim + 2 for error in only Y ) + unsigned int fPointSize; // total point size including value and errors (= fDim + 2 for error in only Y ) unsigned int fNPoints; // number of contained points in the data set (can be different than size of vector) - double fSumContent; // total sum of the bin data content + double fSumContent; // total sum of the bin data content double fSumError2; // total sum square of the errors double fRefVolume; // reference bin volume - used to normalize the bins in case of variable bins data DataVector * fDataVector; // pointer to the copied in data vector DataWrapper * fDataWrapper; // pointer to the external data wrapper structure - std::vector<double> fBinEdge; // vector containing the bin upper edge (coordinate will contain low edge) + std::vector<double> fBinEdge; // vector containing the bin upper edge (coordinate will contain low edge) #ifdef USE_BINPOINT_CLASS - mutable BinPoint fPoint; + mutable BinPoint fPoint; #endif -}; +}; + - } // end namespace Fit } // end namespace ROOT diff --git a/ThirdParty/RootMinimizers/inc/Fit/BinPoint.h b/ThirdParty/RootMinimizers/inc/Fit/BinPoint.h index 40182cfae4d94c8a176c6a777f496693f1f63c8d..ade5045f5e1034de763b8863bf9625315a6c6d0e 100644 --- a/ThirdParty/RootMinimizers/inc/Fit/BinPoint.h +++ b/ThirdParty/RootMinimizers/inc/Fit/BinPoint.h @@ -16,36 +16,36 @@ -namespace ROOT { +namespace ROOT { - namespace Fit { + namespace Fit { - class DataRange; + class DataRange; -/** +/** Obsolete class, no more in use. - class describing the point with bins ( x coordinates, y and error on y ) + class describing the point with bins ( x coordinates, y and error on y ) but not error in X . For the Error in x one should use onother class - -*/ + +*/ class BinPoint { -public: +public: + - - //typedef std::vector<double> CoordData; + //typedef std::vector<double> CoordData; - /** + /** Constructor - */ - explicit BinPoint (unsigned int n = 1) : + */ + explicit BinPoint (unsigned int n = 1) : fDim(n), - fCoords(0 ), + fCoords(0 ), fCoordErr( 0), - fValue(0), + fValue(0), fError(1), fInvError(1) {} @@ -53,50 +53,50 @@ public: // /** // constructor from a vector of coordinates, y value and y error // */ -// BinPoint (const std::vector<double> & x, double y, double ey = 1) : -// fCoords(x), -// fValue(y), +// BinPoint (const std::vector<double> & x, double y, double ey = 1) : +// fCoords(x), +// fValue(y), // fInvError( ey!= 0 ? 1.0/ey : 0 ) // { } - -// template <class Iterator> -// BinPoint (const Iterator begin, const Iterator end, double y, double ey = 1) : -// fCoords(begin,end), -// fValue(y), + +// template <class Iterator> +// BinPoint (const Iterator begin, const Iterator end, double y, double ey = 1) : +// fCoords(begin,end), +// fValue(y), // fInvError( ey!= 0. ? 1.0/ey : 1. ) // { } - void Set(const double * x, double value, double invErr) { - fCoords = x; - fValue = value; + void Set(const double * x, double value, double invErr) { + fCoords = x; + fValue = value; fInvError = invErr; } - void Set(const double * x, double value, const double * ex, double err) { - fCoords = x; + void Set(const double * x, double value, const double * ex, double err) { + fCoords = x; fValue = value; - fCoordErr = ex; + fCoordErr = ex; fError = err; } - /** + /** Destructor (no operations) - */ - ~BinPoint () {} + */ + ~BinPoint () {} // use default copy constructor and assignment - // accessors + // accessors /** - return pointer to coordinates + return pointer to coordinates */ //const double * Coords() const { return &fCoords.front(); } /** - return vector of coordinates + return vector of coordinates */ const double * Coords() const { return fCoords; } @@ -106,42 +106,42 @@ public: double Value() const { return fValue; } /** - return the error on the value + return the error on the value */ - double Error() const { - //return fInvError != 0 ? 1.0/fInvError : 0; + double Error() const { + //return fInvError != 0 ? 1.0/fInvError : 0; return fError; - } + } /** - return the inverse of error on the value + return the inverse of error on the value */ double InvError() const { return fInvError; } - /** + /** get the dimension (dimension of the cooordinates) */ unsigned int NDim() const { return fDim; } /** - check if a Point is inside the given range - */ - bool IsInRange( const DataRange & range) const; + check if a Point is inside the given range + */ + bool IsInRange( const DataRange & range) const; -private: +private: unsigned int fDim; //double fCoords[N]; - const double * fCoords; - const double * fCoordErr; - - double fValue; + const double * fCoords; + const double * fCoordErr; + + double fValue; // better to store the inverse of the error (is more efficient) - double fError; - double fInvError; + double fError; + double fInvError; -}; +}; } // end namespace Fit @@ -150,25 +150,25 @@ private: // #ifndef ROOT_Fit_DataRange // #include "Fit/DataRange.h" // #endif -// #include <cassert> +// #include <cassert> -// namespace ROOT { +// namespace ROOT { -// namespace Fit { +// namespace Fit { -// template<unsigned int N> -// bool BinPoint<N>::IsInRange(const DataRange & range) const +// template<unsigned int N> +// bool BinPoint<N>::IsInRange(const DataRange & range) const // { // // check if given point is inside the given range - -// // need to check that datarange size is same as point size -// if (range.NDim() == 0) return true; // (range is empty is equivalent to (-inf, + inf) + +// // need to check that datarange size is same as point size +// if (range.NDim() == 0) return true; // (range is empty is equivalent to (-inf, + inf) // // in case not zero dimension must be equal to the coordinates -// assert( kSize == range.NDim() ); -// for (unsigned int i = 0; i < kSize; ++i) { -// if ( ! range.IsInside( fCoords[i] ) ) return false; +// assert( kSize == range.NDim() ); +// for (unsigned int i = 0; i < kSize; ++i) { +// if ( ! range.IsInside( fCoords[i] ) ) return false; // } -// return true; +// return true; // } // } // end namespace Fit diff --git a/ThirdParty/RootMinimizers/inc/Fit/Chi2FCN.h b/ThirdParty/RootMinimizers/inc/Fit/Chi2FCN.h index d2fb864fd63455a6a3030e2bbf645dbf20dca428..f83caedde519dccf81c1c206594f95e42ca250f6 100644 --- a/ThirdParty/RootMinimizers/inc/Fit/Chi2FCN.h +++ b/ThirdParty/RootMinimizers/inc/Fit/Chi2FCN.h @@ -13,8 +13,8 @@ #ifndef ROOT_Fit_Chi2FCN #define ROOT_Fit_Chi2FCN -#ifndef ROOT_Math_FitMethodFunction -#include "Math/FitMethodFunction.h" +#ifndef ROOT_Fit_BasicFCN +#include "Fit/BasicFCN.h" #endif #ifndef ROOT_Math_IParamFunction @@ -39,155 +39,153 @@ #endif #endif -/** -@defgroup FitMethodFunc Fit Method Classes +#include <memory> + +/** +@defgroup FitMethodFunc Fit Method Classes Classes describing Fit Method functions @ingroup Fit */ -namespace ROOT { +namespace ROOT { - namespace Fit { + namespace Fit { //___________________________________________________________________________________ -/** - Chi2FCN class for binnned fits using the least square methods - - @ingroup FitMethodFunc -*/ -template<class FunType> -class Chi2FCN : public ::ROOT::Math::BasicFitMethodFunction<FunType> { +/** + Chi2FCN class for binnned fits using the least square methods -public: + @ingroup FitMethodFunc +*/ +template<class FunType> +class Chi2FCN : public BasicFCN<FunType,BinData> { +public: + typedef BasicFCN<FunType,BinData> BaseFCN; - typedef ::ROOT::Math::BasicFitMethodFunction<FunType> BaseObjFunction; - typedef typename BaseObjFunction::BaseFunction BaseFunction; + typedef ::ROOT::Math::BasicFitMethodFunction<FunType> BaseObjFunction; + typedef typename BaseObjFunction::BaseFunction BaseFunction; //typedef typename ::ROOT::Math::ParamFunctionTrait<FunType>::PFType IModelFunction; typedef ::ROOT::Math::IParamMultiFunction IModelFunction; typedef typename BaseObjFunction::Type_t Type_t; - /** - Constructor from data set (binned ) and model function - */ - Chi2FCN (const BinData & data, const IModelFunction & func) : - BaseObjFunction(func.NPar(), data.Size() ), - fData(data), - fFunc(func), + /** + Constructor from data set (binned ) and model function + */ + Chi2FCN (const std::shared_ptr<BinData> & data, const std::shared_ptr<IModelFunction> & func) : + BaseFCN( data, func), + fNEffPoints(0), + fGrad ( std::vector<double> ( func->NPar() ) ) + { } + + /** + Same Constructor from data set (binned ) and model function but now managed by the user + we clone the function but not the data + */ + Chi2FCN ( const BinData & data, const IModelFunction & func) : + BaseFCN(std::shared_ptr<BinData>(const_cast<BinData*>(&data), DummyDeleter<BinData>()), std::shared_ptr<IModelFunction>(dynamic_cast<IModelFunction*>(func.Clone() ) ) ), fNEffPoints(0), fGrad ( std::vector<double> ( func.NPar() ) ) { } - /** + /** Destructor (no operations) - */ + */ virtual ~Chi2FCN () {} - -#ifdef LATER -private: - - // usually copying is non trivial, so we make this unaccessible - - /** + /** Copy constructor - */ - Chi2FCN(const Chi2FCN &); + */ + Chi2FCN(const Chi2FCN & f) : + BaseFCN(f.DataPtr(), f.ModelFunctionPtr() ), + fNEffPoints( f.fNEffPoints ), + fGrad( f.fGrad) + { } - /** + /** Assignment operator - */ - Chi2FCN & operator = (const Chi2FCN & rhs); - -#endif -public: - - virtual BaseFunction * Clone() const { - // clone the function - Chi2FCN * fcn = new Chi2FCN(fData,fFunc); - return fcn; + */ + Chi2FCN & operator = (const Chi2FCN & rhs) { + SetData(rhs.DataPtr() ); + SetModelFunction(rhs.ModelFunctionPtr() ); + fNEffPoints = rhs.fNEffPoints; + fGrad = rhs.fGrad; } - + /* + clone the function + */ + virtual BaseFunction * Clone() const { + return new Chi2FCN(*this); + } - using BaseObjFunction::operator(); - // effective points used in the fit (exclude the rejected one) - virtual unsigned int NFitPoints() const { return fNEffPoints; } + using BaseObjFunction::operator(); - /// i-th chi-square residual - virtual double DataElement(const double * x, unsigned int i, double * g) const { + /// i-th chi-square residual + virtual double DataElement(const double * x, unsigned int i, double * g) const { if (i==0) this->UpdateNCalls(); - return FitUtil::EvaluateChi2Residual(fFunc, fData, x, i, g); + return FitUtil::EvaluateChi2Residual(BaseFCN::ModelFunction(), BaseFCN::Data(), x, i, g); } // need to be virtual to be instantiated - virtual void Gradient(const double *x, double *g) const { + virtual void Gradient(const double *x, double *g) const { // evaluate the chi2 gradient - FitUtil::EvaluateChi2Gradient(fFunc, fData, x, g, fNEffPoints); + FitUtil::EvaluateChi2Gradient(BaseFCN::ModelFunction(), BaseFCN::Data(), x, g, fNEffPoints); } /// get type of fit method function virtual typename BaseObjFunction::Type_t Type() const { return BaseObjFunction::kLeastSquare; } - /// access to const reference to the data - virtual const BinData & Data() const { return fData; } - - /// access to const reference to the model function - virtual const IModelFunction & ModelFunction() const { return fFunc; } - - -protected: +protected: - /// set number of fit points (need to be called in const methods, make it const) + /// set number of fit points (need to be called in const methods, make it const) virtual void SetNFitPoints(unsigned int n) const { fNEffPoints = n; } - -private: + +private: /** Evaluation of the function (required by interface) */ - virtual double DoEval (const double * x) const { + virtual double DoEval (const double * x) const { this->UpdateNCalls(); #ifdef ROOT_FIT_PARALLEL - return FitUtilParallel::EvaluateChi2(fFunc, fData, x, fNEffPoints); -#else - if (!fData.HaveCoordErrors() ) - return FitUtil::EvaluateChi2(fFunc, fData, x, fNEffPoints); - else - return FitUtil::EvaluateChi2Effective(fFunc, fData, x, fNEffPoints); + return FitUtilParallel::EvaluateChi2(BaseFCN::ModelFunction(), BaseFCN::Data(), x, fNEffPoints); +#else + if (!BaseFCN::Data().HaveCoordErrors() ) + return FitUtil::EvaluateChi2(BaseFCN::ModelFunction(), BaseFCN::Data(), x, fNEffPoints); + else + return FitUtil::EvaluateChi2Effective(BaseFCN::ModelFunction(), BaseFCN::Data(), x, fNEffPoints); #endif - } + } - // for derivatives - virtual double DoDerivative(const double * x, unsigned int icoord ) const { - Gradient(x, &fGrad[0]); - return fGrad[icoord]; + // for derivatives + virtual double DoDerivative(const double * x, unsigned int icoord ) const { + Gradient(x, fGrad.data()); + return fGrad[icoord]; } - const BinData & fData; - const IModelFunction & fFunc; - mutable unsigned int fNEffPoints; // number of effective points used in the fit + mutable unsigned int fNEffPoints; // number of effective points used in the fit mutable std::vector<double> fGrad; // for derivatives -}; +}; // define useful typedef's - typedef Chi2FCN<ROOT::Math::IMultiGenFunction> Chi2Function; - typedef Chi2FCN<ROOT::Math::IMultiGradFunction> Chi2GradFunction; + typedef Chi2FCN<ROOT::Math::IMultiGenFunction> Chi2Function; + typedef Chi2FCN<ROOT::Math::IMultiGradFunction> Chi2GradFunction; } // end namespace Fit diff --git a/ThirdParty/RootMinimizers/inc/Fit/DataOptions.h b/ThirdParty/RootMinimizers/inc/Fit/DataOptions.h index 473e2e1c078e29229b41b95d5199a1ef1277c2e5..ca249d1680e600bfe30690f03033c8786fb73f84 100644 --- a/ThirdParty/RootMinimizers/inc/Fit/DataOptions.h +++ b/ThirdParty/RootMinimizers/inc/Fit/DataOptions.h @@ -14,28 +14,29 @@ #define ROOT_Fit_DataOptions -namespace ROOT { +namespace ROOT { - namespace Fit { + namespace Fit { //___________________________________________________________________________________ -/** - DataOptions : simple structure holding the options on how the data are filled +/** + DataOptions : simple structure holding the options on how the data are filled @ingroup FitData -*/ +*/ struct DataOptions { - /** + /** Default constructor: use the default options - */ - DataOptions () : - fIntegral(false), + */ + DataOptions () : + fIntegral(false), fBinVolume(false), - fUseEmpty(false), - fUseRange(false), + fNormBinVolume(false), + fUseEmpty(false), + fUseRange(false), fErrors1(false), fExpErrors(false), fCoordErrors(true), @@ -45,15 +46,16 @@ struct DataOptions { bool fIntegral; // use integral of bin content instead of bin center (default is false) bool fBinVolume; // normalize data by the bin volume (it is used in the Poisson likelihood fits) + bool fNormBinVolume; // normalize data by a normalized the bin volume ( bin volume divided by a reference value) bool fUseEmpty; // use empty bins (default is false) with a fixed error of 1 bool fUseRange; // use the function range when creating the fit data (default is false) - bool fErrors1; // use all errors equal to 1, i.e. fit without errors (default is false) - bool fExpErrors; // use expected errors from the function and not from the data + bool fErrors1; // use all errors equal to 1, i.e. fit without errors (default is false) + bool fExpErrors; // use expected errors from the function and not from the data bool fCoordErrors; // use errors on the x coordinates when available (default is true) bool fAsymErrors; // use asymmetric errors in the value when available, selecting them according to the on sign of residual (default is true) -}; +}; } // end namespace Fit diff --git a/ThirdParty/RootMinimizers/inc/Fit/DataRange.h b/ThirdParty/RootMinimizers/inc/Fit/DataRange.h index 5db35e05a196dd1833e6f49f4e3721269111966d..4a2cdd2219928b9468a1aee7d8ed42c600b5f8de 100644 --- a/ThirdParty/RootMinimizers/inc/Fit/DataRange.h +++ b/ThirdParty/RootMinimizers/inc/Fit/DataRange.h @@ -15,96 +15,96 @@ #include <vector> -namespace ROOT { +namespace ROOT { - namespace Fit { + namespace Fit { //___________________________________________________________________________________ -/** - class describing the range in the coordinates - it supports multiple range in a coordinate. - The rnage dimension is the dimension of the coordinate, its size is - the number of interval for each coordinate. +/** + class describing the range in the coordinates + it supports multiple range in a coordinate. + The rnage dimension is the dimension of the coordinate, its size is + the number of interval for each coordinate. Default range is -inf, inf Range can be modified with the add range method @ingroup FitData -*/ +*/ class DataRange { -public: +public: typedef std::vector<std::pair<double,double> > RangeSet; - typedef std::vector< RangeSet > RangeIntervals; + typedef std::vector< RangeSet > RangeIntervals; - /** - Default constructor (infinite range) - */ + /** + Default constructor (infinite range) + */ explicit DataRange (unsigned int dim = 1) : fRanges ( std::vector<RangeSet> (dim) ) {} /** - construct a range for [xmin, xmax] + construct a range for [xmin, xmax] */ - DataRange(double xmin, double xmax); + DataRange(double xmin, double xmax); /** - construct a range for [xmin, xmax] , [ymin, ymax] + construct a range for [xmin, xmax] , [ymin, ymax] */ - DataRange(double xmin, double xmax, double ymin, double ymax); + DataRange(double xmin, double xmax, double ymin, double ymax); /** - construct a range for [xmin, xmax] , [ymin, ymax] , [zmin, zmax] + construct a range for [xmin, xmax] , [ymin, ymax] , [zmin, zmax] */ - DataRange(double xmin, double xmax, double ymin, double ymax, double zmin, double zmax); + DataRange(double xmin, double xmax, double ymin, double ymax, double zmin, double zmax); /** get range dimension - */ + */ unsigned int NDim() const { return fRanges.size(); } /** return range size for coordinate icoord (starts from zero) Size == 0 indicates no range is present [-inf, + inf] */ - unsigned int Size(unsigned int icoord = 0) const { + unsigned int Size(unsigned int icoord = 0) const { return icoord < fRanges.size() ? fRanges[icoord].size() : 0; } /** - return true if a range has been set in any of the coordinates + return true if a range has been set in any of the coordinates i.e. when it is not [-inf,+inf] for all coordinates Avoid in case of multi-dim to loop on all the coordinated and ask the size - */ - bool IsSet() const { - for (unsigned int icoord = 0; icoord < fRanges.size(); ++icoord) - if (fRanges[icoord].size() > 0) return true; - return false; + */ + bool IsSet() const { + for (unsigned int icoord = 0; icoord < fRanges.size(); ++icoord) + if (fRanges[icoord].size() > 0) return true; + return false; } - /** + /** return the vector of ranges for the coordinate icoord - */ - const RangeSet & Ranges(unsigned int icoord = 0) const { - // return icoord < fRanges.size() ? fRanges[icoord] : RangeSet(); - return fRanges.at(icoord); + */ + const RangeSet & Ranges(unsigned int icoord = 0) const { + // return icoord < fRanges.size() ? fRanges[icoord] : RangeSet(); + return fRanges.at(icoord); } - /** + /** return the i-th range for the coordinate icoord. - Useful method when only one range is present for the given coordinate - */ + Useful method when only one range is present for the given coordinate + */ std::pair<double, double> operator() (unsigned int icoord = 0,unsigned int irange = 0) const; /** get the first range for given coordinate. If range does not exist return -inf, +inf */ - void GetRange(unsigned int icoord, double & xmin, double & xmax) const { + void GetRange(unsigned int icoord, double & xmin, double & xmax) const { if (Size(icoord) == 0) GetInfRange(xmin,xmax); - else { - xmin = fRanges[icoord].front().first; - xmax = fRanges[icoord].front().second; + else { + xmin = fRanges[icoord].front().first; + xmax = fRanges[icoord].front().second; } } /** @@ -114,40 +114,40 @@ public: /** get first range for the x and y coordinates */ - void GetRange(double & xmin, double & xmax, double & ymin, double & ymax) const { - GetRange(0,xmin,xmax); GetRange(1,ymin,ymax); + void GetRange(double & xmin, double & xmax, double & ymin, double & ymax) const { + GetRange(0,xmin,xmax); GetRange(1,ymin,ymax); } /** get first range for the x and y and z coordinates */ - void GetRange(double & xmin, double & xmax, double & ymin, double & ymax, double & zmin, double & zmax) const { - GetRange(0,xmin,xmax); GetRange(1,ymin,ymax); GetRange(2,zmin,zmax); + void GetRange(double & xmin, double & xmax, double & ymin, double & ymax, double & zmin, double & zmax) const { + GetRange(0,xmin,xmax); GetRange(1,ymin,ymax); GetRange(2,zmin,zmax); } /** get first range for coordinates and fill the vector */ - void GetRange(double * xmin, double * xmax) const { - for (unsigned int i = 0; i < fRanges.size(); ++i) - GetRange(i,xmin[i],xmax[i]); + void GetRange(double * xmin, double * xmax) const { + for (unsigned int i = 0; i < fRanges.size(); ++i) + GetRange(i,xmin[i],xmax[i]); } - /** + /** Destructor (no operations) - */ - ~DataRange () {} + */ + ~DataRange () {} /** - add a range [xmin,xmax] for the new coordinate icoord - Adding a range does not delete existing one, but takes the OR with - existing ranges. + add a range [xmin,xmax] for the new coordinate icoord + Adding a range does not delete existing one, but takes the OR with + existing ranges. if want to replace range use method SetRange, which replace range with existing one */ - void AddRange(unsigned int icoord , double xmin, double xmax ); + void AddRange(unsigned int icoord , double xmin, double xmax ); /** - add a range [xmin,xmax] for the first coordinate icoord + add a range [xmin,xmax] for the first coordinate icoord */ void AddRange(double xmin, double xmax ) { AddRange(0,xmin,xmax); } /** @@ -155,21 +155,21 @@ public: */ void AddRange(double xmin, double xmax, double ymin, double ymax ) { AddRange(0,xmin,xmax); AddRange(1,ymin,ymax); } /** - add a range [xmin,xmax] for the first and [ymin,ymax] for the second coordinate and + add a range [xmin,xmax] for the first and [ymin,ymax] for the second coordinate and [zmin,zmax] for the third coordinate */ - void AddRange(double xmin, double xmax, double ymin, double ymax, double zmin, double zmax ) { + void AddRange(double xmin, double xmax, double ymin, double ymax, double zmin, double zmax ) { AddRange(0,xmin,xmax); AddRange(1,ymin,ymax); AddRange(2,zmin,zmax); } /** - set a range [xmin,xmax] for the new coordinate icoord + set a range [xmin,xmax] for the new coordinate icoord If more range exists for other coordinates, delete the existing one and use it the new one - Use Add range if want to keep the union of the existing ranges + Use Add range if want to keep the union of the existing ranges */ - void SetRange(unsigned int icoord , double xmin, double xmax ); + void SetRange(unsigned int icoord , double xmin, double xmax ); /** - set a range [xmin,xmax] for the first coordinate icoord + set a range [xmin,xmax] for the first coordinate icoord */ void SetRange(double xmin, double xmax ) { SetRange(0,xmin,xmax); } /** @@ -177,10 +177,10 @@ public: */ void SetRange(double xmin, double xmax, double ymin, double ymax ) { SetRange(0,xmin,xmax); SetRange(1,ymin,ymax); } /** - set a range [xmin,xmax] for the first and [ymin,ymax] for the second coordinate and + set a range [xmin,xmax] for the first and [ymin,ymax] for the second coordinate and [zmin,zmax] for the third coordinate */ - void SetRange(double xmin, double xmax, double ymin, double ymax, double zmin, double zmax ) { + void SetRange(double xmin, double xmax, double ymin, double ymax, double zmin, double zmax ) { SetRange(0,xmin,xmax); SetRange(1,ymin,ymax); SetRange(2,zmin,zmax); } /** @@ -191,24 +191,24 @@ public: /** check if a point is inside the range for the given coordinate */ - bool IsInside(double x, unsigned int icoord = 0) const; + bool IsInside(double x, unsigned int icoord = 0) const; -protected: - /** - internal function to remove all the existing ranges between xmin and xmax +protected: + /** + internal function to remove all the existing ranges between xmin and xmax called when a new range is inserted */ - void CleanRangeSet(unsigned int icoord, double xmin, double xmax); + void CleanRangeSet(unsigned int icoord, double xmin, double xmax); // get the full range (-inf, +inf) static void GetInfRange(double &x1, double &x2); -private: +private: RangeIntervals fRanges; // list of all ranges -}; +}; } // end namespace Fit diff --git a/ThirdParty/RootMinimizers/inc/Fit/DataVector.h b/ThirdParty/RootMinimizers/inc/Fit/DataVector.h index 9317564a011bf97149b9983c4fd6fb2a9d601f35..80229403a111745bb2940c4dc27926418690c794 100644 --- a/ThirdParty/RootMinimizers/inc/Fit/DataVector.h +++ b/ThirdParty/RootMinimizers/inc/Fit/DataVector.h @@ -13,8 +13,8 @@ #ifndef ROOT_Fit_DataVector #define ROOT_Fit_DataVector -/** -@defgroup FitData Fit Data Classes +/** +@defgroup FitData Fit Data Classes Classes for describing the input data for fitting @@ -38,12 +38,24 @@ Classes for describing the input data for fitting #include <vector> #include <cassert> -#include <iostream> +#include <iostream> + + +namespace ROOT { + namespace Fit { -namespace ROOT { - namespace Fit { + //class used for making shared_ptr of data classes managed by the user (i.e. when we don;t want to delete the contained object) + template <class T> + struct DummyDeleter + { + // a deleter not deleting the contained object + // used to avoid shared_ptr deleting the contained objects if managed externally + void operator()(T* /* p */) { + //printf("ROOT::Fit::DummyDeleter called - do not delete object %x \n", p); + } + }; /** @@ -52,30 +64,30 @@ namespace ROOT { @ingroup FitData */ -class FitData { - -public: +class FitData { - /// construct with default option and data range +public: + + /// construct with default option and data range FitData() {} /// dummy virtual destructor virtual ~FitData() {} - /// construct passing options and default data range - FitData(const DataOptions & opt) : + /// construct passing options and default data range + FitData(const DataOptions & opt) : fOptions(opt) {} - /// construct passing range and default options - FitData(const DataRange & range) : + /// construct passing range and default options + FitData(const DataRange & range) : fRange(range) {} - /// construct passing options and data range - FitData (const DataOptions & opt, const DataRange & range) : - fOptions(opt), + /// construct passing options and data range + FitData (const DataOptions & opt, const DataRange & range) : + fOptions(opt), fRange(range) {} @@ -91,62 +103,62 @@ public: const DataRange & Range() const { return fRange; } // range cannot be modified afterwards - // since fit method functions use all data + // since fit method functions use all data - /** - define a max size to avoid allocating too large arrays + /** + define a max size to avoid allocating too large arrays */ - static unsigned int MaxSize() { + static unsigned int MaxSize() { return (unsigned int) (-1) / sizeof (double); } -private: +private: - DataOptions fOptions; - DataRange fRange; + DataOptions fOptions; + DataRange fRange; }; - -/** + +/** class holding the fit data points. It is template on the type of point, - which can be for example a binned or unbinned point. - It is basicaly a wrapper on an std::vector + which can be for example a binned or unbinned point. + It is basicaly a wrapper on an std::vector @ingroup FitData -*/ +*/ class DataVector { -public: +public: typedef std::vector<double> FData; - /** + /** default constructor for a vector of N -data - */ - explicit DataVector (size_t n ) : + */ + explicit DataVector (size_t n ) : fData(std::vector<double>(n)) { //if (n!=0) fData.reserve(n); - } + } - /** + /** Destructor (no operations) - */ - ~DataVector () {} + */ + ~DataVector () {} // use default copy constructor and assignment operator - + /** - const access to underlying vector + const access to underlying vector */ const FData & Data() const { return fData; } @@ -157,8 +169,8 @@ public: #ifndef __CINT__ /** - const iterator access - */ + const iterator access + */ typedef FData::const_iterator const_iterator; typedef FData::iterator iterator; @@ -166,126 +178,126 @@ public: const_iterator end() const { return fData.begin()+fData.size(); } /** - non-const iterator access - */ + non-const iterator access + */ iterator begin() { return fData.begin(); } iterator end() { return fData.end(); } #endif /** access to the point - */ - const double & operator[] (unsigned int i) const { return fData[i]; } - double & operator[] (unsigned int i) { return fData[i]; } + */ + const double & operator[] (unsigned int i) const { return fData[i]; } + double & operator[] (unsigned int i) { return fData[i]; } /** - full size of data vector (npoints * point size) + full size of data vector (npoints * point size) */ - size_t Size() const { return fData.size(); } + size_t Size() const { return fData.size(); } -private: +private: - FData fData; -}; + FData fData; +}; // // usefule typedef's of DataVector // class BinPoint; - + // // declaration for various type of data vectors -// typedef DataVector<ROOT::Fit::BinPoint> BinData; -// typedef DataVector<ROOT::Fit::BinPoint>::const_iterator BinDataIterator; +// typedef DataVector<ROOT::Fit::BinPoint> BinData; +// typedef DataVector<ROOT::Fit::BinPoint>::const_iterator BinDataIterator; /** class maintaining a pointer to external data Using this class avoids copying the data when performing a fit NOTE: this class is not thread-safe and should not be used in parallel fits - + @ingroup FitData */ -class DataWrapper { +class DataWrapper { -public: +public: /** specialized constructor for 1D data without errors and values */ explicit DataWrapper(const double * dataX ) : fDim(1), - fValues(0), + fValues(0), fErrors(0), fCoords(std::vector<const double * >(1) ), fX(std::vector<double>(1) ) { - fCoords[0] = dataX; + fCoords[0] = dataX; } /** - constructor for 1D data (if errors are not present a null pointer should be passed) + constructor for 1D data (if errors are not present a null pointer should be passed) */ DataWrapper(const double * dataX, const double * val, const double * eval , const double * ex ) : fDim(1), - fValues(val), + fValues(val), fErrors(eval), fCoords(std::vector<const double * >(1) ), fErrCoords(std::vector<const double * >(1) ), fX(std::vector<double>(1) ), fErr(std::vector<double>(1) ) { - fCoords[0] = dataX; - fErrCoords[0] = ex; + fCoords[0] = dataX; + fErrCoords[0] = ex; } /** - constructor for 2D data (if errors are not present a null pointer should be passed) + constructor for 2D data (if errors are not present a null pointer should be passed) */ - DataWrapper(const double * dataX, const double * dataY, const double * val, const double * eval, const double * ex , const double * ey ) : + DataWrapper(const double * dataX, const double * dataY, const double * val, const double * eval, const double * ex , const double * ey ) : fDim(2), - fValues(val), + fValues(val), fErrors(eval), fCoords(std::vector<const double * >(2) ), fErrCoords(std::vector<const double * >(2) ), fX(std::vector<double>(2) ), fErr(std::vector<double>(2) ) { - fCoords[0] = dataX; - fCoords[1] = dataY; - fErrCoords[0] = ex; - fErrCoords[1] = ey; + fCoords[0] = dataX; + fCoords[1] = dataY; + fErrCoords[0] = ex; + fErrCoords[1] = ey; } /** - constructor for 3D data (if errors are not present a null pointer should be passed) + constructor for 3D data (if errors are not present a null pointer should be passed) */ - DataWrapper(const double * dataX, const double * dataY, const double * dataZ, const double * val, const double * eval, const double * ex , const double * ey, const double * ez ) : + DataWrapper(const double * dataX, const double * dataY, const double * dataZ, const double * val, const double * eval, const double * ex , const double * ey, const double * ez ) : fDim(3), - fValues(val), + fValues(val), fErrors(eval), fCoords(std::vector<const double * >(3) ), fErrCoords(std::vector<const double * >(3) ), fX(std::vector<double>(3) ), fErr(std::vector<double>(3) ) { - fCoords[0] = dataX; - fCoords[1] = dataY; - fCoords[2] = dataZ; - fErrCoords[0] = ex; - fErrCoords[1] = ey; - fErrCoords[2] = ez; + fCoords[0] = dataX; + fCoords[1] = dataY; + fCoords[2] = dataZ; + fErrCoords[0] = ex; + fErrCoords[1] = ey; + fErrCoords[2] = ez; } /** - constructor for multi-dim data without errors + constructor for multi-dim data without errors */ - template<class Iterator> - DataWrapper(unsigned int dim, Iterator coordItr ) : + template<class Iterator> + DataWrapper(unsigned int dim, Iterator coordItr ) : fDim(dim), - fValues(0), + fValues(0), fErrors(0), fCoords(std::vector<const double * >(coordItr, coordItr+dim) ), fX(std::vector<double>(dim) ) @@ -293,13 +305,13 @@ public: /** - constructor for multi-dim data with errors and values (if errors are not present a null pointer should be passed) + constructor for multi-dim data with errors and values (if errors are not present a null pointer should be passed) */ - template<class Iterator> - DataWrapper(size_t dim, Iterator coordItr, const double * val, const double * eval, Iterator errItr ) : + template<class Iterator> + DataWrapper(size_t dim, Iterator coordItr, const double * val, const double * eval, Iterator errItr ) : // use size_t for dim to avoid allocating huge vector on 64 bits when dim=-1 fDim(dim), - fValues(val), + fValues(val), fErrors(eval), fCoords(std::vector<const double * >(coordItr, coordItr+dim) ), fErrCoords(std::vector<const double * >(errItr, errItr+dim) ), @@ -307,8 +319,8 @@ public: fErr(std::vector<double>(dim) ) { } - // destructor - ~DataWrapper() { + // destructor + ~DataWrapper() { //printf("Delete Data wrapper\n"); // no operations } @@ -317,53 +329,53 @@ public: // copy the pointer of the data not the data - const double * Coords(unsigned int ipoint) const { - for (unsigned int i = 0; i < fDim; ++i) { + const double * Coords(unsigned int ipoint) const { + for (unsigned int i = 0; i < fDim; ++i) { const double * x = fCoords[i]; assert (x != 0); fX[i] = x[ipoint]; - } + } return &fX.front(); } - double Coord(unsigned int ipoint, unsigned int icoord) const { + double Coord(unsigned int ipoint, unsigned int icoord) const { const double * x = fCoords[icoord]; assert (x != 0); - return x[ipoint]; + return x[ipoint]; } - const double * CoordErrors(unsigned int ipoint) const { - for (unsigned int i = 0; i < fDim; ++i) { + const double * CoordErrors(unsigned int ipoint) const { + for (unsigned int i = 0; i < fDim; ++i) { const double * err = fErrCoords[i]; - if (err == 0) return 0; + if (err == 0) return 0; fErr[i] = err[ipoint]; - } + } return &fErr.front(); } - double CoordError(unsigned int ipoint, unsigned int icoord) const { + double CoordError(unsigned int ipoint, unsigned int icoord) const { const double * err = fErrCoords[icoord]; - return (err != 0) ? err[ipoint] : 0; + return (err != 0) ? err[ipoint] : 0; } - double Value(unsigned int ipoint) const { + double Value(unsigned int ipoint) const { return fValues[ipoint]; } - double Error(unsigned int ipoint) const { + double Error(unsigned int ipoint) const { return (fErrors) ? fErrors[ipoint] : 0. ; - } + } -private: +private: unsigned int fDim; - const double * fValues; - const double * fErrors; + const double * fValues; + const double * fErrors; std::vector<const double *> fCoords; std::vector<const double *> fErrCoords; // cached vector to return x[] and errors on x @@ -373,7 +385,7 @@ private: }; - + } // end namespace Fit } // end namespace ROOT diff --git a/ThirdParty/RootMinimizers/inc/Fit/DataVectorfwd.h b/ThirdParty/RootMinimizers/inc/Fit/DataVectorfwd.h index 0cc73a9bf089f217ce80a646d1e123989463e6d8..51a189734ff2e45af9a8598c397454fb2951dbb1 100644 --- a/ThirdParty/RootMinimizers/inc/Fit/DataVectorfwd.h +++ b/ThirdParty/RootMinimizers/inc/Fit/DataVectorfwd.h @@ -8,25 +8,25 @@ * * **********************************************************************/ -// forward decalaration for the DataVector classes +// forward decalaration for the DataVector classes #ifndef ROOT_Fit_DataVectorfwd #define ROOT_Fit_DataVectorfwd -namespace ROOT { +namespace ROOT { - namespace Fit { - + namespace Fit { - //template <class Point> class DataVector; - //class DataVector; - //class BinPoint; - //class UnBinPoint; + //template <class Point> class DataVector; + //class DataVector; - class BinData; - class UnBinData; + //class BinPoint; + //class UnBinPoint; + + class BinData; + class UnBinData; diff --git a/ThirdParty/RootMinimizers/inc/Fit/FcnAdapter.h b/ThirdParty/RootMinimizers/inc/Fit/FcnAdapter.h index 95def276676ab14522fc29b665632301f2b4cf1b..76ef1f0c07e83fe06d2ba80486d7aaf910304c91 100644 --- a/ThirdParty/RootMinimizers/inc/Fit/FcnAdapter.h +++ b/ThirdParty/RootMinimizers/inc/Fit/FcnAdapter.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Author: L. Moneta 10/2005 +// Author: L. Moneta 10/2005 /********************************************************************** * * @@ -17,20 +17,20 @@ //___________________________________________________________ // -// Adapt the interface used in TMinuit (and the TVirtualFitter) for -// passing the objective function in a IFunction interface +// Adapt the interface used in TMinuit (and the TVirtualFitter) for +// passing the objective function in a IFunction interface // (ROOT::Math::IMultiGenFunction) // -namespace ROOT { +namespace ROOT { - namespace Fit { + namespace Fit { class FcnAdapter : public ROOT::Math::IMultiGenFunction { public: - FcnAdapter(void (*fcn)(int&, double*, double&, double*, int ), int dim = 0) : + FcnAdapter(void (*fcn)(int&, double*, double&, double*, int ), int dim = 0) : fDim(dim), fFCN(fcn) {} @@ -39,27 +39,27 @@ public: virtual unsigned int NDim() const { return fDim; } - ROOT::Math::IMultiGenFunction * Clone() const { + ROOT::Math::IMultiGenFunction * Clone() const { return new FcnAdapter(fFCN,fDim); } void SetDimension(int dim) { fDim = dim; } -private: +private: - virtual double DoEval(const double * x) const { - double fval = 0; - int dim = fDim; + virtual double DoEval(const double * x) const { + double fval = 0; + int dim = fDim; // call with flag 4 - fFCN(dim, 0, fval, const_cast<double *>(x), 4); - return fval; + fFCN(dim, 0, fval, const_cast<double *>(x), 4); + return fval; } private: - unsigned int fDim; + unsigned int fDim; void (*fFCN)(int&, double*, double&, double*, int); - + }; diff --git a/ThirdParty/RootMinimizers/inc/Fit/FitConfig.h b/ThirdParty/RootMinimizers/inc/Fit/FitConfig.h index 00e398a46b97fdd85a95b43e3f5b6748c0f63185..1a2ec53ddc8d123c6f3aeee5180ca9268e9cb3b3 100644 --- a/ThirdParty/RootMinimizers/inc/Fit/FitConfig.h +++ b/ThirdParty/RootMinimizers/inc/Fit/FitConfig.h @@ -29,47 +29,47 @@ #include <vector> -namespace ROOT { +namespace ROOT { - namespace Math { + namespace Math { class Minimizer; - class MinimizerOptions; + class MinimizerOptions; } - namespace Fit { + namespace Fit { class FitResult; //___________________________________________________________________________________ -/** +/** Class describing the configuration of the fit, options and parameter settings - using the ROOT::Fit::ParameterSettings class + using the ROOT::Fit::ParameterSettings class @ingroup FitMain -*/ +*/ class FitConfig { -public: +public: - /** + /** Default constructor - */ - FitConfig (unsigned int npar = 0); + */ + FitConfig (unsigned int npar = 0); /* - Copy constructor + Copy constructor */ FitConfig(const FitConfig & rhs); - /** - Destructor - */ - ~FitConfig (); + /** + Destructor + */ + ~FitConfig (); /* - Assignment operator + Assignment operator */ FitConfig & operator= (const FitConfig & rhs); @@ -95,25 +95,25 @@ public: std::vector<ROOT::Fit::ParameterSettings> & ParamsSettings() { return fSettings; } /** - number of parameters settings + number of parameters settings */ unsigned int NPar() const { return fSettings.size(); } /** - set the parameter settings from a model function. - Create always new parameter setting list from a given model function + set the parameter settings from a model function. + Create always new parameter setting list from a given model function */ - void CreateParamsSettings(const ROOT::Math::IParamMultiFunction & func); + void CreateParamsSettings(const ROOT::Math::IParamMultiFunction & func); /** - set the parameter settings from number of parameters and a vector of values and optionally step values. If there are not existing or number of parameters does not match existing one, create a new parameter setting list. + set the parameter settings from number of parameters and a vector of values and optionally step values. If there are not existing or number of parameters does not match existing one, create a new parameter setting list. */ - void SetParamsSettings(unsigned int npar, const double * params, const double * vstep = 0); + void SetParamsSettings(unsigned int npar, const double * params, const double * vstep = 0); /* Set the parameter settings from a vector of parameter settings */ - void SetParamsSettings (const std::vector<ROOT::Fit::ParameterSettings>& pars ) { + void SetParamsSettings (const std::vector<ROOT::Fit::ParameterSettings>& pars ) { fSettings = pars; } @@ -128,47 +128,47 @@ public: /** create a new minimizer according to chosen configuration */ - ROOT::Math::Minimizer * CreateMinimizer(); + ROOT::Math::Minimizer * CreateMinimizer(); /** - access to the minimizer control parameter (non const method) + access to the minimizer control parameter (non const method) */ - ROOT::Math::MinimizerOptions & MinimizerOptions() { return fMinimizerOpts; } + ROOT::Math::MinimizerOptions & MinimizerOptions() { return fMinimizerOpts; } #ifndef __CINT__ // this method fails on Windows /** set all the minimizer options using class MinimizerOptions */ - void SetMinimizerOptions(const ROOT::Math::MinimizerOptions & minopt); + void SetMinimizerOptions(const ROOT::Math::MinimizerOptions & minopt); #endif - + /** - set minimizer type + set minimizer type */ - void SetMinimizer(const char * type, const char * algo = 0) { - if (type) fMinimizerOpts.SetMinimizerType(type); - if (algo) fMinimizerOpts.SetMinimizerAlgorithm(algo); - } + void SetMinimizer(const char * type, const char * algo = 0) { + if (type) fMinimizerOpts.SetMinimizerType(type); + if (algo) fMinimizerOpts.SetMinimizerAlgorithm(algo); + } /** return type of minimizer package */ - const std::string & MinimizerType() const { return fMinimizerOpts.MinimizerType(); } + const std::string & MinimizerType() const { return fMinimizerOpts.MinimizerType(); } /** - return type of minimizer algorithms + return type of minimizer algorithms */ - const std::string & MinimizerAlgoType() const { return fMinimizerOpts.MinimizerAlgorithm(); } + const std::string & MinimizerAlgoType() const { return fMinimizerOpts.MinimizerAlgorithm(); } /** - flag to check if resulting errors are be normalized according to chi2/ndf + flag to check if resulting errors are be normalized according to chi2/ndf */ - bool NormalizeErrors() const { return fNormErrors; } + bool NormalizeErrors() const { return fNormErrors; } ///do analysis for parabolic errors bool ParabErrors() const { return fParabErrors; } @@ -177,7 +177,7 @@ public: bool MinosErrors() const { return fMinosErrors; } ///Update configuration after a fit using the FitResult - bool UpdateAfterFit() const { return fUpdateAfterFit; } + bool UpdateAfterFit() const { return fUpdateAfterFit; } ///Apply Weight correction for error matrix computation bool UseWeightCorrection() const { return fWeightCorr; } @@ -192,51 +192,51 @@ public: void SetNormErrors(bool on = true) { fNormErrors= on; } ///set parabolic erros - void SetParabErrors(bool on = true) { fParabErrors = on; } + void SetParabErrors(bool on = true) { fParabErrors = on; } ///set Minos erros computation to be performed after fitting - void SetMinosErrors(bool on = true) { fMinosErrors = on; } + void SetMinosErrors(bool on = true) { fMinosErrors = on; } ///apply the weight correction for error matric computation void SetWeightCorrection(bool on = true) { fWeightCorr = on; } /// set parameter indeces for running Minos - /// this can be used for running Minos on a subset of parameters - otherwise is run on all of them - /// if MinosErrors() is set - void SetMinosErrors(const std::vector<unsigned int> & paramInd ) { - fMinosErrors = true; - fMinosParams = paramInd; + /// this can be used for running Minos on a subset of parameters - otherwise is run on all of them + /// if MinosErrors() is set + void SetMinosErrors(const std::vector<unsigned int> & paramInd ) { + fMinosErrors = true; + fMinosParams = paramInd; } ///Update configuration after a fit using the FitResult - void SetUpdateAfterFit(bool on = true) { fUpdateAfterFit = on; } + void SetUpdateAfterFit(bool on = true) { fUpdateAfterFit = on; } /** static function to control default minimizer type and algorithm */ - static void SetDefaultMinimizer(const char * type, const char * algo = 0); + static void SetDefaultMinimizer(const char * type, const char * algo = 0); + - -protected: +protected: -private: +private: bool fNormErrors; // flag for error normalization - bool fParabErrors; // get correct parabolic errors estimate (call Hesse after minimizing) + bool fParabErrors; // get correct parabolic errors estimate (call Hesse after minimizing) bool fMinosErrors; // do full error analysis using Minos bool fUpdateAfterFit; // update the configuration after a fit using the result - bool fWeightCorr; // apply correction to errors for weights fits + bool fWeightCorr; // apply correction to errors for weights fits std::vector<ROOT::Fit::ParameterSettings> fSettings; // vector with the parameter settings std::vector<unsigned int> fMinosParams; // vector with the parameter indeces for running Minos ROOT::Math::MinimizerOptions fMinimizerOpts; //minimizer control parameters including name and algo type -}; +}; } // end namespace Fit diff --git a/ThirdParty/RootMinimizers/inc/Fit/FitResult.h b/ThirdParty/RootMinimizers/inc/Fit/FitResult.h index 67c8a4a124ff469bcf858a0c164bf6562c9fa6ae..16f7ca00b88640dc355bb27bc88c7b5b9775a04a 100644 --- a/ThirdParty/RootMinimizers/inc/Fit/FitResult.h +++ b/ThirdParty/RootMinimizers/inc/Fit/FitResult.h @@ -25,138 +25,152 @@ #include <string> #include <cmath> #include <cassert> +#include <memory> -namespace ROOT { +namespace ROOT { - namespace Math { - class Minimizer; + namespace Math { + class Minimizer; } - namespace Fit { + namespace Fit { - class FitConfig; + class FitConfig; + class FitData; class BinData; //___________________________________________________________________________________ -/** - class containg the result of the fit and all the related information +/** + class containg the result of the fit and all the related information (fitted parameter values, error, covariance matrix and minimizer result information) - Contains a pointer also to the fitted (model) function, modified with the fit parameter values. - When the fit is valid, it is constructed from a Minimizer and a model function pointer + Contains a pointer also to the fitted (model) function, modified with the fit parameter values. + When the fit is valid, it is constructed from a Minimizer and a model function pointer @ingroup FitMain -*/ +*/ class FitResult { -public: +public: - typedef ROOT::Math::IParamMultiFunction IModelFunction; + typedef ROOT::Math::IParamMultiFunction IModelFunction; - /** + /** Default constructor for an empty (non valid) fit result - */ - FitResult (); + */ + FitResult (); - /** - Constructor from a fit-config for a dummy fit + /** + Constructor from a fit-config for a dummy fit (e.g. when only one fcn evaluation is done) - */ + */ FitResult (const FitConfig & fconfig); - /** - Construct from a Minimizer instance after fitting - Run also Minos if requested from the configuration - */ - FitResult(ROOT::Math::Minimizer & min, const FitConfig & fconfig, const IModelFunction * f, bool isValid, unsigned int sizeOfData = 0, bool binFit = true, const ROOT::Math::IMultiGenFunction * chi2func = 0, unsigned int ncalls = 0); - /** - Copy constructor. - */ - FitResult(const FitResult &); + /** + Copy constructor. + */ + FitResult(const FitResult & rhs); - /** + /** Assignment operator - */ - FitResult & operator = (const FitResult & rhs); + */ + FitResult & operator = (const FitResult & rhs); - /** - Destructor - */ - ~FitResult (); + /** + Destructor + */ + virtual ~FitResult (); -public: +public: + + /** + Fill the fit result from a Minimizer instance after fitting + Run also Minos if requested from the configuration + */ + void FillResult(const std::shared_ptr<ROOT::Math::Minimizer> & min, const FitConfig & fconfig, const std::shared_ptr<IModelFunction> & f, + bool isValid, unsigned int sizeOfData = 0, bool binFit = true, const ROOT::Math::IMultiGenFunction * chi2func = 0, unsigned int ncalls = 0); + /** Update the fit result with a new minimization status - To be run only if same fit is performed with same configuration + To be run only if same fit is performed with same configuration Note that in this case MINOS is not re-run. If one wants to run also MINOS - a new result must be created + a new result must be created */ - bool Update(const ROOT::Math::Minimizer & min, bool isValid, unsigned int ncalls = 0 ); + bool Update(const std::shared_ptr<ROOT::Math::Minimizer> & min, bool isValid, unsigned int ncalls = 0 ); /** minimization quantities **/ - /// minimizer type - const std::string & MinimizerType() const { return fMinimType; } + /// minimizer type + const std::string & MinimizerType() const { return fMinimType; } - /** + /** True if fit successful, otherwise false. - A fit is considered successful if the minimizer succeded in finding the - minimum. It could happen that subsequent operations like error analysis (e.g. Minos) - failed. In that case the status can be still true if the original minimization algorithm - succeeded in finding the minimum. - One can query in that case the minimizer return status using Status(). - It is responability to the Minimizer class to tag a found minimum as valid or not + A fit is considered successful if the minimizer succeded in finding the + minimum. It could happen that subsequent operations like error analysis (e.g. Minos) + failed. In that case the status can be still true if the original minimization algorithm + succeeded in finding the minimum. + One can query in that case the minimizer return status using Status(). + It is responability to the Minimizer class to tag a found minimum as valid or not and to produce also a status code. */ bool IsValid() const { return fValid; } - /// True if a fit result does not exist (even invalid) with parameter values + /// True if a fit result does not exist (even invalid) with parameter values bool IsEmpty() const { return (fParams.size() == 0); } - + /// Return value of the objective function (chi2 or likelihood) used in the fit - double MinFcnValue() const { return fVal; } + double MinFcnValue() const { return fVal; } ///Number of function calls to find minimum unsigned int NCalls() const { return fNCalls; } - - ///Expected distance from minimum + + ///Expected distance from minimum double Edm() const { return fEdm; } - /// get total number of parameters - unsigned int NTotalParameters() const { return fParams.size(); } + /// get total number of parameters + unsigned int NTotalParameters() const { return fParams.size(); } /// total number of parameters (abbreviation) unsigned int NPar() const { return NTotalParameters(); } - + /// get total number of free parameters unsigned int NFreeParameters() const { return fNFree; } - /// minimizer status code - int Status() const { return fStatus; } + /// minimizer status code + int Status() const { return fStatus; } ///covariance matrix status code /// using Minuit convention : =0 not calculated, =1 approximated, =2 made pos def , =3 accurate int CovMatrixStatus() const { return fCovStatus; } - + /** fitting quantities **/ /// Return pointer to model (fit) function with fitted parameter values. - const IModelFunction * FittedFunction() const { return fFitFunc; } + /// Pointer is managed internally. I must not be deleted + const IModelFunction * FittedFunction() const { + return fFitFunc.get(); + } + + /// return BinData used in the fit (return a nullptr in case a different fit is done + /// or the data are not available + /// Pointer is managed internally, it must not be deleted + const BinData * FittedBinData() const; + /// Chi2 fit value - /// in case of likelihood must be computed ? - double Chi2() const { return fChi2; } + /// in case of likelihood must be computed ? + double Chi2() const { return fChi2; } /// Number of degree of freedom - unsigned int Ndf() const { return fNdf; } + unsigned int Ndf() const { return fNdf; } /// p value of the fit (chi2 probability) - double Prob() const; + double Prob() const; - /// parameter errors (return st::vector) + /// parameter errors (return st::vector) const std::vector<double> & Errors() const { return fErrors; } /// parameter errors (return const pointer) const double * GetErrors() const { return (fErrors.empty()) ? 0 : &fErrors.front(); } @@ -168,22 +182,22 @@ public: /// parameter value by index double Value(unsigned int i) const { return fParams[i]; } - /// parameter value by index + /// parameter value by index double Parameter(unsigned int i) const { return fParams[i]; } - /// parameter error by index - // (NOTE: this due to conflict with TObject::Error cannot used in derived class which + /// parameter error by index + // (NOTE: this due to conflict with TObject::Error cannot used in derived class which // inherits from TObject. Use instead ParError (or Errors()[i] ) - double Error(unsigned int i) const { - return (i < fErrors.size() ) ? fErrors[i] : 0; - } - /// parameter error by index + double Error(unsigned int i) const { + return (i < fErrors.size() ) ? fErrors[i] : 0; + } + /// parameter error by index double ParError(unsigned int i) const { - return (i < fErrors.size() ) ? fErrors[i] : 0; + return (i < fErrors.size() ) ? fErrors[i] : 0; } /// name of the parameter - std::string ParName(unsigned int i) const; + std::string ParName(unsigned int i) const; /// set the Minos errors for parameter i (called by the Fitter class when running Minos) void SetMinosError(unsigned int i, double elow, double eup); @@ -191,89 +205,96 @@ public: /// query if parameter i has the Minos error bool HasMinosError(unsigned int i) const; - /// lower Minos error. If Minos has not run for parameter i return the parabolic error + /// lower Minos error. If Minos has not run for parameter i return the parabolic error double LowerError(unsigned int i) const; - /// upper Minos error. If Minos has not run for parameter i return the parabolic error + /// upper Minos error. If Minos has not run for parameter i return the parabolic error double UpperError(unsigned int i) const; - - /// parameter global correlation coefficient - double GlobalCC(unsigned int i) const { - return (i < fGlobalCC.size() ) ? fGlobalCC[i] : -1; - } + + /// parameter global correlation coefficient + double GlobalCC(unsigned int i) const { + return (i < fGlobalCC.size() ) ? fGlobalCC[i] : -1; + } - /// retrieve covariance matrix element - double CovMatrix (unsigned int i, unsigned int j) const { - if ( i >= fErrors.size() || j >= fErrors.size() ) return 0; + /// retrieve covariance matrix element + double CovMatrix (unsigned int i, unsigned int j) const { + if ( i >= fErrors.size() || j >= fErrors.size() ) return 0; if (fCovMatrix.size() == 0) return 0; // no matrix is available in case of non-valid fits - if ( j < i ) + if ( j < i ) return fCovMatrix[j + i* (i+1) / 2]; - else + else return fCovMatrix[i + j* (j+1) / 2]; } - /// retrieve correlation elements - double Correlation(unsigned int i, unsigned int j ) const { - if ( i >= fErrors.size() || j >= fErrors.size() ) return 0; + /// retrieve correlation elements + double Correlation(unsigned int i, unsigned int j ) const { + if ( i >= fErrors.size() || j >= fErrors.size() ) return 0; if (fCovMatrix.size() == 0) return 0; // no matrix is available in case of non-valid fits - double tmp = CovMatrix(i,i)*CovMatrix(j,j); - return ( tmp > 0) ? CovMatrix(i,j)/ std::sqrt(tmp) : 0; + double tmp = CovMatrix(i,i)*CovMatrix(j,j); + return ( tmp > 0) ? CovMatrix(i,j)/ std::sqrt(tmp) : 0; } - + /// fill covariance matrix elements using a generic matrix class implementing operator(i,j) - /// the matrix must be previously allocates with right size (npar * npar) - template<class Matrix> - void GetCovarianceMatrix(Matrix & mat) const { + /// the matrix must be previously allocates with right size (npar * npar) + template<class Matrix> + void GetCovarianceMatrix(Matrix & mat) const { unsigned int npar = fErrors.size(); - if (fCovMatrix.size() != npar*(npar+1)/2 ) return; // do nothing - for (unsigned int i = 0; i< npar; ++i) { - for (unsigned int j = 0; j<=i; ++j) { + if (fCovMatrix.size() != npar*(npar+1)/2 ) return; // do nothing + for (unsigned int i = 0; i< npar; ++i) { + for (unsigned int j = 0; j<=i; ++j) { mat(i,j) = fCovMatrix[j + i*(i+1)/2 ]; - if (i != j) mat(j,i) = mat(i,j); + if (i != j) mat(j,i) = mat(i,j); } } } /// fill a correlation matrix elements using a generic symmetric matrix class implementing operator(i,j) - /// the matrix must be previously allocates with right size (npar * npar) - template<class Matrix> - void GetCorrelationMatrix(Matrix & mat) const { - unsigned int npar = fErrors.size(); + /// the matrix must be previously allocates with right size (npar * npar) + template<class Matrix> + void GetCorrelationMatrix(Matrix & mat) const { + unsigned int npar = fErrors.size(); if (fCovMatrix.size() != npar*(npar+1)/2) return; // do nothing - for (unsigned int i = 0; i< npar; ++i) { - for (unsigned int j = 0; j<=i; ++j) { - double tmp = fCovMatrix[i * (i +3)/2 ] * fCovMatrix[ j * (j+3)/2 ]; - mat(i,j) = (tmp > 0) ? fCovMatrix[j + i*(i+1)/2 ] / std::sqrt(tmp) : 0; - if (i != j) mat(j,i) = mat(i,j); + for (unsigned int i = 0; i< npar; ++i) { + for (unsigned int j = 0; j<=i; ++j) { + double tmp = fCovMatrix[i * (i +3)/2 ] * fCovMatrix[ j * (j+3)/2 ]; + mat(i,j) = (tmp > 0) ? fCovMatrix[j + i*(i+1)/2 ] / std::sqrt(tmp) : 0; + if (i != j) mat(j,i) = mat(i,j); } } } /** - get confidence intervals for an array of n points x. - stride1 indicates the stride in the coordinate space while stride2 the stride in dimension space. + get confidence intervals for an array of n points x. + stride1 indicates the stride in the coordinate space while stride2 the stride in dimension space. For 1-dim points : stride1=1, stride2=1 for multi-dim points arranged as (x0,x1,...,xN,y0,....yN) stride1=1 stride2=n for multi-dim points arraged as (x0,y0,..,x1,y1,...,xN,yN,..) stride1=ndim, stride2=1 - + the confidence interval are returned in the array ci cl is the desired confidedence interval value norm is a flag to control if the intervals need to be normalized to the chi2/ndf value By default the intervals are corrected using the chi2/ndf value of the fit if a chi2 fit is performed */ - void GetConfidenceIntervals(unsigned int n, unsigned int stride1, unsigned int stride2, const double * x, double * ci, double cl=0.95, bool norm = true ) const; + void GetConfidenceIntervals(unsigned int n, unsigned int stride1, unsigned int stride2, const double * x, double * ci, double cl=0.95, bool norm = true ) const; /** evaluate confidence interval for the point specified in the passed data sets the confidence interval are returned in the array ci - cl is the desired confidence interval value - */ + cl is the desired confidence interval value. + This method is mantained for backward compatibility and will be deprecated + */ void GetConfidenceIntervals(const BinData & data, double * ci, double cl=0.95, bool norm = true ) const; + /** + evaluate confidence interval for the data set used in the last fit + the confidence interval are returned as a vector of data points + */ + std::vector<double> GetConfidenceIntervals(double cl=0.95, bool norm = true ) const; + /// get index for parameter name (return -1 if not found) - int Index(const std::string & name) const; + int Index(const std::string & name) const; ///normalize errors using chi2/ndf for chi2 fits @@ -286,38 +307,39 @@ public: void Print(std::ostream & os, bool covmat = false) const; ///print error matrix and correlations - void PrintCovMatrix(std::ostream & os) const; + void PrintCovMatrix(std::ostream & os) const; - /// query if a parameter is bound - bool IsParameterBound(unsigned int ipar) const; + /// query if a parameter is bound + bool IsParameterBound(unsigned int ipar) const; - /// query if a parameter is fixed - bool IsParameterFixed(unsigned int ipar) const; + /// query if a parameter is fixed + bool IsParameterFixed(unsigned int ipar) const; /// retrieve parameter bounds - return false if parameter is not bound - bool ParameterBounds(unsigned int ipar, double &lower, double &upper) const; + bool ParameterBounds(unsigned int ipar, double &lower, double &upper) const; /// get name of parameter (deprecated) - std::string GetParameterName(unsigned int ipar) const { + std::string GetParameterName(unsigned int ipar) const { return ParName(ipar); } -protected: +protected: /// Return pointer non const pointer to model (fit) function with fitted parameter values. - /// used by Fitter class - IModelFunction * ModelFunction() { return fFitFunc; } - void SetModelFunction(IModelFunction * func) { fFitFunc = func; } + /// used by Fitter class + std::shared_ptr<IModelFunction> ModelFunction() { return fFitFunc; } + void SetModelFunction(const std::shared_ptr<IModelFunction> & func) { fFitFunc = func; } - friend class Fitter; + + friend class Fitter; bool fValid; // flag for indicating valid fit bool fNormalized; // flag for indicating is errors are normalized - unsigned int fNFree; // number of fit free parameters (total parameters are in size of parameter vector) + unsigned int fNFree; // number of fit free parameters (total parameters are in size of parameter vector) unsigned int fNdf; // number of degree of freedom unsigned int fNCalls; // number of function calls int fStatus; // minimizer status code @@ -325,23 +347,30 @@ protected: double fVal; // minimum function value double fEdm; // expected distance from mimimum double fChi2; // fit chi2 value (different than fval in case of chi2 fits) - IModelFunction * fFitFunc; //! model function resulting from the fit. It is given by Fitter but it is managed by FitResult + std::shared_ptr<ROOT::Math::Minimizer> fMinimizer; //! minimizer object used for fitting + std::shared_ptr<ROOT::Math::IMultiGenFunction> fObjFunc; //! objective function used for fitting + std::shared_ptr<IModelFunction> fFitFunc; //! model function resulting from the fit. + std::shared_ptr<FitData> fFitData; //! data set used in the fit std::map<unsigned int, bool> fFixedParams; // list of fixed parameters std::map<unsigned int, unsigned int> fBoundParams; // list of limited parameters std::vector<std::pair<double,double> > fParamBounds; // parameter bounds std::vector<double> fParams; // parameter values. Size is total number of parameters - std::vector<double> fErrors; // errors + std::vector<double> fErrors; // errors std::vector<double> fCovMatrix; // covariance matrix (size is npar*(npar+1)/2) where npar is total parameters std::vector<double> fGlobalCC; // global Correlation coefficient std::map<unsigned int, std::pair<double,double> > fMinosErrors; // map contains the two Minos errors std::string fMinimType; // string indicating type of minimizer std::vector<std::string> fParNames; // parameter names (only with FCN only fits, when fFitFunc=0) -}; +}; + } // end namespace Fit } // end namespace ROOT + + + #endif /* ROOT_Fit_FitResult */ diff --git a/ThirdParty/RootMinimizers/inc/Fit/FitUtil.h b/ThirdParty/RootMinimizers/inc/Fit/FitUtil.h index 734030ea5d993bab4fb981587d1bd8b0b053eafe..b0de43cef30a0b9e41521f5f0bfdc5cf63e5aaa9 100644 --- a/ThirdParty/RootMinimizers/inc/Fit/FitUtil.h +++ b/ThirdParty/RootMinimizers/inc/Fit/FitUtil.h @@ -22,19 +22,19 @@ #endif -namespace ROOT { +namespace ROOT { - namespace Fit { + namespace Fit { - -/** - namespace defining utility free functions using in Fit for evaluating the various fit method - functions (chi2, likelihood, etc..) given the data and the model function + +/** + namespace defining utility free functions using in Fit for evaluating the various fit method + functions (chi2, likelihood, etc..) given the data and the model function @ingroup FitMain -*/ +*/ namespace FitUtil { typedef ROOT::Math::IParamMultiFunction IModelFunction; @@ -42,89 +42,89 @@ namespace FitUtil { /** Chi2 Functions */ - /** - evaluate the Chi2 given a model function and the data at the point x. + /** + evaluate the Chi2 given a model function and the data at the point x. return also nPoints as the effective number of used points in the Chi2 evaluation - */ - double EvaluateChi2(const IModelFunction & func, const BinData & data, const double * x, unsigned int & nPoints); + */ + double EvaluateChi2(const IModelFunction & func, const BinData & data, const double * x, unsigned int & nPoints); - /** - evaluate the effective Chi2 given a model function and the data at the point x. + /** + evaluate the effective Chi2 given a model function and the data at the point x. The effective chi2 uses the errors on the coordinates : W = 1/(sigma_y**2 + ( sigma_x_i * df/dx_i )**2 ) return also nPoints as the effective number of used points in the Chi2 evaluation - */ - double EvaluateChi2Effective(const IModelFunction & func, const BinData & data, const double * x, unsigned int & nPoints); + */ + double EvaluateChi2Effective(const IModelFunction & func, const BinData & data, const double * x, unsigned int & nPoints); - /** - evaluate the Chi2 gradient given a model function and the data at the point x. + /** + evaluate the Chi2 gradient given a model function and the data at the point x. return also nPoints as the effective number of used points in the Chi2 evaluation - */ - void EvaluateChi2Gradient(const IModelFunction & func, const BinData & data, const double * x, double * grad, unsigned int & nPoints); + */ + void EvaluateChi2Gradient(const IModelFunction & func, const BinData & data, const double * x, double * grad, unsigned int & nPoints); - /** - evaluate the LogL given a model function and the data at the point x. + /** + evaluate the LogL given a model function and the data at the point x. return also nPoints as the effective number of used points in the LogL evaluation - */ - double EvaluateLogL(const IModelFunction & func, const UnBinData & data, const double * x, int iWeight, bool extended, unsigned int & nPoints); + */ + double EvaluateLogL(const IModelFunction & func, const UnBinData & data, const double * x, int iWeight, bool extended, unsigned int & nPoints); - /** - evaluate the LogL gradient given a model function and the data at the point x. + /** + evaluate the LogL gradient given a model function and the data at the point x. return also nPoints as the effective number of used points in the LogL evaluation - */ - void EvaluateLogLGradient(const IModelFunction & func, const UnBinData & data, const double * x, double * grad, unsigned int & nPoints); + */ + void EvaluateLogLGradient(const IModelFunction & func, const UnBinData & data, const double * x, double * grad, unsigned int & nPoints); - /** - evaluate the Poisson LogL given a model function and the data at the point x. + /** + evaluate the Poisson LogL given a model function and the data at the point x. return also nPoints as the effective number of used points in the LogL evaluation By default is extended, pass extedend to false if want to be not extended (MultiNomial) - */ - double EvaluatePoissonLogL(const IModelFunction & func, const BinData & data, const double * x, int iWeight, bool extended, unsigned int & nPoints); + */ + double EvaluatePoissonLogL(const IModelFunction & func, const BinData & data, const double * x, int iWeight, bool extended, unsigned int & nPoints); - /** - evaluate the Poisson LogL given a model function and the data at the point x. + /** + evaluate the Poisson LogL given a model function and the data at the point x. return also nPoints as the effective number of used points in the LogL evaluation - */ - void EvaluatePoissonLogLGradient(const IModelFunction & func, const BinData & data, const double * x, double * grad); + */ + void EvaluatePoissonLogLGradient(const IModelFunction & func, const BinData & data, const double * x, double * grad); -// /** -// Parallel evaluate the Chi2 given a model function and the data at the point x. +// /** +// Parallel evaluate the Chi2 given a model function and the data at the point x. // return also nPoints as the effective number of used points in the Chi2 evaluation -// */ -// double ParallelEvalChi2(const IModelFunction & func, const BinData & data, const double * x, unsigned int & nPoints); +// */ +// double ParallelEvalChi2(const IModelFunction & func, const BinData & data, const double * x, unsigned int & nPoints); + + // methods required by dedicate minimizer like Fumili - // methods required by dedicate minimizer like Fumili - - /** - evaluate the residual contribution to the Chi2 given a model function and the BinPoint data + /** + evaluate the residual contribution to the Chi2 given a model function and the BinPoint data and if the pointer g is not null evaluate also the gradient of the residual. - If the function provides parameter derivatives they are used otherwise a simple derivative calculation - is used - */ - double EvaluateChi2Residual(const IModelFunction & func, const BinData & data, const double * x, unsigned int ipoint, double *g = 0); + If the function provides parameter derivatives they are used otherwise a simple derivative calculation + is used + */ + double EvaluateChi2Residual(const IModelFunction & func, const BinData & data, const double * x, unsigned int ipoint, double *g = 0); - /** + /** evaluate the pdf contribution to the LogL given a model function and the BinPoint data. If the pointer g is not null evaluate also the gradient of the pdf. - If the function provides parameter derivatives they are used otherwise a simple derivative calculation - is used - */ - double EvaluatePdf(const IModelFunction & func, const UnBinData & data, const double * x, unsigned int ipoint, double * g = 0); + If the function provides parameter derivatives they are used otherwise a simple derivative calculation + is used + */ + double EvaluatePdf(const IModelFunction & func, const UnBinData & data, const double * x, unsigned int ipoint, double * g = 0); - /** - evaluate the pdf contribution to the Poisson LogL given a model function and the BinPoint data. + /** + evaluate the pdf contribution to the Poisson LogL given a model function and the BinPoint data. If the pointer g is not null evaluate also the gradient of the Poisson pdf. - If the function provides parameter derivatives they are used otherwise a simple derivative calculation - is used - */ - double EvaluatePoissonBinPdf(const IModelFunction & func, const BinData & data, const double * x, unsigned int ipoint, double * g = 0); + If the function provides parameter derivatives they are used otherwise a simple derivative calculation + is used + */ + double EvaluatePoissonBinPdf(const IModelFunction & func, const BinData & data, const double * x, unsigned int ipoint, double * g = 0); + - -} // end namespace FitUtil +} // end namespace FitUtil } // end namespace Fit diff --git a/ThirdParty/RootMinimizers/inc/Fit/FitUtilParallel.h b/ThirdParty/RootMinimizers/inc/Fit/FitUtilParallel.h index 75965f382f73e20cf887176c9a59c3165618839a..2fd8e7c40dfefbd84fc9bd2e655b398aa1cf579b 100644 --- a/ThirdParty/RootMinimizers/inc/Fit/FitUtilParallel.h +++ b/ThirdParty/RootMinimizers/inc/Fit/FitUtilParallel.h @@ -11,7 +11,10 @@ // Header file for class FitUtil -#ifdef _WIN32 // no support for parallel fits on Win32 +#ifndef ROOT_Fit_FitUtilParallel +#define ROOT_Fit_FitUtilParallel + +#ifdef _WIN32 // no support for parallel fits on Win32 #ifdef ROOT_FIT_PARALLEL #undef ROOT_FIT_PARALLEL #endif @@ -19,9 +22,6 @@ #ifdef ROOT_FIT_PARALLEL -#ifndef ROOT_Fit_FitUtilParallel -#define ROOT_Fit_FitUtilParallel - #ifndef ROOT_Math_IParamFunctionfwd #include "Math/IParamFunctionfwd.h" #endif @@ -31,42 +31,42 @@ #endif -namespace ROOT { +namespace ROOT { - namespace Fit { + namespace Fit { typedef ROOT::Math::IParamMultiFunction IModelFunction; - -/** - namespace defining free functions for Fitting parallel mode + +/** + namespace defining free functions for Fitting parallel mode Status: functions are not not completed and are still preliminary @ingroup FitMain -*/ +*/ namespace FitUtilParallel { - /** - evaluate the Chi2 given a model function and the data at the point x. + /** + evaluate the Chi2 given a model function and the data at the point x. return also nPoints as the effective number of used points in the Chi2 evaluation - Use a parallel evaluation spawning multiple threads - */ - double EvaluateChi2(IModelFunction & func, const BinData & data, const double * x, unsigned int & nPoints); + Use a parallel evaluation spawning multiple threads + */ + double EvaluateChi2(IModelFunction & func, const BinData & data, const double * x, unsigned int & nPoints); - double EvaluateLogL(IModelFunction & func, const UnBinData & data, const double * p, unsigned int &nPoints); + double EvaluateLogL(IModelFunction & func, const UnBinData & data, const double * p, unsigned int &nPoints); -} // end namespace FitUtil +} // end namespace FitUtil } // end namespace Fit } // end namespace ROOT -#endif /* ROOT_Fit_FitUtil */ #endif /* ROOT_FIT_PARALLEL */ +#endif /* ROOT_Fit_FitUtil */ diff --git a/ThirdParty/RootMinimizers/inc/Fit/Fitter.h b/ThirdParty/RootMinimizers/inc/Fit/Fitter.h index 3a320c0f55e58fb5a0873c87e19d139560f252fd..7e2e73aded3fcb8c2dd744bbed990f1a01bcecf0 100644 --- a/ThirdParty/RootMinimizers/inc/Fit/Fitter.h +++ b/ThirdParty/RootMinimizers/inc/Fit/Fitter.h @@ -16,11 +16,17 @@ /** @defgroup Fit Fitting and Parameter Estimation -Classes used for fitting (regression analysis) and estimation of parameter values given a data sample. +Classes used for fitting (regression analysis) and estimation of parameter values given a data sample. */ -#ifndef ROOT_Fit_DataVectorfwd -#include "Fit/DataVectorfwd.h" +// #ifndef ROOT_Fit_DataVectorfwd +// #include "Fit/DataVectorfwd.h" +// #endif +#ifndef ROOT_Fit_BinData +#include "Fit/BinData.h" +#endif +#ifndef ROOT_Fit_UnBinData +#include "Fit/UnBinData.h" #endif #ifndef ROOT_Fit_FitConfig @@ -38,27 +44,27 @@ Classes used for fitting (regression analysis) and estimation of parameter value #include <memory> -namespace ROOT { +namespace ROOT { - namespace Math { + namespace Math { class Minimizer; // should maybe put this in a FitMethodFunctionfwd file template<class FunctionType> class BasicFitMethodFunction; // define the normal and gradient function - typedef BasicFitMethodFunction<ROOT::Math::IMultiGenFunction> FitMethodFunction; + typedef BasicFitMethodFunction<ROOT::Math::IMultiGenFunction> FitMethodFunction; typedef BasicFitMethodFunction<ROOT::Math::IMultiGradFunction> FitMethodGradFunction; - } + } /** Namespace for the fitting classes @ingroup Fit */ - namespace Fit { + namespace Fit { /** @defgroup FitMain User Fitting classes @@ -67,124 +73,155 @@ namespace ROOT { @ingroup Fit */ + //___________________________________________________________________________________ -/** - Fitter class, entry point for performing all type of fits. - Fits are performed using the generic ROOT::Fit::Fitter::Fit method. +/** + Fitter class, entry point for performing all type of fits. + Fits are performed using the generic ROOT::Fit::Fitter::Fit method. The inputs are the data points and a model function (using a ROOT::Math::IParamFunction) - The result of the fit is returned and kept internally in the ROOT::Fit::FitResult class. - The configuration of the fit (parameters, options, etc...) are specified in the - ROOT::Math::FitConfig class. - After fitting the config of the fit will be modified to have the new values the resulting - parameter of the fit with step sizes equal to the errors. FitConfig can be preserved with + The result of the fit is returned and kept internally in the ROOT::Fit::FitResult class. + The configuration of the fit (parameters, options, etc...) are specified in the + ROOT::Math::FitConfig class. + After fitting the config of the fit will be modified to have the new values the resulting + parameter of the fit with step sizes equal to the errors. FitConfig can be preserved with initial parameters by calling FitConfig.SetUpdateAfterFit(false); @ingroup FitMain -*/ +*/ class Fitter { -public: +public: - typedef ROOT::Math::IParamMultiFunction IModelFunction; + typedef ROOT::Math::IParamMultiFunction IModelFunction; typedef ROOT::Math::IParamMultiGradFunction IGradModelFunction; - typedef ROOT::Math::IParamFunction IModel1DFunction; - typedef ROOT::Math::IParamGradFunction IGradModel1DFunction; + typedef ROOT::Math::IParamFunction IModel1DFunction; + typedef ROOT::Math::IParamGradFunction IGradModel1DFunction; - typedef ROOT::Math::IMultiGenFunction BaseFunc; - typedef ROOT::Math::IMultiGradFunction BaseGradFunc; + typedef ROOT::Math::IMultiGenFunction BaseFunc; + typedef ROOT::Math::IMultiGradFunction BaseGradFunc; - /** + /** Default constructor - */ - Fitter (); + */ + Fitter (); + + /** + Constructor from a result + */ + Fitter (const std::shared_ptr<FitResult> & result); - /** + + /** Destructor - */ - ~Fitter (); + */ + ~Fitter (); -private: +private: - /** + /** Copy constructor (disabled, class is not copyable) - */ + */ Fitter(const Fitter &); - /** - Assignment operator (disabled, class is not copyable) - */ - Fitter & operator = (const Fitter & rhs); + /** + Assignment operator (disabled, class is not copyable) + */ + Fitter & operator = (const Fitter & rhs); -public: +public: - /** + /** fit a data set using any generic model function If data set is binned a least square fit is performed If data set is unbinned a maximum likelihood fit (not extended) is done - Pre-requisite on the function: - it must implement the 1D or multidimensional parametric function interface - */ - template < class Data , class Function> - bool Fit( const Data & data, const Function & func ) { + Pre-requisite on the function: + it must implement the 1D or multidimensional parametric function interface + */ + template < class Data , class Function> + bool Fit( const Data & data, const Function & func ) { SetFunction(func); return Fit(data); } - /** + /** Fit a binned data set using a least square fit (default method) - */ - bool Fit(const BinData & data) { - return DoLeastSquareFit(data); - } - - /** - Fit a binned data set using a least square fit - */ - bool LeastSquareFit(const BinData & data) { - return DoLeastSquareFit(data); - } - - /** - fit an unbinned data set using loglikelihood method - */ - bool Fit(const UnBinData & data, bool extended = false) { - return DoLikelihoodFit(data, extended); - } + */ + bool Fit(const BinData & data) { + SetData(data); + return DoLeastSquareFit(); + } + bool Fit(const std::shared_ptr<BinData> & data) { + SetData(data); + return DoLeastSquareFit(); + } /** - Likelihood fit (unbinned or unbinned) depending on the type of data - If Binned default is extended - If Unbinned default is NOT extended (for backward compatibility) - */ - template <class Data> - bool LikelihoodFit(const Data & data ) { - return DoLikelihoodFit(data); + Fit a binned data set using a least square fit + */ + bool LeastSquareFit(const BinData & data) { + return Fit(data); } + /** + fit an unbinned data set using loglikelihood method + */ + bool Fit(const UnBinData & data, bool extended = false) { + SetData(data); + return DoUnbinnedLikelihoodFit(extended); + } /** - Likelihood fit using extended or not extended method + Binned Likelihood fit. Default is extended */ - template <class Data> - bool LikelihoodFit(const Data & data, bool extended ) { - return DoLikelihoodFit(data, extended); + bool LikelihoodFit(const BinData & data, bool extended = true) { + SetData(data); + return DoBinnedLikelihoodFit(extended); + } + bool LikelihoodFit(const std::shared_ptr<BinData> & data, bool extended = true) { + SetData(data); + return DoBinnedLikelihoodFit(extended); + } + /** + Unbinned Likelihood fit. Default is not extended + */ + bool LikelihoodFit(const UnBinData & data, bool extended = false) { + SetData(data); + return DoUnbinnedLikelihoodFit(extended); + } + bool LikelihoodFit(const std::shared_ptr<UnBinData> & data, bool extended = false) { + SetData(data); + return DoUnbinnedLikelihoodFit(extended); } - /** + + /** fit a data set using any generic model function - Pre-requisite on the function: - */ - template < class Data , class Function> - bool LikelihoodFit( const Data & data, const Function & func, bool extended) { + Pre-requisite on the function: + */ + template < class Data , class Function> + bool LikelihoodFit( const Data & data, const Function & func, bool extended) { SetFunction(func); - return DoLikelihoodFit(data, extended); + return LikelihoodFit(data, extended); + } + + /** + do a linear fit on a set of bin-data + */ + bool LinearFit(const BinData & data) { + SetData(data); + return DoLinearFit(); + } + bool LinearFit(const std::shared_ptr<BinData> & data) { + SetData(data); + return DoLinearFit(); } + /** - Fit using the a generic FCN function as a C++ callable object implementing - double () (const double *) + Fit using the a generic FCN function as a C++ callable object implementing + double () (const double *) Note that the function dimension (i.e. the number of parameter) is needed in this case For the options see documentation for following methods FitFCN(IMultiGenFunction & fcn,..) */ @@ -192,8 +229,8 @@ public: bool FitFCN(unsigned int npar, Function & fcn, const double * params = 0, unsigned int dataSize = 0, bool chi2fit = false); /** - Set a generic FCN function as a C++ callable object implementing - double () (const double *) + Set a generic FCN function as a C++ callable object implementing + double () (const double *) Note that the function dimension (i.e. the number of parameter) is needed in this case For the options see documentation for following methods FitFCN(IMultiGenFunction & fcn,..) */ @@ -201,67 +238,67 @@ public: bool SetFCN(unsigned int npar, Function & fcn, const double * params = 0, unsigned int dataSize = 0, bool chi2fit = false); /** - Fit using the given FCN function represented by a multi-dimensional function interface - (ROOT::Math::IMultiGenFunction). - Give optionally the initial arameter values, data size to have the fit Ndf correctly - set in the FitResult and flag specifying if it is a chi2 fit. - Note that if the parameters values are not given (params=0) the - current parameter settings are used. The parameter settings can be created before - by using the FitConfig::SetParamsSetting. If they have not been created they are created - automatically when the params pointer is not zero. - Note that passing a params != 0 will set the parameter settings to the new value AND also the + Fit using the given FCN function represented by a multi-dimensional function interface + (ROOT::Math::IMultiGenFunction). + Give optionally the initial arameter values, data size to have the fit Ndf correctly + set in the FitResult and flag specifying if it is a chi2 fit. + Note that if the parameters values are not given (params=0) the + current parameter settings are used. The parameter settings can be created before + by using the FitConfig::SetParamsSetting. If they have not been created they are created + automatically when the params pointer is not zero. + Note that passing a params != 0 will set the parameter settings to the new value AND also the step sizes to some pre-defined value (stepsize = 0.3 * abs(parameter_value) ) */ bool FitFCN(const ROOT::Math::IMultiGenFunction & fcn, const double * params = 0, unsigned int dataSize = 0, bool - chi2fit = false); + chi2fit = false); - /** + /** Fit using a FitMethodFunction interface. Same as method above, but now extra information can be taken from the function class */ - bool FitFCN(const ROOT::Math::FitMethodFunction & fcn, const double * params = 0); + bool FitFCN(const ROOT::Math::FitMethodFunction & fcn, const double * params = 0); /** - Set the FCN function represented by a multi-dimensional function interface + Set the FCN function represented by a multi-dimensional function interface (ROOT::Math::IMultiGenFunction) and optionally the initial parameters See also note above for the initial parameters for FitFCN */ - bool SetFCN(const ROOT::Math::IMultiGenFunction & fcn, const double * params = 0, unsigned int dataSize = 0, bool chi2fit = false); + bool SetFCN(const ROOT::Math::IMultiGenFunction & fcn, const double * params = 0, unsigned int dataSize = 0, bool chi2fit = false); - /** - Set the objective function (FCN) using a FitMethodFunction interface. + /** + Set the objective function (FCN) using a FitMethodFunction interface. Same as method above, but now extra information can be taken from the function class */ - bool SetFCN(const ROOT::Math::FitMethodFunction & fcn, const double * params = 0); + bool SetFCN(const ROOT::Math::FitMethodFunction & fcn, const double * params = 0); /** - Fit using the given FCN function representing a multi-dimensional gradient function - interface (ROOT::Math::IMultiGradFunction). In this case the minimizer will use the - gradient information provided by the function. + Fit using the given FCN function representing a multi-dimensional gradient function + interface (ROOT::Math::IMultiGradFunction). In this case the minimizer will use the + gradient information provided by the function. For the options same consideration as in the previous method */ - bool FitFCN(const ROOT::Math::IMultiGradFunction & fcn, const double * params = 0, unsigned int dataSize = 0, bool chi2fit = false); + bool FitFCN(const ROOT::Math::IMultiGradFunction & fcn, const double * params = 0, unsigned int dataSize = 0, bool chi2fit = false); - /** + /** Fit using a FitMethodGradFunction interface. Same as method above, but now extra information can be taken from the function class */ - bool FitFCN(const ROOT::Math::FitMethodGradFunction & fcn, const double * params = 0); + bool FitFCN(const ROOT::Math::FitMethodGradFunction & fcn, const double * params = 0); /** - Set the FCN function represented by a multi-dimensional gradient function interface + Set the FCN function represented by a multi-dimensional gradient function interface (ROOT::Math::IMultiGenFunction) and optionally the initial parameters See also note above for the initial parameters for FitFCN */ - bool SetFCN(const ROOT::Math::IMultiGradFunction & fcn, const double * params = 0, unsigned int dataSize = 0, bool chi2fit = false); + bool SetFCN(const ROOT::Math::IMultiGradFunction & fcn, const double * params = 0, unsigned int dataSize = 0, bool chi2fit = false); - /** - Set the objective function (FCN) using a FitMethodGradFunction interface. + /** + Set the objective function (FCN) using a FitMethodGradFunction interface. Same as method above, but now extra information can be taken from the function class */ - bool SetFCN(const ROOT::Math::FitMethodGradFunction & fcn, const double * params = 0); + bool SetFCN(const ROOT::Math::FitMethodGradFunction & fcn, const double * params = 0); + - /** fit using user provided FCN with Minuit-like interface If npar = 0 it is assumed that the parameters are specified in the parameter settings created before @@ -280,149 +317,168 @@ public: /** Perform a fit with the previously set FCN function. Require SetFCN before */ - bool FitFCN(); + bool FitFCN(); /** - Perform a simple FCN evaluation. FitResult will be modified and contain the value of the FCN + Perform a simple FCN evaluation. FitResult will be modified and contain the value of the FCN */ - bool EvalFCN(); + bool EvalFCN(); - /** - do a linear fit on a set of bin-data - */ - bool LinearFit(const BinData & data) { return DoLinearFit(data); } - /** + /** Set the fitted function (model function) from a parametric function interface - */ - void SetFunction(const IModelFunction & func, bool useGradient = false); + */ + void SetFunction(const IModelFunction & func, bool useGradient = false); /** Set the fitted function from a parametric 1D function interface */ - void SetFunction(const IModel1DFunction & func, bool useGradient = false); + void SetFunction(const IModel1DFunction & func, bool useGradient = false); - /** + /** Set the fitted function (model function) from a parametric gradient function interface - */ - void SetFunction(const IGradModelFunction & func, bool useGradient = true); + */ + void SetFunction(const IGradModelFunction & func, bool useGradient = true); /** Set the fitted function from 1D gradient parametric function interface */ - void SetFunction(const IGradModel1DFunction & func, bool useGradient = true); + void SetFunction(const IGradModel1DFunction & func, bool useGradient = true); /** get fit result */ - const FitResult & Result() const { + const FitResult & Result() const { assert( fResult.get() ); - return *fResult; - } + return *fResult; + } + /** perform an error analysis on the result using the Hessian Errors are obtaied from the inverse of the Hessian matrix - To be called only after fitting and when a minimizer supporting the Hessian calculations is used + To be called only after fitting and when a minimizer supporting the Hessian calculations is used otherwise an error (false) is returned. A new FitResult with the Hessian result will be produced */ - bool CalculateHessErrors(); + bool CalculateHessErrors(); /** perform an error analysis on the result using MINOS - To be called only after fitting and when a minimizer supporting MINOS is used + To be called only after fitting and when a minimizer supporting MINOS is used otherwise an error (false) is returned. - The result will be appended in the fit result class - Optionally a vector of parameter indeces can be passed for selecting - the parameters to analyse using FitConfig::SetMinosErrors + The result will be appended in the fit result class + Optionally a vector of parameter indeces can be passed for selecting + the parameters to analyse using FitConfig::SetMinosErrors */ - bool CalculateMinosErrors(); + bool CalculateMinosErrors(); /** access to the fit configuration (const method) */ - const FitConfig & Config() const { return fConfig; } + const FitConfig & Config() const { return fConfig; } /** access to the configuration (non const method) */ - FitConfig & Config() { return fConfig; } + FitConfig & Config() { return fConfig; } /** - query if fit is binned. In cse of false teh fit can be unbinned + query if fit is binned. In cse of false teh fit can be unbinned or is not defined (like in case of fitting through a ::FitFCN) */ - bool IsBinFit() const { return fBinFit; } + bool IsBinFit() const { return fBinFit; } /** - return pointer to last used minimizer + return pointer to last used minimizer (is NULL in case fit is not yet done) - This pointer will be valid as far as the data, the objective function - and the fitter class have not been deleted. + This pointer is guranteed to be valid as far as the fitter class is valid and a new fit is not redone. To be used only after fitting. - The pointer should not be stored and will be invalided after performing a new fitting. - In this case a new instance of ROOT::Math::Minimizer will be re-created and can be + The pointer should not be stored and will be invalided after performing a new fitting. + In this case a new instance of ROOT::Math::Minimizer will be re-created and can be obtained calling again GetMinimizer() */ - ROOT::Math::Minimizer * GetMinimizer() const { return fMinimizer.get(); } + ROOT::Math::Minimizer * GetMinimizer() const { return fMinimizer.get(); } /** - return pointer to last used objective function + return pointer to last used objective function (is NULL in case fit is not yet done) - This pointer will be valid as far as the data and the fitter class - have not been deleted. To be used after the fitting. + This pointer will be valid as far as the fitter class + has not been deleted. To be used after the fitting. The pointer should not be stored and will be invalided after performing a new fitting. - In this case a new instance of the function pointer will be re-created and can be - obtained calling again GetFCN() + In this case a new instance of the function pointer will be re-created and can be + obtained calling again GetFCN() */ - ROOT::Math::IMultiGenFunction * GetFCN() const { return fObjFunction.get(); } + ROOT::Math::IMultiGenFunction * GetFCN() const { return fObjFunction.get(); } /** apply correction in the error matrix for the weights for likelihood fits - This method can be called only after a fit. The - passed function (loglw2) is a log-likelihood function impelemented using the - sum of weight squared - When using FitConfig.SetWeightCorrection() this correction is applied + This method can be called only after a fit. The + passed function (loglw2) is a log-likelihood function impelemented using the + sum of weight squared + When using FitConfig.SetWeightCorrection() this correction is applied automatically when doing a likelihood fit (binned or unbinned) */ bool ApplyWeightCorrection(const ROOT::Math::IMultiGenFunction & loglw2, bool minimizeW2L=false); -protected: +protected: - /// least square fit - bool DoLeastSquareFit(const BinData & data); + /// least square fit + bool DoLeastSquareFit(); /// binned likelihood fit - bool DoLikelihoodFit(const BinData & data, bool extended = true); + bool DoBinnedLikelihoodFit( bool extended = true); /// un-binned likelihood fit - bool DoLikelihoodFit(const UnBinData & data, bool extended = false); - /// linear least square fit - bool DoLinearFit(const BinData & data); + bool DoUnbinnedLikelihoodFit( bool extended = false); + /// linear least square fit + bool DoLinearFit(); - // initialize the minimizer - bool DoInitMinimizer(); + // initialize the minimizer + bool DoInitMinimizer(); /// do minimization - bool DoMinimization(const BaseFunc & f, const ROOT::Math::IMultiGenFunction * chifunc = 0); + bool DoMinimization(const BaseFunc & f, const ROOT::Math::IMultiGenFunction * chifunc = 0); // do minimization after having set obj function - bool DoMinimization(const ROOT::Math::IMultiGenFunction * chifunc = 0); - // update config after fit - void DoUpdateFitConfig(); - // get function calls from the FCN - int GetNCallsFromFCN(); + bool DoMinimization(const ROOT::Math::IMultiGenFunction * chifunc = 0); + // update config after fit + void DoUpdateFitConfig(); + // get function calls from the FCN + int GetNCallsFromFCN(); + + + //set data for the fit + void SetData(const FitData & data) { + fData = std::shared_ptr<FitData>(const_cast<FitData*>(&data),DummyDeleter<FitData>()); + } + // set data and function without cloning them + void SetFunctionAndData(const IModelFunction & func, const FitData & data) { + SetData(data); + fFunc = std::shared_ptr<IModelFunction>(const_cast<IModelFunction*>(&func),DummyDeleter<IModelFunction>()); + } + + //set data for the fit using a shared ptr + template <class Data> + void SetData(const std::shared_ptr<Data> & data) { + fData = std::static_pointer_cast<Data>(data); + } + + /// look at the user provided FCN and get data and model function is + /// they derive from ROOT::Fit FCN classes + void ExamineFCN(); - // set 1D function - void DoSetFunction(const IModel1DFunction & func, bool useGrad); - // set generic N-d function - void DoSetFunction(const IModelFunction & func, bool useGrad); + + /// internal functions to get data set and model function from FCN + /// useful for fits done with customized FCN classes + template <class ObjFuncType> + bool GetDataFromFCN(); -private: +private: + bool fUseGradient; // flag to indicate if using gradient or not - bool fBinFit; // flag to indicate if fit is binned + bool fBinFit; // flag to indicate if fit is binned // in case of false the fit is unbinned or undefined) // flag it is used to compute chi2 for binned likelihood fit @@ -430,19 +486,37 @@ private: int fDataSize; // size of data sets (need for Fumili or LM fitters) - IModelFunction * fFunc; // copy of the fitted function containing on output the fit result (managed by FitResult) - FitConfig fConfig; // fitter configuration (options and parameter settings) - std::auto_ptr<ROOT::Fit::FitResult> fResult; //! pointer to the object containing the result of the fit + std::shared_ptr<IModelFunction> fFunc; //! copy of the fitted function containing on output the fit result + + std::shared_ptr<ROOT::Fit::FitResult> fResult; //! pointer to the object containing the result of the fit + + std::shared_ptr<ROOT::Math::Minimizer> fMinimizer; //! pointer to used minimizer - std::auto_ptr<ROOT::Math::Minimizer> fMinimizer; //! pointer to used minimizer + std::shared_ptr<ROOT::Fit::FitData> fData; //! pointer to the fit data (binned or unbinned data) - std::auto_ptr<ROOT::Math::IMultiGenFunction> fObjFunction; //! pointer to used objective function + std::shared_ptr<ROOT::Math::IMultiGenFunction> fObjFunction; //! pointer to used objective function +}; -}; +// internal functions to get data set and model function from FCN +// useful for fits done with customized FCN classes +template <class ObjFuncType> +bool Fitter::GetDataFromFCN() { + ObjFuncType * objfunc = dynamic_cast<ObjFuncType*>(fObjFunction.get() ); + if (objfunc) { + fFunc = objfunc->ModelFunctionPtr(); + fData = objfunc->DataPtr(); + return true; + } + else { + return false; + } +} + + } // end namespace Fit } // end namespace ROOT @@ -459,12 +533,12 @@ private: template<class Function> bool ROOT::Fit::Fitter::FitFCN(unsigned int npar, Function & f, const double * par, unsigned int datasize,bool chi2fit) { - ROOT::Math::WrappedMultiFunction<Function &> wf(f,npar); + ROOT::Math::WrappedMultiFunction<Function &> wf(f,npar); return FitFCN(wf,par,datasize,chi2fit); } template<class Function> bool ROOT::Fit::Fitter::SetFCN(unsigned int npar, Function & f, const double * par, unsigned int datasize,bool chi2fit) { - ROOT::Math::WrappedMultiFunction<Function &> wf(f,npar); + ROOT::Math::WrappedMultiFunction<Function &> wf(f,npar); return SetFCN(wf,par,datasize,chi2fit); } diff --git a/ThirdParty/RootMinimizers/inc/Fit/LogLikelihoodFCN.h b/ThirdParty/RootMinimizers/inc/Fit/LogLikelihoodFCN.h index 5c55a86acb5b43870abfd238c86362f4b84ce5af..885d6d4d1fee73ef3eb1063e914081e3258aa424 100644 --- a/ThirdParty/RootMinimizers/inc/Fit/LogLikelihoodFCN.h +++ b/ThirdParty/RootMinimizers/inc/Fit/LogLikelihoodFCN.h @@ -13,8 +13,8 @@ #ifndef ROOT_Fit_LogLikelihoodFCN #define ROOT_Fit_LogLikelihoodFCN -#ifndef ROOT_Math_FitMethodFunction -#include "Math/FitMethodFunction.h" +#ifndef ROOT_Fit_BasicFCN +#include "Fit/BasicFCN.h" #endif #ifndef ROOT_Math_IParamFunction @@ -35,69 +35,89 @@ #endif #endif -namespace ROOT { +#include <memory> - namespace Fit { +namespace ROOT { + + namespace Fit { //___________________________________________________________________________________ -/** - LogLikelihoodFCN class - for likelihood fits +/** + LogLikelihoodFCN class + for likelihood fits it is template to distinguish gradient and non-gradient case - @ingroup FitMethodFunc -*/ -template<class FunType> -class LogLikelihoodFCN : public ::ROOT::Math::BasicFitMethodFunction<FunType> { - -public: + @ingroup FitMethodFunc +*/ +template<class FunType> +class LogLikelihoodFCN : public BasicFCN<FunType,UnBinData> { +public: + typedef BasicFCN<FunType,UnBinData> BaseFCN; - typedef ::ROOT::Math::BasicFitMethodFunction<FunType> BaseObjFunction; - typedef typename BaseObjFunction::BaseFunction BaseFunction; + typedef ::ROOT::Math::BasicFitMethodFunction<FunType> BaseObjFunction; + typedef typename BaseObjFunction::BaseFunction BaseFunction; typedef ::ROOT::Math::IParamMultiFunction IModelFunction; - /** + /** Constructor from unbin data set and model function (pdf) - */ - LogLikelihoodFCN (const UnBinData & data, const IModelFunction & func, int weight = 0, bool extended = false) : - BaseObjFunction(func.NPar(), data.Size() ), + */ + LogLikelihoodFCN (const std::shared_ptr<UnBinData> & data, const std::shared_ptr<IModelFunction> & func, int weight = 0, bool extended = false) : + BaseFCN( data, func), + fIsExtended(extended), + fWeight(weight), + fNEffPoints(0), + fGrad ( std::vector<double> ( func->NPar() ) ) + {} + + /** + Constructor from unbin data set and model function (pdf) for object managed by users + */ + LogLikelihoodFCN (const UnBinData & data, const IModelFunction & func, int weight = 0, bool extended = false) : + BaseFCN(std::shared_ptr<UnBinData>(const_cast<UnBinData*>(&data), DummyDeleter<UnBinData>()), std::shared_ptr<IModelFunction>(dynamic_cast<IModelFunction*>(func.Clone() ) ) ), fIsExtended(extended), fWeight(weight), - fData(data), - fFunc(func), fNEffPoints(0), fGrad ( std::vector<double> ( func.NPar() ) ) {} - - /** + /** Destructor (no operations) - */ + */ virtual ~LogLikelihoodFCN () {} -private: - // usually copying is non trivial, so we make this unaccessible + /** + Copy constructor + */ + LogLikelihoodFCN(const LogLikelihoodFCN & f) : + BaseFCN(f.DataPtr(), f.ModelFunctionPtr() ), + fIsExtended(f.fIsExtended ), + fWeight( f.fWeight ), + fNEffPoints( f.fNEffPoints ), + fGrad( f.fGrad) + { } - /** - Dummy Copy constructor (private) - */ - LogLikelihoodFCN(const LogLikelihoodFCN &); - /** - Dummy Assignment operator (private) - */ - LogLikelihoodFCN & operator = (const LogLikelihoodFCN &); + /** + Assignment operator + */ + LogLikelihoodFCN & operator = (const LogLikelihoodFCN & rhs) { + SetData(rhs.DataPtr() ); + SetModelFunction(rhs.ModelFunctionPtr() ); + fNEffPoints = rhs.fNEffPoints; + fGrad = rhs.fGrad; + fIsExtended = rhs.fIsExtended; + fWeight = rhs.fWeight; + } -public: /// clone the function (need to return Base for Windows) - virtual BaseFunction * Clone() const { return new LogLikelihoodFCN(fData,fFunc,fWeight,fIsExtended); } + virtual BaseFunction * Clone() const { return new LogLikelihoodFCN(*this); } //using BaseObjFunction::operator(); @@ -106,38 +126,33 @@ public: virtual unsigned int NFitPoints() const { return fNEffPoints; } /// i-th likelihood contribution and its gradient - virtual double DataElement(const double * x, unsigned int i, double * g) const { + virtual double DataElement(const double * x, unsigned int i, double * g) const { if (i==0) this->UpdateNCalls(); - return FitUtil::EvaluatePdf(fFunc, fData, x, i, g); + return FitUtil::EvaluatePdf(BaseFCN::ModelFunction(), BaseFCN::Data(), x, i, g); } // need to be virtual to be instantited - virtual void Gradient(const double *x, double *g) const { + virtual void Gradient(const double *x, double *g) const { // evaluate the chi2 gradient - FitUtil::EvaluateLogLGradient(fFunc, fData, x, g, fNEffPoints); + FitUtil::EvaluateLogLGradient(BaseFCN::ModelFunction(), BaseFCN::Data(), x, g, fNEffPoints); } /// get type of fit method function virtual typename BaseObjFunction::Type_t Type() const { return BaseObjFunction::kLogLikelihood; } - /// access to const reference to the data - virtual const UnBinData & Data() const { return fData; } - /// access to const reference to the model function - virtual const IModelFunction & ModelFunction() const { return fFunc; } - - // Use sum of the weight squared in evaluating the likelihood + // Use sum of the weight squared in evaluating the likelihood // (this is needed for calculating the errors) - void UseSumOfWeightSquare(bool on = true) { - if (fWeight == 0) return; // do nothing if it was not weighted + void UseSumOfWeightSquare(bool on = true) { + if (fWeight == 0) return; // do nothing if it was not weighted if (on) fWeight = 2; else fWeight = 1; } - -protected: + +protected: private: @@ -145,40 +160,38 @@ private: /** Evaluation of the function (required by interface) */ - virtual double DoEval (const double * x) const { + virtual double DoEval (const double * x) const { this->UpdateNCalls(); #ifdef ROOT_FIT_PARALLEL - return FitUtilParallel::EvaluateLogL(fFunc, fData, x, fNEffPoints); -#else - return FitUtil::EvaluateLogL(fFunc, fData, x, fWeight, fIsExtended, fNEffPoints); + return FitUtilParallel::EvaluateLogL(BaseFCN::ModelFunction(), BaseFCN::Data(), x, fNEffPoints); +#else + return FitUtil::EvaluateLogL(BaseFCN::ModelFunction(), BaseFCN::Data(), x, fWeight, fIsExtended, fNEffPoints); #endif - } + } - // for derivatives - virtual double DoDerivative(const double * x, unsigned int icoord ) const { - Gradient(x, &fGrad[0]); - return fGrad[icoord]; + // for derivatives + virtual double DoDerivative(const double * x, unsigned int icoord ) const { + Gradient(x, &fGrad[0]); + return fGrad[icoord]; } - + //data member bool fIsExtended; // flag for indicating if likelihood is extended int fWeight; // flag to indicate if needs to evaluate using weight or weight squared (default weight = 0) - const UnBinData & fData; - const IModelFunction & fFunc; - mutable unsigned int fNEffPoints; // number of effective points used in the fit + mutable unsigned int fNEffPoints; // number of effective points used in the fit mutable std::vector<double> fGrad; // for derivatives -}; +}; // define useful typedef's - typedef LogLikelihoodFCN<ROOT::Math::IMultiGenFunction> LogLikelihoodFunction; - typedef LogLikelihoodFCN<ROOT::Math::IMultiGradFunction> LogLikelihoodGradFunction; + typedef LogLikelihoodFCN<ROOT::Math::IMultiGenFunction> LogLikelihoodFunction; + typedef LogLikelihoodFCN<ROOT::Math::IMultiGradFunction> LogLikelihoodGradFunction; } // end namespace Fit diff --git a/ThirdParty/RootMinimizers/inc/Fit/ParameterSettings.h b/ThirdParty/RootMinimizers/inc/Fit/ParameterSettings.h index 70f3f5a1e128782448ce923fc1d4364124abe5f3..131d4c9d7aca1ed24f79727f5346707571a222fd 100644 --- a/ThirdParty/RootMinimizers/inc/Fit/ParameterSettings.h +++ b/ThirdParty/RootMinimizers/inc/Fit/ParameterSettings.h @@ -20,114 +20,114 @@ #endif -namespace ROOT { +namespace ROOT { - namespace Fit { + namespace Fit { //___________________________________________________________________________________ -/** - Class, describing value, limits and step size of the parameters - Provides functionality also to set/retrieve values, step sizes, limits and fix the - parameters. +/** + Class, describing value, limits and step size of the parameters + Provides functionality also to set/retrieve values, step sizes, limits and fix the + parameters. To be done: add constraints (equality and inequality) as functions of the parameters @ingroup FitMain -*/ +*/ class ParameterSettings { -public: +public: - /** + /** Default constructor - */ - ParameterSettings () : - fValue(0.), fStepSize(0.1), fFix(false), - fLowerLimit(0.), fUpperLimit(0.), fHasLowerLimit(false), fHasUpperLimit(false), - fName("") + */ + ParameterSettings () : + fValue(0.), fStepSize(0.1), fFix(false), + fLowerLimit(0.), fUpperLimit(0.), fHasLowerLimit(false), fHasUpperLimit(false), + fName("") {} - + ///constructor for unlimited named Parameter ParameterSettings(const std::string & name, double val, double err) : - fValue(val), fStepSize(err), fFix(false), - fLowerLimit(0.), fUpperLimit(0.), fHasLowerLimit(false), fHasUpperLimit(false), - fName(name) + fValue(val), fStepSize(err), fFix(false), + fLowerLimit(0.), fUpperLimit(0.), fHasLowerLimit(false), fHasUpperLimit(false), + fName(name) {} - + ///constructor for double limited Parameter - ParameterSettings(const std::string & name, double val, double err, + ParameterSettings(const std::string & name, double val, double err, double min, double max) : - fValue(val), fStepSize(err), fFix(false), - fLowerLimit(0.), fUpperLimit(0.), fHasLowerLimit(false), fHasUpperLimit(false), - fName(name) - { - SetLimits(min,max); + fValue(val), fStepSize(err), fFix(false), + fLowerLimit(0.), fUpperLimit(0.), fHasLowerLimit(false), fHasUpperLimit(false), + fName(name) + { + SetLimits(min,max); } ///constructor for fixed Parameter - ParameterSettings(const std::string & name, double val) : - fValue(val), fStepSize(0), fFix(true), - fLowerLimit(0.), fUpperLimit(0.), fHasLowerLimit(false), fHasUpperLimit(false), - fName(name) + ParameterSettings(const std::string & name, double val) : + fValue(val), fStepSize(0), fFix(true), + fLowerLimit(0.), fUpperLimit(0.), fHasLowerLimit(false), fHasUpperLimit(false), + fName(name) {} - /// set value and name (unlimited parameter) - void Set(const std::string & name, double value, double step) { - SetName(name); - SetValue(value); + /// set value and name (unlimited parameter) + void Set(const std::string & name, double value, double step) { + SetName(name); + SetValue(value); SetStepSize(step); } /// set a limited parameter - void Set(const std::string & name, double value, double step, double lower, double upper ) { - SetName(name); - SetValue(value); + void Set(const std::string & name, double value, double step, double lower, double upper ) { + SetName(name); + SetValue(value); SetStepSize(step); - SetLimits(lower,upper); + SetLimits(lower,upper); } /// set a fixed parameter - void Set(const std::string & name, double value) { - SetName(name); - SetValue(value); + void Set(const std::string & name, double value) { + SetName(name); + SetValue(value); Fix(); } - /** + /** Destructor (no operations) - */ - ~ParameterSettings () {} + */ + ~ParameterSettings () {} - /// copy constructor and assignment operators (leave them to the compiler) + /// copy constructor and assignment operators (leave them to the compiler) -public: +public: /// return parameter value - double Value() const { return fValue; } - /// return step size - double StepSize() const { return fStepSize; } + double Value() const { return fValue; } + /// return step size + double StepSize() const { return fStepSize; } /// return lower limit value double LowerLimit() const {return fLowerLimit;} /// return upper limit value double UpperLimit() const {return fUpperLimit;} - /// check if is fixed + /// check if is fixed bool IsFixed() const { return fFix; } /// check if parameter has lower limit bool HasLowerLimit() const {return fHasLowerLimit; } /// check if parameter has upper limit bool HasUpperLimit() const {return fHasUpperLimit; } /// check if is bound - bool IsBound() const { return fHasLowerLimit || fHasUpperLimit; } - /// check if is double bound (upper AND lower limit) - bool IsDoubleBound() const { return fHasLowerLimit && fHasUpperLimit; } - /// return name - const std::string & Name() const { return fName; } + bool IsBound() const { return fHasLowerLimit || fHasUpperLimit; } + /// check if is double bound (upper AND lower limit) + bool IsDoubleBound() const { return fHasLowerLimit && fHasUpperLimit; } + /// return name + const std::string & Name() const { return fName; } /** interaction **/ @@ -140,61 +140,62 @@ public: void Release() {fFix = false;} /// set the value void SetValue(double val) {fValue = val;} - /// set the step size + /// set the step size void SetStepSize(double err) {fStepSize = err;} - /// set a double side limit, + /// set a double side limit, /// if low == up the parameter is fixed if low > up the limits are removed void SetLimits(double low, double up) { - - if ( low > up ) { - RemoveLimits(); - return; + + if ( low > up ) { + RemoveLimits(); + return; } - if (low == up && low == fValue) { - Fix(); - return; + if (low == up && low == fValue) { + Fix(); + return; } - if (low > fValue || up < fValue) { - MATH_ERROR_MSG("ParameterSettings","Invalid lower/upper bounds - ignoring the bounds "); + if (low > fValue || up < fValue) { + MATH_INFO_MSG("ParameterSettings","lower/upper bounds outside current parameter value. The value will be set to (low+up)/2 "); + fValue = 0.5 * (up+low); } - fLowerLimit = low; + fLowerLimit = low; fUpperLimit = up; - fHasLowerLimit = true; + fHasLowerLimit = true; fHasUpperLimit = true; } /// set a single upper limit void SetUpperLimit(double up) { - fLowerLimit = 0.; + fLowerLimit = 0.; fUpperLimit = up; - fHasLowerLimit = false; + fHasLowerLimit = false; fHasUpperLimit = true; } - /// set a single lower limit + /// set a single lower limit void SetLowerLimit(double low) { - fLowerLimit = low; + fLowerLimit = low; fUpperLimit = 0.; - fHasLowerLimit = true; + fHasLowerLimit = true; fHasUpperLimit = false; } /// remove all limit void RemoveLimits() { - fLowerLimit = 0.; + fLowerLimit = 0.; fUpperLimit = 0.; - fHasLowerLimit = false; + fHasLowerLimit = false; fHasUpperLimit = false; } - - -protected: -private: +protected: + + +private: double fValue; // parameter value double fStepSize; // parameter step size (used by minimizer) - bool fFix; // flag to control if parameter is fixed + bool fFix; // flag to control if parameter is fixed double fLowerLimit; // lower parameter limit double fUpperLimit; // upper parameter limit bool fHasLowerLimit; // flag to control lower parameter limit @@ -202,7 +203,7 @@ private: std::string fName; // parameter name -}; +}; } // end namespace Fit diff --git a/ThirdParty/RootMinimizers/inc/Fit/PoissonLikelihoodFCN.h b/ThirdParty/RootMinimizers/inc/Fit/PoissonLikelihoodFCN.h index 197ff0401fc5e236bd7959bed267de66fe80e749..e98f5ba81ed31b40fef9449916f99ea2c3eeb3dd 100644 --- a/ThirdParty/RootMinimizers/inc/Fit/PoissonLikelihoodFCN.h +++ b/ThirdParty/RootMinimizers/inc/Fit/PoissonLikelihoodFCN.h @@ -13,8 +13,8 @@ #ifndef ROOT_Fit_PoissonLikelihoodFCN #define ROOT_Fit_PoissonLikelihoodFCN -#ifndef ROOT_Math_FitMethodunction -#include "Math/FitMethodFunction.h" +#ifndef ROOT_Fit_BasicFCN +#include "Fit/BasicFCN.h" #endif #ifndef ROOT_Math_IParamFunction @@ -29,6 +29,9 @@ #include "Fit/FitUtil.h" #endif + +#include <memory> + //#define PARALLEL // #ifdef PARALLEL // #ifndef ROOT_Fit_FitUtilParallel @@ -50,10 +53,11 @@ namespace ROOT { @ingroup FitMethodFunc */ template<class FunType> -class PoissonLikelihoodFCN : public ::ROOT::Math::BasicFitMethodFunction<FunType> { +class PoissonLikelihoodFCN : public BasicFCN<FunType,BinData> { public: + typedef BasicFCN<FunType,BinData> BaseFCN; typedef ::ROOT::Math::BasicFitMethodFunction<FunType> BaseObjFunction; typedef typename BaseObjFunction::BaseFunction BaseFunction; @@ -64,12 +68,21 @@ public: /** Constructor from unbin data set and model function (pdf) */ + PoissonLikelihoodFCN (const std::shared_ptr<BinData> & data, const std::shared_ptr<IModelFunction> & func, int weight = 0, bool extended = true ) : + BaseFCN( data, func), + fIsExtended(extended), + fWeight(weight), + fNEffPoints(0), + fGrad ( std::vector<double> ( func->NPar() ) ) + { } + + /** + Constructor from unbin data set and model function (pdf) managed by the users + */ PoissonLikelihoodFCN (const BinData & data, const IModelFunction & func, int weight = 0, bool extended = true ) : - BaseObjFunction(func.NPar(), data.Size() ), + BaseFCN(std::shared_ptr<BinData>(const_cast<BinData*>(&data), DummyDeleter<BinData>()), std::shared_ptr<IModelFunction>(dynamic_cast<IModelFunction*>(func.Clone() ) ) ), fIsExtended(extended), fWeight(weight), - fData(data), - fFunc(func), fNEffPoints(0), fGrad ( std::vector<double> ( func.NPar() ) ) { } @@ -78,25 +91,34 @@ public: /** Destructor (no operations) */ - ~PoissonLikelihoodFCN () {} - -private: - // usually copying is non trivial, so we declare but don't implement them + virtual ~PoissonLikelihoodFCN () {} /** Copy constructor */ - PoissonLikelihoodFCN(const PoissonLikelihoodFCN &); + PoissonLikelihoodFCN(const PoissonLikelihoodFCN & f) : + BaseFCN(f.DataPtr(), f.ModelFunctionPtr() ), + fIsExtended(f.fIsExtended ), + fWeight( f.fWeight ), + fNEffPoints( f.fNEffPoints ), + fGrad( f.fGrad) + { } /** Assignment operator */ - PoissonLikelihoodFCN & operator = (const PoissonLikelihoodFCN &); + PoissonLikelihoodFCN & operator = (const PoissonLikelihoodFCN & rhs) { + SetData(rhs.DataPtr() ); + SetModelFunction(rhs.ModelFunctionPtr() ); + fNEffPoints = rhs.fNEffPoints; + fGrad = rhs.fGrad; + fIsExtended = rhs.fIsExtended; + fWeight = rhs.fWeight; + } -public: /// clone the function (need to return Base for Windows) - virtual BaseFunction * Clone() const { return new PoissonLikelihoodFCN(fData,fFunc,fWeight,fIsExtended); } + virtual BaseFunction * Clone() const { return new PoissonLikelihoodFCN(*this); } // effective points used in the fit virtual unsigned int NFitPoints() const { return fNEffPoints; } @@ -104,36 +126,30 @@ public: /// i-th likelihood element and its gradient virtual double DataElement(const double * x, unsigned int i, double * g) const { if (i==0) this->UpdateNCalls(); - return FitUtil::EvaluatePoissonBinPdf(fFunc, fData, x, i, g); + return FitUtil::EvaluatePoissonBinPdf(BaseFCN::ModelFunction(), BaseFCN::Data(), x, i, g); } /// evaluate gradient virtual void Gradient(const double *x, double *g) const { // evaluate the chi2 gradient - FitUtil::EvaluatePoissonLogLGradient(fFunc, fData, x, g ); + FitUtil::EvaluatePoissonLogLGradient(BaseFCN::ModelFunction(), BaseFCN::Data(), x, g ); } /// get type of fit method function virtual typename BaseObjFunction::Type_t Type() const { return BaseObjFunction::kLogLikelihood; } - /// access to const reference to the data - virtual const BinData & Data() const { return fData; } - - /// access to const reference to the model function - virtual const IModelFunction & ModelFunction() const { return fFunc; } - bool IsWeighted() const { return (fWeight != 0); } - // Use the weights in evaluating the likelihood - void UseSumOfWeights() { - if (fWeight == 0) return; // do nothing if it was not weighted + // Use the weights in evaluating the likelihood + void UseSumOfWeights() { + if (fWeight == 0) return; // do nothing if it was not weighted fWeight = 1; } - // Use sum of the weight squared in evaluating the likelihood + // Use sum of the weight squared in evaluating the likelihood // (this is needed for calculating the errors) - void UseSumOfWeightSquare(bool on = true) { - if (fWeight == 0) return; // do nothing if it was not weighted + void UseSumOfWeightSquare(bool on = true) { + if (fWeight == 0) return; // do nothing if it was not weighted if (on) fWeight = 2; else fWeight = 1; } @@ -149,7 +165,7 @@ private: */ virtual double DoEval (const double * x) const { this->UpdateNCalls(); - return FitUtil::EvaluatePoissonLogL(fFunc, fData, x, fWeight, fIsExtended, fNEffPoints); + return FitUtil::EvaluatePoissonLogL(BaseFCN::ModelFunction(), BaseFCN::Data(), x, fWeight, fIsExtended, fNEffPoints); } // for derivatives @@ -164,12 +180,8 @@ private: bool fIsExtended; // flag to indicate if is extended (when false is a Multinomial lieklihood), default is true int fWeight; // flag to indicate if needs to evaluate using weight or weight squared (default weight = 0) - const BinData & fData; - const IModelFunction & fFunc; - mutable unsigned int fNEffPoints; // number of effective points used in the fit - - + mutable std::vector<double> fGrad; // for derivatives }; diff --git a/ThirdParty/RootMinimizers/inc/Fit/SparseData.h b/ThirdParty/RootMinimizers/inc/Fit/SparseData.h index 129e0215e0be171031a74ee88341c5b545a19066..148784d66c74d9c4dfbd99360ae66010882320e3 100644 --- a/ThirdParty/RootMinimizers/inc/Fit/SparseData.h +++ b/ThirdParty/RootMinimizers/inc/Fit/SparseData.h @@ -22,18 +22,18 @@ #include "Fit/BinData.h" #endif -namespace ROOT { +namespace ROOT { - namespace Fit { + namespace Fit { - // This is a proxy to a list<Box> + // This is a proxy to a std::list<Box> class ProxyListBox; - class SparseData : public FitData { + class SparseData : public FitData { public: //Constructor with a vector SparseData(std::vector<double>& min, std::vector<double>& max); - + //Constructor with a dimension and two arrays SparseData(const unsigned int dim, double min[], double max[]); @@ -46,10 +46,10 @@ namespace ROOT { unsigned int NDim() const; // Adds a new bin specified by the vectors - void Add(std::vector<double>& min, std::vector<double>& max, + void Add(std::vector<double>& min, std::vector<double>& max, const double content, const double error = 1.0); - - void GetPoint(const unsigned int i, + + void GetPoint(const unsigned int i, std::vector<double>& min, std::vector<double>&max, double& content, double& error); @@ -62,13 +62,13 @@ namespace ROOT { void GetBinDataIntegral(BinData&) const; // Same as before, but including zero content bins void GetBinDataNoZeros(BinData&) const; - - private : + + private : ProxyListBox *fList; }; - + } // end namespace Fit - + } // end namespace ROOT diff --git a/ThirdParty/RootMinimizers/inc/Fit/UnBinData.h b/ThirdParty/RootMinimizers/inc/Fit/UnBinData.h index c072a0ea64c674ff00f80607a453e9d24c058150..ea5d6acceb8b2eb549a79adb7bab44ecced403f7 100644 --- a/ThirdParty/RootMinimizers/inc/Fit/UnBinData.h +++ b/ThirdParty/RootMinimizers/inc/Fit/UnBinData.h @@ -23,30 +23,30 @@ -namespace ROOT { +namespace ROOT { - namespace Fit { + namespace Fit { //___________________________________________________________________________________ -/** +/** Class describing the unbinned data sets (just x coordinates values) of any dimensions - There is the option to construct UnBindata copying the data in (using the DataVector class) - or using pointer to external data (DataWrapper) class. - In general is found to be more efficient to copy the data. + There is the option to construct UnBindata copying the data in (using the DataVector class) + or using pointer to external data (DataWrapper) class. + In general is found to be more efficient to copy the data. In case of really large data sets for limiting memory consumption then the other option can be used - Specialized constructor exists for using external data up to 3 dimensions. + Specialized constructor exists for using external data up to 3 dimensions. - When the data are copying in the number of points can be set later (or re-set) using Initialize and - the data are inserted one by one using the Add method. - It is mandatory to set the size before using the Add method. + When the data are copying in the number of points can be set later (or re-set) using Initialize and + the data are inserted one by one using the Add method. + It is mandatory to set the size before using the Add method. - @ingroup FitData -*/ -class UnBinData : public FitData { + @ingroup FitData +*/ +class UnBinData : public FitData { -public : +public : /** constructor from dimension of point and max number of points (to pre-allocate vector) @@ -86,19 +86,19 @@ public : constructor for multi-dim external data (data are not copied inside) Uses as argument an iterator of a list (or vector) containing the const double * of the data An example could be the std::vector<const double *>::begin - In case of weighted data, the external data must have a dim+1 lists of data + In case of weighted data, the external data must have a dim+1 lists of data The apssed dim refers just to the coordinate size */ - template<class Iterator> - UnBinData(unsigned int n, unsigned int dim, Iterator dataItr, bool isWeighted = false ) : - FitData( ), - fDim(dim), + template<class Iterator> + UnBinData(unsigned int n, unsigned int dim, Iterator dataItr, bool isWeighted = false ) : + FitData( ), + fDim(dim), fPointSize( (isWeighted) ? dim +1 : dim), fNPoints(n), fDataVector(0) - { + { fDataWrapper = new DataWrapper(fPointSize, dataItr); - } + } /** constructor for 1D data and a range (data are copied inside according to the given range) @@ -107,13 +107,13 @@ public : /** constructor for 2D data and a range (data are copied inside according to the given range) - or 1 1D data set + weight. If is weighted dataY is the pointer to the list of the weights + or 1 1D data set + weight. If is weighted dataY is the pointer to the list of the weights */ UnBinData(unsigned int maxpoints, const double * dataX, const double * dataY, const DataRange & range, bool isWeighted = false); /** - constructor for 3D data and a range (data are copied inside according to the given range) - or a 2D data set + weights. If is weighted dataZ is the pointer to the list of the weights + constructor for 3D data and a range (data are copied inside according to the given range) + or a 2D data set + weights. If is weighted dataZ is the pointer to the list of the weights */ UnBinData(unsigned int maxpoints, const double * dataX, const double * dataY, const double * dataZ, const DataRange & range, bool isWeighted = false); @@ -122,85 +122,85 @@ public : Uses as argument an iterator of a list (or vector) containing the const double * of the data An example could be the std::vector<const double *>::begin */ - template<class Iterator> - UnBinData(unsigned int maxpoints, unsigned int dim, Iterator dataItr, const DataRange & range, bool isWeighted = false ) : - FitData( ), - fDim(dim), + template<class Iterator> + UnBinData(unsigned int maxpoints, unsigned int dim, Iterator dataItr, const DataRange & range, bool isWeighted = false ) : + FitData( ), + fDim(dim), fPointSize( (isWeighted) ? dim +1 : dim), fNPoints(0), fDataVector(0), fDataWrapper(0) - { - unsigned int n = fPointSize*maxpoints; + { + unsigned int n = fPointSize*maxpoints; if ( n > MaxSize() ) { MATH_ERROR_MSGVAL("UnBinData","Invalid data size n - no allocation done", n ); } - else if (n > 0) { + else if (n > 0) { fDataVector = new DataVector(n); // use data wrapper to get the data - ROOT::Fit::DataWrapper wdata(fPointSize, dataItr); - for (unsigned int i = 0; i < maxpoints; ++i) { + ROOT::Fit::DataWrapper wdata(fPointSize, dataItr); + for (unsigned int i = 0; i < maxpoints; ++i) { bool isInside = true; - for (unsigned int icoord = 0; icoord < dim; ++icoord) - isInside &= range.IsInside( wdata.Coords(i)[icoord], icoord ); + for (unsigned int icoord = 0; icoord < dim; ++icoord) + isInside &= range.IsInside( wdata.Coords(i)[icoord], icoord ); // treat here the weight as an extra coordinate - if ( isInside ) Add(wdata.Coords(i)); + if ( isInside ) Add(wdata.Coords(i)); } if (fNPoints < maxpoints) (fDataVector->Data()).resize(fPointSize*fNPoints); - } + } } -private: - /// copy constructor (private) +private: + /// copy constructor (private) UnBinData(const UnBinData &) : FitData() {} - /// assignment operator (private) - UnBinData & operator= (const UnBinData &) { return *this; } + /// assignment operator (private) + UnBinData & operator= (const UnBinData &) { return *this; } -public: +public: #ifdef LATER /** Create from a compatible UnBinData set */ - - UnBinData (const UnBinData & data , const DataOptions & opt, const DataRange & range) : - DataVector(opt,range, data.DataSize() ), + + UnBinData (const UnBinData & data , const DataOptions & opt, const DataRange & range) : + DataVector(opt,range, data.DataSize() ), fDim(data.fDim), fPointSize(data.fPointSize), - fNPoints(data.fNPoints) + fNPoints(data.fNPoints) { -// for (Iterator itr = begin; itr != end; ++itr) +// for (Iterator itr = begin; itr != end; ++itr) // if (itr->IsInRange(range) ) -// Add(*itr); - } +// Add(*itr); + } #endif /** destructor, delete pointer to internal data or external data wrapper */ virtual ~UnBinData() { - if (fDataVector) delete fDataVector; - if (fDataWrapper) delete fDataWrapper; + if (fDataVector) delete fDataVector; + if (fDataWrapper) delete fDataWrapper; } /** preallocate a data set given size and dimension of the coordinates if a vector already exists with correct dimension (point size) extend the existing one - to a total size of maxpoints (equivalent to a Resize) + to a total size of maxpoints (equivalent to a Resize) */ void Initialize(unsigned int maxpoints, unsigned int dim = 1, bool isWeighted = false); - + /** add one dim coordinate data (unweighted) */ - void Add(double x) { - int index = fNPoints*PointSize(); + void Add(double x) { + int index = fNPoints*PointSize(); assert(fDataVector != 0); assert(PointSize() == 1); - assert (index + PointSize() <= DataSize() ); + assert (index + PointSize() <= DataSize() ); (fDataVector->Data())[ index ] = x; @@ -212,11 +212,11 @@ public: add 2-dim coordinate data can also be used to add 1-dim data with a weight */ - void Add(double x, double y) { - int index = fNPoints*PointSize(); + void Add(double x, double y) { + int index = fNPoints*PointSize(); assert(fDataVector != 0); assert(PointSize() == 2); - assert (index + PointSize() <= DataSize() ); + assert (index + PointSize() <= DataSize() ); (fDataVector->Data())[ index ] = x; (fDataVector->Data())[ index+1 ] = y; @@ -228,11 +228,11 @@ public: add 3-dim coordinate data can also be used to add 2-dim data with a weight */ - void Add(double x, double y, double z) { - int index = fNPoints*PointSize(); + void Add(double x, double y, double z) { + int index = fNPoints*PointSize(); assert(fDataVector != 0); assert(PointSize() == 3); - assert (index + PointSize() <= DataSize() ); + assert (index + PointSize() <= DataSize() ); (fDataVector->Data())[ index ] = x; (fDataVector->Data())[ index+1 ] = y; @@ -244,16 +244,16 @@ public: /** add multi-dim coordinate data */ - void Add(const double *x) { - int index = fNPoints*fPointSize; + void Add(const double *x) { + int index = fNPoints*fPointSize; assert(fDataVector != 0); - assert (index + PointSize() <= DataSize() ); + assert (index + PointSize() <= DataSize() ); double * itr = &( (fDataVector->Data()) [ index ]); - for (unsigned int i = 0; i < fDim; ++i) - *itr++ = x[i]; + for (unsigned int i = 0; i < fDim; ++i) + *itr++ = x[i]; fNPoints++; } @@ -261,16 +261,16 @@ public: /** add multi-dim coordinate data + weight */ - void Add(const double *x, double w) { - int index = fNPoints*fPointSize; + void Add(const double *x, double w) { + int index = fNPoints*fPointSize; assert(fDataVector != 0); - assert (index + PointSize() <= DataSize() ); + assert (index + PointSize() <= DataSize() ); double * itr = &( (fDataVector->Data()) [ index ]); - for (unsigned int i = 0; i < fDim; ++i) - *itr++ = x[i]; + for (unsigned int i = 0; i < fDim; ++i) + *itr++ = x[i]; *itr = w; fNPoints++; @@ -279,79 +279,79 @@ public: /** return pointer to coordinate data */ - const double * Coords(unsigned int ipoint) const { - if (fDataVector) + const double * Coords(unsigned int ipoint) const { + if (fDataVector) return &( (fDataVector->Data()) [ ipoint*fPointSize ] ); - else - return fDataWrapper->Coords(ipoint); + else + return fDataWrapper->Coords(ipoint); } - bool IsWeighted() const { - return (fPointSize == fDim+1); + bool IsWeighted() const { + return (fPointSize == fDim+1); } - double Weight(unsigned int ipoint) const { - if (fPointSize == fDim) return 1; - if (fDataVector ) + double Weight(unsigned int ipoint) const { + if (fPointSize == fDim) return 1; + if (fDataVector ) return (fDataVector->Data()) [ ipoint*fPointSize + 1 ] ; - else - return 0; // weights are not supported for wrapper data sets + else + return 0; // weights are not supported for wrapper data sets } /** - resize the vector to the given npoints + resize the vector to the given npoints */ - void Resize (unsigned int npoints); + void Resize (unsigned int npoints); /** - return number of contained points - */ - unsigned int NPoints() const { return fNPoints; } + return number of contained points + */ + unsigned int NPoints() const { return fNPoints; } /** - return number of contained points - */ + return number of contained points + */ unsigned int Size() const { return fNPoints; } /** return coordinate data dimension - */ - unsigned int NDim() const { return fDim; } + */ + unsigned int NDim() const { return fDim; } /** - return point size. For unweighted data is equivalent to coordinate dimension, + return point size. For unweighted data is equivalent to coordinate dimension, for weighted data is NDim()+1 */ - unsigned int PointSize() const { - return fPointSize; + unsigned int PointSize() const { + return fPointSize; } /** - return size of internal data vector (is 0 for external data) + return size of internal data vector (is 0 for external data) */ - unsigned int DataSize() const { + unsigned int DataSize() const { return (fDataVector) ? fDataVector->Size() : 0; } -protected: +protected: void SetNPoints(unsigned int n) { fNPoints = n; } -private: +private: unsigned int fDim; // coordinate data dimension unsigned int fPointSize; // poit size dimension (coordinate + weight) unsigned int fNPoints; // numer of fit points - + DataVector * fDataVector; // pointer to internal data vector (null for external data) DataWrapper * fDataWrapper; // pointer to structure wrapping external data (null when data are copied in) -}; +}; + - } // end namespace Fit } // end namespace ROOT diff --git a/ThirdParty/RootMinimizers/inc/Math/BasicMinimizer.h b/ThirdParty/RootMinimizers/inc/Math/BasicMinimizer.h index fc43aa7795c190c3987f9bb2a7a8c3872ff0265d..6c2dfbbdf7ee7fbafb3056f1f3a2f80ad84f7f22 100644 --- a/ThirdParty/RootMinimizers/inc/Math/BasicMinimizer.h +++ b/ThirdParty/RootMinimizers/inc/Math/BasicMinimizer.h @@ -34,26 +34,26 @@ #include <vector> #include <map> -#include <string> +#include <string> -namespace ROOT { +namespace ROOT { -namespace Math { +namespace Math { class MinimTransformFunction; //_______________________________________________________________________________ -/** - Base Minimizer class, which defines the basic funcionality of various minimizer - implementations (apart from Minuit and Minuit2) - It provides support for storing parameter values, step size, - parameter transofrmation etc.. in case real minimizer impelmentations do not provide - such functionality. - This is an internal class and should not be used directly by the user +/** + Base Minimizer class, which defines the basic funcionality of various minimizer + implementations (apart from Minuit and Minuit2) + It provides support for storing parameter values, step size, + parameter transofrmation etc.. in case real minimizer impelmentations do not provide + such functionality. + This is an internal class and should not be used directly by the user @ingroup MultiMin */ @@ -61,73 +61,73 @@ namespace Math { class BasicMinimizer : public ROOT::Math::Minimizer { -public: +public: - /** + /** Default constructor - */ - BasicMinimizer ( ); + */ + BasicMinimizer ( ); - /** - Destructor - */ - virtual ~BasicMinimizer (); + /** + Destructor + */ + virtual ~BasicMinimizer (); private: // usually copying is non trivial, so we make this unaccessible - /** + /** Copy constructor - */ + */ BasicMinimizer(const BasicMinimizer &) : Minimizer() {} - /** + /** Assignment operator - */ - BasicMinimizer & operator = (const BasicMinimizer & rhs) { + */ + BasicMinimizer & operator = (const BasicMinimizer & rhs) { if (this == &rhs) return *this; // time saving self-test return *this; } -public: +public: /// set the function to minimize - virtual void SetFunction(const ROOT::Math::IMultiGenFunction & func); + virtual void SetFunction(const ROOT::Math::IMultiGenFunction & func); /// set gradient the function to minimize - virtual void SetFunction(const ROOT::Math::IMultiGradFunction & func); + virtual void SetFunction(const ROOT::Math::IMultiGradFunction & func); - /// set free variable - virtual bool SetVariable(unsigned int ivar, const std::string & name, double val, double step); + /// set free variable + virtual bool SetVariable(unsigned int ivar, const std::string & name, double val, double step); /// set lower limit variable (override if minimizer supports them ) virtual bool SetLowerLimitedVariable(unsigned int ivar , const std::string & name , double val , double step , double lower ); /// set upper limit variable (override if minimizer supports them ) - virtual bool SetUpperLimitedVariable(unsigned int ivar , const std::string & name , double val , double step , double upper ); + virtual bool SetUpperLimitedVariable(unsigned int ivar , const std::string & name , double val , double step , double upper ); /// set upper/lower limited variable (override if minimizer supports them ) - virtual bool SetLimitedVariable(unsigned int ivar , const std::string & name , double val , double step , double /* lower */, double /* upper */); + virtual bool SetLimitedVariable(unsigned int ivar , const std::string & name , double val , double step , double /* lower */, double /* upper */); /// set fixed variable (override if minimizer supports them ) - virtual bool SetFixedVariable(unsigned int /* ivar */, const std::string & /* name */, double /* val */); - /// set the value of an existing variable + virtual bool SetFixedVariable(unsigned int /* ivar */, const std::string & /* name */, double /* val */); + /// set the value of an existing variable virtual bool SetVariableValue(unsigned int ivar, double val ); /// set the values of all existing variables (array must be dimensioned to the size of existing parameters) virtual bool SetVariableValues(const double * x); /// set the step size of an already existing variable virtual bool SetVariableStepSize(unsigned int ivar, double step ); - /// set the lower-limit of an already existing variable + /// set the lower-limit of an already existing variable virtual bool SetVariableLowerLimit(unsigned int ivar, double lower); - /// set the upper-limit of an already existing variable + /// set the upper-limit of an already existing variable virtual bool SetVariableUpperLimit(unsigned int ivar, double upper); - /// set the limits of an already existing variable - virtual bool SetVariableLimits(unsigned int ivar, double lower, double upper); + /// set the limits of an already existing variable + virtual bool SetVariableLimits(unsigned int ivar, double lower, double upper); /// fix an existing variable virtual bool FixVariable(unsigned int ivar); /// release an existing variable virtual bool ReleaseVariable(unsigned int ivar); /// query if an existing variable is fixed (i.e. considered constant in the minimization) - /// note that by default all variables are not fixed + /// note that by default all variables are not fixed virtual bool IsFixedVariable(unsigned int ivar) const; /// get variable settings in a variable object (like ROOT::Fit::ParamsSettings) virtual bool GetVariableSettings(unsigned int ivar, ROOT::Fit::ParameterSettings & varObj) const; @@ -138,30 +138,30 @@ public: virtual int VariableIndex(const std::string & name) const; /// method to perform the minimization - virtual bool Minimize(); + virtual bool Minimize(); /// return minimum function value - virtual double MinValue() const { return fMinVal; } + virtual double MinValue() const { return fMinVal; } - /// return pointer to X values at the minimum - virtual const double * X() const { return &fValues.front(); } + /// return pointer to X values at the minimum + virtual const double * X() const { return &fValues.front(); } /// number of dimensions - virtual unsigned int NDim() const { return fDim; } + virtual unsigned int NDim() const { return fDim; } /// number of free variables (real dimension of the problem) - virtual unsigned int NFree() const; + virtual unsigned int NFree() const; /// total number of parameter defined - virtual unsigned int NPar() const { return fValues.size(); } - - /// return pointer to used objective function + virtual unsigned int NPar() const { return fValues.size(); } + + /// return pointer to used objective function const ROOT::Math::IMultiGenFunction * ObjFunction() const { return fObjFunc; } - /// return pointer to used gradient object function (NULL if gradient is not supported) + /// return pointer to used gradient object function (NULL if gradient is not supported) const ROOT::Math::IMultiGradFunction * GradObjFunction() const; - /// return transformation function (NULL if not having a transformation) + /// return transformation function (NULL if not having a transformation) const ROOT::Math::MinimTransformFunction * TransformFunction() const; /// print result of minimization @@ -170,33 +170,33 @@ public: /// accessor methods virtual const double * StepSizes() const { return &fSteps.front(); } -protected: +protected: - bool CheckDimension() const; + bool CheckDimension() const; - bool CheckObjFunction() const; + bool CheckObjFunction() const; MinimTransformFunction * CreateTransformation(std::vector<double> & startValues, const ROOT::Math::IMultiGradFunction * func = 0); void SetFinalValues(const double * x); - + void SetMinValue(double val) { fMinVal = val; } -private: - - // dimension of the function to be minimized - unsigned int fDim; +private: + + // dimension of the function to be minimized + unsigned int fDim; + + const ROOT::Math::IMultiGenFunction * fObjFunc; - const ROOT::Math::IMultiGenFunction * fObjFunc; - - double fMinVal; + double fMinVal; std::vector<double> fValues; std::vector<double> fSteps; std::vector<std::string> fNames; std::vector<ROOT::Math::EMinimVariableType> fVarTypes; // vector specifyng the type of variables std::map< unsigned int, std::pair<double, double> > fBounds; // map specifying the bound using as key the parameter index -}; +}; } // end namespace Fit diff --git a/ThirdParty/RootMinimizers/inc/Math/Derivator.h b/ThirdParty/RootMinimizers/inc/Math/Derivator.h index 0b5a0c65cca2be9a0a8bc6645ab78bb9992c6e9b..45edde0a76208ddda4d93b84501643a2a84ac3f7 100644 --- a/ThirdParty/RootMinimizers/inc/Math/Derivator.h +++ b/ThirdParty/RootMinimizers/inc/Math/Derivator.h @@ -1,5 +1,5 @@ // @(#)root/mathmore:$Id$ -// Authors: L. Moneta, A. Zsenei 08/2005 +// Authors: L. Moneta, A. Zsenei 08/2005 /********************************************************************** * * @@ -23,21 +23,21 @@ **********************************************************************/ // Header file for class Derivator -// +// // class for calculating Derivative of functions -// +// // Created by: moneta at Sat Nov 13 14:46:00 2004 -// +// // Last update: Sat Nov 13 14:46:00 2004 -// +// #ifndef ROOT_Math_Derivator #define ROOT_Math_Derivator -/** +/** @defgroup Deriv Numerical Differentiation @ingroup NumAlgo */ - + #ifndef ROOT_Math_IFunctionfwd #include "Math/IFunctionfwd.h" #endif @@ -52,15 +52,15 @@ namespace Math { -class GSLDerivator; +class GSLDerivator; //_______________________________________________________________________ -/** - Class for computing numerical derivative of a function. - Presently this class is implemented only using the numerical derivatives +/** + Class for computing numerical derivative of a function. + Presently this class is implemented only using the numerical derivatives algorithms provided by GSL using the implementation class ROOT::Math::GSLDerivator - + This class does not support copying @ingroup Deriv @@ -73,173 +73,173 @@ public: /** signature for function pointers used by GSL */ - typedef double ( * GSLFuncPointer ) ( double, void * ); + typedef double ( * GSLFuncPointer ) ( double, void * ); /** - Empty Construct for a Derivator class + Empty Construct for a Derivator class Need to set the function afterwards with Derivator::SetFunction */ Derivator(); /** - Construct using a ROOT::Math::IGenFunction interface + Construct using a ROOT::Math::IGenFunction interface */ explicit Derivator(const IGenFunction &f); /** - Construct using a GSL function pointer type + Construct using a GSL function pointer type @param f : free function pointer of the GSL required type - @param p : pointer to the object carrying the function state + @param p : pointer to the object carrying the function state (for example the function object itself) */ explicit Derivator(const GSLFuncPointer &f, void * p = 0); - /// destructor - virtual ~Derivator(); + /// destructor + virtual ~Derivator(); // disable copying -private: +private: Derivator(const Derivator &); - Derivator & operator = (const Derivator &); + Derivator & operator = (const Derivator &); -public: +public: #ifdef LATER - /** + /** Template methods for generic functions Set the function f for evaluating the derivative. - The function type must implement the assigment operator, + The function type must implement the assigment operator, <em> double operator() ( double x ) </em> */ template <class UserFunc> - inline void SetFunction(const UserFunc &f) { - const void * p = &f; - SetFunction( &GSLFunctionAdapter<UserFunc>::F, const_cast<void *>(p) ); + inline void SetFunction(const UserFunc &f) { + const void * p = &f; + SetFunction( &GSLFunctionAdapter<UserFunc>::F, const_cast<void *>(p) ); } #endif - /** - Set the function for calculating the derivatives. + /** + Set the function for calculating the derivatives. The function must implement the ROOT::Math::IGenFunction signature */ void SetFunction(const IGenFunction &f); - /** - Set the function f for evaluating the derivative using a GSL function pointer type + /** + Set the function f for evaluating the derivative using a GSL function pointer type @param f : free function pointer of the GSL required type - @param p : pointer to the object carrying the function state + @param p : pointer to the object carrying the function state (for example the function object itself) */ void SetFunction( const GSLFuncPointer &f, void * p = 0); - - - - /** - Computes the numerical derivative of a function f at a point x. - It uses Derivator::EvalCentral to compute the derivative using an + + + + /** + Computes the numerical derivative of a function f at a point x. + It uses Derivator::EvalCentral to compute the derivative using an adaptive central difference algorithm with a step size h */ double Eval(double x, double h = 1E-8) const; - - /** - Computes the numerical derivative at a point x using an adaptive central - difference algorithm with a step size h. + + /** + Computes the numerical derivative at a point x using an adaptive central + difference algorithm with a step size h. */ - double EvalCentral( double x, double h = 1E-8) const; + double EvalCentral( double x, double h = 1E-8) const; - /** - Computes the numerical derivative at a point x using an adaptive forward + /** + Computes the numerical derivative at a point x using an adaptive forward difference algorithm with a step size h. The function is evaluated only at points greater than x and at x itself. */ - double EvalForward( double x, double h = 1E-8) const; + double EvalForward( double x, double h = 1E-8) const; - /** - Computes the numerical derivative at a point x using an adaptive backward + /** + Computes the numerical derivative at a point x using an adaptive backward difference algorithm with a step size h. The function is evaluated only at points less than x and at x itself. */ - double EvalBackward( double x, double h = 1E-8) const; + double EvalBackward( double x, double h = 1E-8) const; - /** @name --- Static methods --- - This methods don't require to use a Derivator object, and are designed to be used in + /** @name --- Static methods --- + This methods don't require to use a Derivator object, and are designed to be used in fast calculation. Error and status code cannot be retrieved in this case */ - /** - Computes the numerical derivative of a function f at a point x. - It uses Derivator::EvalCentral to compute the derivative using an + /** + Computes the numerical derivative of a function f at a point x. + It uses Derivator::EvalCentral to compute the derivative using an adaptive central difference algorithm with a step size h */ static double Eval(const IGenFunction & f, double x, double h = 1E-8); - /** - Computes the numerical derivative of a function f at a point x using an adaptive central + /** + Computes the numerical derivative of a function f at a point x using an adaptive central difference algorithm with a step size h - */ + */ static double EvalCentral(const IGenFunction & f, double x, double h = 1E-8); - /** - Computes the numerical derivative of a function f at a point x using an adaptive forward + /** + Computes the numerical derivative of a function f at a point x using an adaptive forward difference algorithm with a step size h. The function is evaluated only at points greater than x and at x itself - */ + */ static double EvalForward(const IGenFunction & f, double x, double h = 1E-8); - /** - Computes the numerical derivative of a function f at a point x using an adaptive backward + /** + Computes the numerical derivative of a function f at a point x using an adaptive backward difference algorithm with a step size h. The function is evaluated only at points less than x and at x itself - */ + */ static double EvalBackward(const IGenFunction & f, double x, double h = 1E-8); // Derivatives for multi-dimension functions /** - Evaluate the partial derivative of a multi-dim function + Evaluate the partial derivative of a multi-dim function with respect coordinate x_icoord at the point x[] - */ + */ static double Eval(const IMultiGenFunction & f, const double * x, unsigned int icoord = 0, double h = 1E-8); /** - Evaluate the derivative with respect a parameter for one-dim parameteric function + Evaluate the derivative with respect a parameter for one-dim parameteric function at the point ( x,p[]) with respect the parameter p_ipar - */ + */ static double Eval(IParamFunction & f, double x, const double * p, unsigned int ipar = 0, double h = 1E-8); /** - Evaluate the derivative with respect a parameter for a multi-dim parameteric function + Evaluate the derivative with respect a parameter for a multi-dim parameteric function at the point ( x[],p[]) with respect the parameter p_ipar - */ + */ static double Eval(IParamMultiFunction & f, const double * x, const double * p, unsigned int ipar = 0, double h = 1E-8); /** return the error status of the last derivative calculation - */ - int Status() const; + */ + int Status() const; /** return the result of the last derivative calculation */ - double Result() const; + double Result() const; /** return the estimate of the absolute error of the last derivative calculation */ - double Error() const; + double Error() const; -private: +private: - mutable GSLDerivator * fDerivator; + mutable GSLDerivator * fDerivator; -}; +}; diff --git a/ThirdParty/RootMinimizers/inc/Math/FitMethodFunction.h b/ThirdParty/RootMinimizers/inc/Math/FitMethodFunction.h index af0e58e3f96d0d27a81cd99190f055b4655785f2..e8fade98e2333ee38393799520178749fff6036d 100644 --- a/ThirdParty/RootMinimizers/inc/Math/FitMethodFunction.h +++ b/ThirdParty/RootMinimizers/inc/Math/FitMethodFunction.h @@ -21,41 +21,41 @@ // #include "Math/IParamFunctionfwd.h" // #endif -namespace ROOT { +namespace ROOT { - namespace Math { + namespace Math { //______________________________________________________________________________________ -/** - FitMethodFunction class +/** + FitMethodFunction class Interface for objective functions (like chi2 and likelihood used in the fit) - In addition to normal function interface provide interface for calculating each + In addition to normal function interface provide interface for calculating each data contrinution to the function which is required by some algorithm (like Fumili) @ingroup FitMethodFunc -*/ +*/ template<class FunctionType> class BasicFitMethodFunction : public FunctionType { public: - typedef typename FunctionType::BaseFunc BaseFunction; + typedef typename FunctionType::BaseFunc BaseFunction; /// enumeration specyfing the possible fit method types - enum Type_t { kUndefined , kLeastSquare, kLogLikelihood }; + enum Type_t { kUndefined , kLeastSquare, kLogLikelihood }; - BasicFitMethodFunction(int dim, int npoint) : - fNDim(dim), + BasicFitMethodFunction(int dim, int npoint) : + fNDim(dim), fNPoints(npoint), fNCalls(0) {} - /** + /** Virtual Destructor (no operations) - */ - virtual ~BasicFitMethodFunction () {} + */ + virtual ~BasicFitMethodFunction () {} /** Number of dimension (parameters) . From IGenMultiFunction interface @@ -64,11 +64,11 @@ public: /** method returning the data i-th contribution to the fit objective function - For example the residual for the least square functions or the pdf element for the - likelihood functions. + For example the residual for the least square functions or the pdf element for the + likelihood functions. Estimating eventually also the gradient of the data element if the passed pointer is not null */ - virtual double DataElement(const double *x, unsigned int i, double *g = 0) const = 0; + virtual double DataElement(const double *x, unsigned int i, double *g = 0) const = 0; /** @@ -87,7 +87,7 @@ public: virtual unsigned int NCalls() const { return fNCalls; } /** - update number of calls + update number of calls */ virtual void UpdateNCalls() const { fNCalls++; } @@ -98,38 +98,38 @@ public: -public: +public: -protected: +protected: -private: +private: - unsigned int fNDim; // function dimension + unsigned int fNDim; // function dimension unsigned int fNPoints; // size of the data mutable unsigned int fNCalls; // number of function calls -}; +}; // define the normal and gradient function - typedef BasicFitMethodFunction<ROOT::Math::IMultiGenFunction> FitMethodFunction; + typedef BasicFitMethodFunction<ROOT::Math::IMultiGenFunction> FitMethodFunction; typedef BasicFitMethodFunction<ROOT::Math::IMultiGradFunction> FitMethodGradFunction; - // useful template definition to use these interface in + // useful template definition to use these interface in // generic programming - // (comment them out since they are not used anymore) + // (comment them out since they are not used anymore) /* - template<class FunType> - struct ParamFunctionTrait { + template<class FunType> + struct ParamFunctionTrait { typedef IParamMultiFunction PFType; }; // specialization for the gradient param functions - template<> - struct ParamFunctionTrait<ROOT::Math::IMultiGradFunction> { + template<> + struct ParamFunctionTrait<ROOT::Math::IMultiGradFunction> { typedef IParamMultiGradFunction PFType; }; */ diff --git a/ThirdParty/RootMinimizers/inc/Math/Functor.h b/ThirdParty/RootMinimizers/inc/Math/Functor.h index 6c98d0ce4e25ac5814d9c554ce4e359891988c95..f5b46e8e28125de6bab9464dca6ffd06d8764caf 100644 --- a/ThirdParty/RootMinimizers/inc/Math/Functor.h +++ b/ThirdParty/RootMinimizers/inc/Math/Functor.h @@ -8,7 +8,7 @@ * * **********************************************************************/ -// Heaer file for Functor classes. +// Heaer file for Functor classes. // designed is inspired by the Loki Functor #ifndef ROOT_Math_Functor @@ -22,196 +22,196 @@ // #include "Math/StaticCheck.h" // #endif -#include <memory> +#include <memory> -namespace ROOT { +namespace ROOT { -namespace Math { +namespace Math { /** - FunctorImpl is a base class for the functor - handler implementation class. + FunctorImpl is a base class for the functor + handler implementation class. It defines the Copy operator used to clone the functor objects */ -template<class IBaseFunc> -class FunctorImpl : public IBaseFunc { +template<class IBaseFunc> +class FunctorImpl : public IBaseFunc { -public: +public: - typedef IBaseFunc BaseFunc; + typedef IBaseFunc BaseFunc; FunctorImpl() : IBaseFunc() { } virtual ~FunctorImpl() {} - virtual FunctorImpl* Copy() const = 0; + virtual FunctorImpl* Copy() const = 0; }; -/** - Functor Handler class is responsible for wrapping any other functor and pointer to +/** + Functor Handler class is responsible for wrapping any other functor and pointer to free C functions. - It can be created from any function implementing the correct signature + It can be created from any function implementing the correct signature corresponding to the requested type In the case of one dimension the function evaluation object must implement - double operator() (double x). If it implements a method: double Derivative(double x) - can be used to create a Gradient function type. - - In the case of multi-dimension the function evaluation object must implement - double operator()(const double *x). If it implements a method: - double Derivative(const double *x, int icoord) + double operator() (double x). If it implements a method: double Derivative(double x) + can be used to create a Gradient function type. + + In the case of multi-dimension the function evaluation object must implement + double operator()(const double *x). If it implements a method: + double Derivative(const double *x, int icoord) can be used to create a Gradient function type. @ingroup Functor_int -*/ +*/ template<class ParentFunctor, class Func > -class FunctorHandler : public ParentFunctor::Impl { +class FunctorHandler : public ParentFunctor::Impl { - typedef typename ParentFunctor::Impl ImplFunc; - typedef typename ImplFunc::BaseFunc BaseFunc; - //typedef typename ParentFunctor::Dim Dim; + typedef typename ParentFunctor::Impl ImplFunc; + typedef typename ImplFunc::BaseFunc BaseFunc; + //typedef typename ParentFunctor::Dim Dim; -public: +public: - // constructor for 1d functions + // constructor for 1d functions FunctorHandler(const Func & fun) : fDim(1), fFunc(fun) {} // constructor for multi-dimensional functions w/0 NDim() FunctorHandler(unsigned int dim, const Func & fun ) : fDim(dim), - fFunc(fun) + fFunc(fun) {} virtual ~FunctorHandler() {} // copy of the function handler (use copy-ctor) - ImplFunc * Copy() const { - return new FunctorHandler(*this); + ImplFunc * Copy() const { + return new FunctorHandler(*this); } - // clone of the function handler (use copy-ctor) - BaseFunc * Clone() const { - return Copy(); + // clone of the function handler (use copy-ctor) + BaseFunc * Clone() const { + return Copy(); } // constructor for multi-dimensional functions - unsigned int NDim() const { + unsigned int NDim() const { return fDim; - } + } private : - inline double DoEval (double x) const { - return fFunc(x); - } + inline double DoEval (double x) const { + return fFunc(x); + } - inline double DoEval (const double * x) const { - return fFunc(x); - } + inline double DoEval (const double * x) const { + return fFunc(x); + } - inline double DoDerivative (double x) const { + inline double DoDerivative (double x) const { return fFunc.Derivative(x); - } + } - inline double DoDerivative (const double * x, unsigned int icoord ) const { + inline double DoDerivative (const double * x, unsigned int icoord ) const { return fFunc.Derivative(x,icoord); - } + } + - - unsigned int fDim; - mutable Func fFunc; // should here be a reference and pass a non-const ref in ctor + unsigned int fDim; + mutable Func fFunc; // should here be a reference and pass a non-const ref in ctor }; -/** - Functor Handler class for gradient functions where both callable objects are provided for the function +/** + Functor Handler class for gradient functions where both callable objects are provided for the function evaluation (type Func) and for the gradient (type GradFunc) . - It can be created from any function implementing the correct signature + It can be created from any function implementing the correct signature corresponding to the requested type In the case of one dimension the function evaluation object and the derivative function object must implement double operator() (double x). - In the case of multi-dimension the function evaluation object must implement - double operator() (const double * x) and the gradient function object must implement - double operator() (const double * x, int icoord) + In the case of multi-dimension the function evaluation object must implement + double operator() (const double * x) and the gradient function object must implement + double operator() (const double * x, int icoord) @ingroup Functor_int -*/ +*/ template<class ParentFunctor, class Func, class GradFunc > -class FunctorGradHandler : public ParentFunctor::Impl { +class FunctorGradHandler : public ParentFunctor::Impl { - typedef typename ParentFunctor::Impl ImplFunc; - typedef typename ImplFunc::BaseFunc BaseFunc; - //typedef typename ParentFunctor::Dim Dim; + typedef typename ParentFunctor::Impl ImplFunc; + typedef typename ImplFunc::BaseFunc BaseFunc; + //typedef typename ParentFunctor::Dim Dim; -public: +public: - // constructor for 1d functions - FunctorGradHandler(const Func & fun, const GradFunc & gfun) : - fDim(1), - fFunc(fun), - fGradFunc(gfun) + // constructor for 1d functions + FunctorGradHandler(const Func & fun, const GradFunc & gfun) : + fDim(1), + fFunc(fun), + fGradFunc(gfun) {} - // constructor for multi-dimensional functions + // constructor for multi-dimensional functions FunctorGradHandler(unsigned int dim, const Func & fun, const GradFunc & gfun) : fDim(dim), - fFunc(fun), - fGradFunc( gfun ) + fFunc(fun), + fGradFunc( gfun ) {} - virtual ~FunctorGradHandler() {} + virtual ~FunctorGradHandler() {} - // clone of the function handler (use copy-ctor) + // clone of the function handler (use copy-ctor) ImplFunc * Copy() const { return new FunctorGradHandler(*this); } - // clone of the function handler (use copy-ctor) + // clone of the function handler (use copy-ctor) BaseFunc * Clone() const { return Copy(); } // constructor for multi-dimensional functions - unsigned int NDim() const { + unsigned int NDim() const { return fDim; - } + } private : - inline double DoEval (double x) const { - return fFunc(x); - } + inline double DoEval (double x) const { + return fFunc(x); + } - inline double DoEval (const double * x) const { - return fFunc(x); - } + inline double DoEval (const double * x) const { + return fFunc(x); + } - inline double DoDerivative (double x) const { + inline double DoDerivative (double x) const { return fGradFunc(x); - } + } + + inline double DoDerivative (const double * x, unsigned int icoord ) const { + return fGradFunc(x, icoord); + } - inline double DoDerivative (const double * x, unsigned int icoord ) const { - return fGradFunc(x, icoord); - } - - unsigned int fDim; - mutable Func fFunc; - mutable GradFunc fGradFunc; + unsigned int fDim; + mutable Func fFunc; + mutable GradFunc fGradFunc; }; /** - Functor Handler to Wrap pointers to member functions - The member function type must be (XXX means any name is allowed) : - double XXX ( double x) for 1D functions - and + Functor Handler to Wrap pointers to member functions + The member function type must be (XXX means any name is allowed) : + double XXX ( double x) for 1D functions + and double XXXX (const double *x) for multi-dimensional functions @ingroup Functor_int @@ -220,57 +220,57 @@ template <class ParentFunctor, typename PointerToObj, typename PointerToMemFn> class MemFunHandler : public ParentFunctor::Impl { - //typedef typename ParentFunctor::Dim Dim; - typedef typename ParentFunctor::Impl ImplFunc; - typedef typename ImplFunc::BaseFunc BaseFunc; - + //typedef typename ParentFunctor::Dim Dim; + typedef typename ParentFunctor::Impl ImplFunc; + typedef typename ImplFunc::BaseFunc BaseFunc; + public: - + /// constructor from a pointer to the class and a pointer to the function - MemFunHandler(const PointerToObj& pObj, PointerToMemFn pMemFn) + MemFunHandler(const PointerToObj& pObj, PointerToMemFn pMemFn) : fDim(1), fObj(pObj), fMemFn(pMemFn) // should pass pointer by value ?? {} /// constructor from a pointer to the class and a pointer to the function - MemFunHandler(unsigned int dim, const PointerToObj& pObj, PointerToMemFn pMemFn) + MemFunHandler(unsigned int dim, const PointerToObj& pObj, PointerToMemFn pMemFn) : fDim(dim), fObj(pObj), fMemFn(pMemFn) {} virtual ~MemFunHandler() {} - - // clone of the function handler (use copy-ctor) + + // clone of the function handler (use copy-ctor) ImplFunc * Copy() const { return new MemFunHandler(*this); } - // clone of the function handler (use copy-ctor) + // clone of the function handler (use copy-ctor) BaseFunc * Clone() const { return new MemFunHandler(*this); } // constructor for multi-dimensional functions - unsigned int NDim() const { + unsigned int NDim() const { return fDim; - } + } private : - - inline double DoEval (double x) const { - return ((*fObj).*fMemFn)(x); - } - - inline double DoEval (const double * x) const { - return ((*fObj).*fMemFn)(x); + + inline double DoEval (double x) const { + return ((*fObj).*fMemFn)(x); + } + + inline double DoEval (const double * x) const { + return ((*fObj).*fMemFn)(x); } - unsigned int fDim; + unsigned int fDim; mutable PointerToObj fObj; - PointerToMemFn fMemFn; + PointerToMemFn fMemFn; }; /** - Functor Handler to Wrap pointers to member functions for the evaluation of the function - and the gradient. - The member function type must be (XXX means any name is allowed) : - double XXX ( double x) for 1D function and derivative evaluation - double XXX (const double *x) for multi-dimensional function evaluation and + Functor Handler to Wrap pointers to member functions for the evaluation of the function + and the gradient. + The member function type must be (XXX means any name is allowed) : + double XXX ( double x) for 1D function and derivative evaluation + double XXX (const double *x) for multi-dimensional function evaluation and double XXX (cost double *x, int icoord) for partial derivatives evaluation @ingroup Functor_int @@ -280,129 +280,129 @@ template <class ParentFunctor, typename PointerToObj, typename PointerToMemFn, typename PointerToGradMemFn> class MemGradFunHandler : public ParentFunctor::Impl { - typedef typename ParentFunctor::Impl ImplFunc; - typedef typename ImplFunc::BaseFunc BaseFunc; - //typedef typename ParentFunctor::Dim Dim; + typedef typename ParentFunctor::Impl ImplFunc; + typedef typename ImplFunc::BaseFunc BaseFunc; + //typedef typename ParentFunctor::Dim Dim; public: - + /// constructor from a pointer to the class and a pointer to the function - MemGradFunHandler(const PointerToObj& pObj, PointerToMemFn pMemFn, PointerToGradMemFn pGradMemFn) - : fDim(1), - fObj(pObj), - fMemFn(pMemFn), + MemGradFunHandler(const PointerToObj& pObj, PointerToMemFn pMemFn, PointerToGradMemFn pGradMemFn) + : fDim(1), + fObj(pObj), + fMemFn(pMemFn), fGradMemFn(pGradMemFn) {} /// constructor from a pointer to the class and a pointer to the function - MemGradFunHandler(unsigned int dim, - const PointerToObj& pObj, - PointerToMemFn pMemFn, - PointerToGradMemFn pGradMemFn ) - : fDim(dim), - fObj(pObj), - fMemFn(pMemFn), + MemGradFunHandler(unsigned int dim, + const PointerToObj& pObj, + PointerToMemFn pMemFn, + PointerToGradMemFn pGradMemFn ) + : fDim(dim), + fObj(pObj), + fMemFn(pMemFn), fGradMemFn(pGradMemFn) {} - + virtual ~MemGradFunHandler() {} - // clone of the function handler (use copy-ctor) + // clone of the function handler (use copy-ctor) ImplFunc * Copy() const { return new MemGradFunHandler(*this); } - - // clone of the function handler (use copy-ctor) + + // clone of the function handler (use copy-ctor) BaseFunc * Clone() const { return new MemGradFunHandler(*this); } // constructor for multi-dimensional functions - unsigned int NDim() const { + unsigned int NDim() const { return fDim; - } + } private : - - inline double DoEval (double x) const { - return ((*fObj).*fMemFn)(x); - } - - inline double DoEval (const double * x) const { - return ((*fObj).*fMemFn)(x); - } - - inline double DoDerivative (double x) const { - return ((*fObj).*fGradMemFn)(x); - } - - inline double DoDerivative (const double * x, unsigned int icoord ) const { - return ((*fObj).*fGradMemFn)(x,icoord); - } - - unsigned int fDim; + + inline double DoEval (double x) const { + return ((*fObj).*fMemFn)(x); + } + + inline double DoEval (const double * x) const { + return ((*fObj).*fMemFn)(x); + } + + inline double DoDerivative (double x) const { + return ((*fObj).*fGradMemFn)(x); + } + + inline double DoDerivative (const double * x, unsigned int icoord ) const { + return ((*fObj).*fGradMemFn)(x,icoord); + } + + unsigned int fDim; mutable PointerToObj fObj; PointerToMemFn fMemFn; PointerToGradMemFn fGradMemFn; }; - + //**************************** -// LM 7/2/2014: no needed this : make template ctor of Functor1D and GradFunctor1D not +// LM 7/2/2014: no needed this : make template ctor of Functor1D and GradFunctor1D not // available to CINT s //*************************************** -//#if defined(__MAKECINT__) || defined(G__DICTIONARY) +//#if defined(__MAKECINT__) || defined(G__DICTIONARY) // needed since CINT initialize it with TRootIOCtor -//class TRootIOCtor; +//class TRootIOCtor; -// template<class ParentFunctor> -// class FunctorHandler<ParentFunctor,TRootIOCtor *> : public ParentFunctor::Impl +// template<class ParentFunctor> +// class FunctorHandler<ParentFunctor,TRootIOCtor *> : public ParentFunctor::Impl // { // public: -// typedef typename ParentFunctor::Impl ImplFunc; -// typedef typename ImplFunc::BaseFunc BaseFunc; +// typedef typename ParentFunctor::Impl ImplFunc; +// typedef typename ImplFunc::BaseFunc BaseFunc; // FunctorHandler(TRootIOCtor *) {} // // function required by interface // virtual ~FunctorHandler() {} -// double DoEval (double ) const { return 0; } -// double DoDerivative (double ) const { return 0; } -// ImplFunc * Copy() const { return 0; } -// BaseFunc * Clone() const { return 0; } +// double DoEval (double ) const { return 0; } +// double DoDerivative (double ) const { return 0; } +// ImplFunc * Copy() const { return 0; } +// BaseFunc * Clone() const { return 0; } -// }; -// #endif +// }; +// #endif //_______________________________________________________________________________________________ /** - Documentation for class Functor class. - It is used to wrap in a very simple and convenient way multi-dimensional function objects. + Documentation for class Functor class. + It is used to wrap in a very simple and convenient way multi-dimensional function objects. It can wrap all the following types: <ul> - <li> any C++ callable object implemention double operator()( const double * ) - <li> a free C function of type double ()(const double * ) - <li> a member function with the correct signature like Foo::Eval(const double * ). - In this case one pass the object pointer and a pointer to the member function (&Foo::Eval) + <li> any C++ callable object implemention double operator()( const double * ) + <li> a free C function of type double ()(const double * ) + <li> a member function with the correct signature like Foo::Eval(const double * ). + In this case one pass the object pointer and a pointer to the member function (&Foo::Eval) </ul> - The function dimension is required when constructing the functor. + The function dimension is required when constructing the functor. @ingroup GenFunc */ -class Functor : public IBaseFunctionMultiDim { +class Functor : public IBaseFunctionMultiDim { -public: +public: - typedef FunctorImpl<IBaseFunctionMultiDim> Impl; - typedef IBaseFunctionMultiDim::BaseFunc ImplBase; + typedef FunctorImpl<IBaseFunctionMultiDim> Impl; + typedef IBaseFunctionMultiDim::BaseFunc ImplBase; - /** + /** Default constructor - */ - Functor () : fImpl(0) {} + */ + Functor () : fImpl(0) {} - /** + /** construct from a pointer to member function (multi-dim type) - */ + */ template <class PtrObj, typename MemFn> Functor(const PtrObj& p, MemFn memFn, unsigned int dim ) : fImpl(new MemFunHandler<Functor, PtrObj, MemFn>(dim, p, memFn)) @@ -411,79 +411,73 @@ public: /** - construct from a callable object of multi-dimension + construct from a callable object of multi-dimension with the right signature (implementing operator()(double *x) */ - template <typename Func> - Functor( const Func & f, unsigned int dim ) : + template <typename Func> + Functor( const Func & f, unsigned int dim ) : fImpl(new FunctorHandler<Functor,Func>(dim,f) ) {} - //implement for interpreted CINT functions -#if defined(__CINT__) || defined(G__DICTIONARY) || defined(MAKE_CINT_FUNCTOR) - Functor(void * p, unsigned int dim, const char * className = 0, const char * methodName = 0); -#endif - - - /** + /** Destructor (no operations) - */ - virtual ~Functor () {} + */ + virtual ~Functor () {} - /** + /** Copy constructor for functor based on ROOT::Math::IMultiGenFunction - */ - Functor(const Functor & rhs) : - ImplBase() + */ + Functor(const Functor & rhs) : + ImplBase() { - if (rhs.fImpl.get() != 0) - fImpl = std::auto_ptr<Impl>( (rhs.fImpl)->Copy() ); - } + if (rhs.fImpl.get() != 0) + fImpl = std::auto_ptr<Impl>( (rhs.fImpl)->Copy() ); + } // need a specialization in order to call base classes and use clone - /** + /** Assignment operator - */ + */ Functor & operator = (const Functor & rhs) { - Functor copy(rhs); + Functor copy(rhs); // swap auto_ptr by hand - Impl * p = fImpl.release(); + Impl * p = fImpl.release(); fImpl.reset(copy.fImpl.release()); copy.fImpl.reset(p); return *this; } - // clone of the function handler (use copy-ctor) + // clone of the function handler (use copy-ctor) ImplBase * Clone() const { return new Functor(*this); } // for multi-dimensional functions - unsigned int NDim() const { return fImpl->NDim(); } + unsigned int NDim() const { return fImpl->NDim(); } private : - inline double DoEval (const double * x) const { - return (*fImpl)(x); - } + inline double DoEval (const double * x) const { + return (*fImpl)(x); + } std::auto_ptr<Impl> fImpl; // pointer to base functor handler -}; +}; //______________________________________________________________________________________ /** - Functor1D class for one-dimensional functions. - It is used to wrap in a very simple and convenient way: + Functor1D class for one-dimensional functions. + It is used to wrap in a very simple and convenient way: <ul> - <li> any C++ callable object implemention double operator()( double ) - <li> a free C function of type double ()(double ) - <li> a member function with the correct signature like Foo::Eval(double ). - In this case one pass the object pointer and a pointer to the member function (&Foo::Eval) + <li> any C++ callable object implemention double operator()( double ) + <li> a free C function of type double ()(double ) + <li> a member function with the correct signature like Foo::Eval(double ). + In this case one pass the object pointer and a pointer to the member function (&Foo::Eval) </ul> @@ -491,140 +485,132 @@ private : */ -class Functor1D : public IBaseFunctionOneDim { +class Functor1D : public IBaseFunctionOneDim { -public: +public: - typedef FunctorImpl<IBaseFunctionOneDim> Impl; - typedef IBaseFunctionOneDim::BaseFunc ImplBase; + typedef FunctorImpl<IBaseFunctionOneDim> Impl; + typedef IBaseFunctionOneDim::BaseFunc ImplBase; - /** + /** Default constructor - */ - Functor1D () : fImpl(0) {} + */ + Functor1D () : fImpl(0) {} -#ifndef __CINT__ /** - construct from a callable object with the right signature + construct from a callable object with the right signature implementing operator() (double x) */ - template <typename Func> - Functor1D(const Func & f) : + template <typename Func> + Functor1D(const Func & f) : fImpl(new FunctorHandler<Functor1D,Func>(f) ) {} -#endif - /** + /** construct from a pointer to member function (1D type) - */ + */ template <class PtrObj, typename MemFn> Functor1D(const PtrObj& p, MemFn memFn) : fImpl(new MemFunHandler<Functor1D, PtrObj, MemFn>(p, memFn)) {} - //implement for interpreted CINT functions -#if defined(__CINT__) || defined(G__DICTIONARY) || defined(MAKE_CINT_FUNCTOR) - Functor1D(void * p, const char * className = 0, const char * methodName = 0); - -#endif - - /** + /** Destructor (no operations) - */ - virtual ~Functor1D () {} + */ + virtual ~Functor1D () {} - /** + /** Copy constructor for Functor based on ROOT::Math::IGenFunction - */ - Functor1D(const Functor1D & rhs) : + */ + Functor1D(const Functor1D & rhs) : // strange that this is required eventhough ImplBase is an abstract class ImplBase() { - if (rhs.fImpl.get() != 0) - fImpl = std::auto_ptr<Impl>( (rhs.fImpl)->Copy() ); - } + if (rhs.fImpl.get() != 0) + fImpl = std::auto_ptr<Impl>( (rhs.fImpl)->Copy() ); + } - /** + /** Assignment operator - */ + */ Functor1D & operator = (const Functor1D & rhs) { - Functor1D copy(rhs); + Functor1D copy(rhs); // swap auto_ptr by hand - Impl * p = fImpl.release(); + Impl * p = fImpl.release(); fImpl.reset(copy.fImpl.release()); copy.fImpl.reset(p); return *this; } - // clone of the function handler (use copy-ctor) + // clone of the function handler (use copy-ctor) ImplBase * Clone() const { return new Functor1D(*this); } private : - inline double DoEval (double x) const { - return (*fImpl)(x); - } + inline double DoEval (double x) const { + return (*fImpl)(x); + } std::auto_ptr<Impl> fImpl; // pointer to base functor handler -}; +}; //_______________________________________________________________________________________________ /** - GradFunctor class for Multidimensional gradient functions. - It is used to wrap in a very C++ callable object to make gradient functions. - It can be constructed in three different way: + GradFunctor class for Multidimensional gradient functions. + It is used to wrap in a very C++ callable object to make gradient functions. + It can be constructed in three different way: <ol> - <li> from an object implementing both - double operator()( const double * ) for the function evaluation and + <li> from an object implementing both + double operator()( const double * ) for the function evaluation and double Derivative(const double *, int icoord) for the partial derivatives - <li>from an object implementing any member function like Foo::XXX(const double *) for the function evaluation + <li>from an object implementing any member function like Foo::XXX(const double *) for the function evaluation and any member function like Foo::XXX(const double *, int icoord) for the partial derivatives - <li>from an function object implementing - double operator()( const double * ) for the function evaluation and another function object implementing + <li>from an function object implementing + double operator()( const double * ) for the function evaluation and another function object implementing double operator() (const double *, int icoord) for the partial derivatives </ol> - The function dimension is required when constructing the functor. + The function dimension is required when constructing the functor. @ingroup GenFunc */ -class GradFunctor : public IGradientFunctionMultiDim { +class GradFunctor : public IGradientFunctionMultiDim { + +public: -public: + typedef FunctorImpl<IGradientFunctionMultiDim> Impl; + typedef IGradientFunctionMultiDim::BaseFunc ImplBase; - typedef FunctorImpl<IGradientFunctionMultiDim> Impl; - typedef IGradientFunctionMultiDim::BaseFunc ImplBase; - - /** + /** Default constructor - */ - GradFunctor () : fImpl(0) {} + */ + GradFunctor () : fImpl(0) {} /** - construct from a callable object of multi-dimension - implementing operator()(const double *x) and + construct from a callable object of multi-dimension + implementing operator()(const double *x) and Derivative(const double * x,icoord) */ - template <typename Func> - GradFunctor( const Func & f, unsigned int dim ) : + template <typename Func> + GradFunctor( const Func & f, unsigned int dim ) : fImpl(new FunctorHandler<GradFunctor,Func>(dim,f) ) {} - /** + /** construct from a pointer to member function and member function types for function and derivative evaluations - */ + */ template <class PtrObj, typename MemFn, typename GradMemFn> GradFunctor(const PtrObj& p, MemFn memFn, GradMemFn gradFn, unsigned int dim ) : fImpl(new MemGradFunHandler<GradFunctor, PtrObj, MemFn, GradMemFn>(dim, p, memFn, gradFn)) @@ -633,85 +619,79 @@ public: /** construct for Gradient Functions of multi-dimension Func gives the function evaluatiion, GradFunc the partial derivatives - The function dimension is required + The function dimension is required */ - template <typename Func, typename GradFunc> - GradFunctor(const Func & f, const GradFunc & g, int dim ) : + template <typename Func, typename GradFunc> + GradFunctor(const Func & f, const GradFunc & g, int dim ) : fImpl(new FunctorGradHandler<GradFunctor,Func,GradFunc>(dim, f, g) ) { } - // for interpreted CINT functions -#if defined(__CINT__) || defined(G__DICTIONARY) || defined(MAKE_CINT_FUNCTOR) - GradFunctor(void * p1, unsigned int dim, const char * className, const char * methodName, const char * derivName); - GradFunctor(void * p1, void * p2, unsigned int dim); -#endif - /** + /** Destructor (no operations) - */ - virtual ~GradFunctor () {} + */ + virtual ~GradFunctor () {} - /** + /** Copy constructor for functor based on ROOT::Math::IMultiGradFunction - */ - GradFunctor(const GradFunctor & rhs) : - ImplBase(), - IGradientFunctionMultiDim() + */ + GradFunctor(const GradFunctor & rhs) : + ImplBase() { - if (rhs.fImpl.get() != 0) - fImpl = std::auto_ptr<Impl>( rhs.fImpl->Copy() ); - } + if (rhs.fImpl.get() != 0) + fImpl = std::auto_ptr<Impl>( rhs.fImpl->Copy() ); + } - /** + /** Assignment operator - */ + */ GradFunctor & operator = (const GradFunctor & rhs) { - GradFunctor copy(rhs); + GradFunctor copy(rhs); // swap auto_ptr by hand - Impl * p = fImpl.release(); + Impl * p = fImpl.release(); fImpl.reset(copy.fImpl.release()); copy.fImpl.reset(p); return *this; } - // clone of the function handler (use copy-ctor) + // clone of the function handler (use copy-ctor) ImplBase * Clone() const { return new GradFunctor(*this); } // for multi-dimensional functions - unsigned int NDim() const { return fImpl->NDim(); } + unsigned int NDim() const { return fImpl->NDim(); } private : - inline double DoEval (const double * x) const { - return (*fImpl)(x); - } + inline double DoEval (const double * x) const { + return (*fImpl)(x); + } - inline double DoDerivative (const double * x, unsigned int icoord ) const { + inline double DoDerivative (const double * x, unsigned int icoord ) const { return fImpl->Derivative(x,icoord); - } + } std::auto_ptr<Impl> fImpl; // pointer to base grad functor handler -}; +}; //_______________________________________________________________________________________________ /** - GradFunctor1D class for one-dimensional gradient functions. - It is used to wrap in a very C++ callable object to make a 1D gradient functions. - It can be constructed in three different way: + GradFunctor1D class for one-dimensional gradient functions. + It is used to wrap in a very C++ callable object to make a 1D gradient functions. + It can be constructed in three different way: <ol> - <li> from an object implementing both - double operator()( double ) for the function evaluation and + <li> from an object implementing both + double operator()( double ) for the function evaluation and double Derivative(double ) for the partial derivatives - <li>from an object implementing any member function like Foo::XXX(double ) for the function evaluation + <li>from an object implementing any member function like Foo::XXX(double ) for the function evaluation and any other member function like Foo::YYY(double ) for the derivative. - <li>from an 2 function objects implementing + <li>from an 2 function objects implementing double operator()( double ) . One object provides the function evaluation, the other the derivative. </ol> @@ -719,38 +699,36 @@ private : */ -class GradFunctor1D : public IGradientFunctionOneDim { +class GradFunctor1D : public IGradientFunctionOneDim { + +public: -public: + typedef FunctorImpl<IGradientFunctionOneDim> Impl; + typedef IGradientFunctionOneDim::BaseFunc ImplBase; - typedef FunctorImpl<IGradientFunctionOneDim> Impl; - typedef IGradientFunctionOneDim::BaseFunc ImplBase; - - /** + /** Default constructor - */ - GradFunctor1D () : fImpl(0) {} + */ + GradFunctor1D () : fImpl(0) {} -#ifndef __CINT__ /** - construct from an object with the right signature + construct from an object with the right signature implementing both operator() (double x) and Derivative(double x) */ - template <typename Func> - GradFunctor1D(const Func & f) : + template <typename Func> + GradFunctor1D(const Func & f) : fImpl(new FunctorHandler<GradFunctor1D,Func>(f) ) {} -#endif - /** - construct from a pointer to class and two pointers to member functions, one for - the function evaluation and the other for the derivative. + /** + construct from a pointer to class and two pointers to member functions, one for + the function evaluation and the other for the derivative. The member functions must take a double as argument and return a double - */ + */ template <class PtrObj, typename MemFn, typename GradMemFn> GradFunctor1D(const PtrObj& p, MemFn memFn, GradMemFn gradFn) : fImpl(new MemGradFunHandler<GradFunctor1D, PtrObj, MemFn, GradMemFn>(p, memFn, gradFn)) @@ -758,71 +736,64 @@ public: - // eventually implement for interpreted CINT functions -#if defined(__CINT__) || defined(G__DICTIONARY) || defined(MAKE_CINT_FUNCTOR) - GradFunctor1D(void * p1, const char * className, const char * methodName, const char * derivName); - GradFunctor1D(void * p1, void * p2); -#endif - /** construct from two 1D function objects */ - template <typename Func, typename GradFunc> - GradFunctor1D(const Func & f, const GradFunc & g ) : + template <typename Func, typename GradFunc> + GradFunctor1D(const Func & f, const GradFunc & g ) : fImpl(new FunctorGradHandler<GradFunctor1D,Func, GradFunc>(f, g) ) {} - /** + /** Destructor (no operations) - */ - virtual ~GradFunctor1D () {} + */ + virtual ~GradFunctor1D () {} - /** + /** Copy constructor for Functor based on ROOT::Math::IGradFunction - */ - GradFunctor1D(const GradFunctor1D & rhs) : + */ + GradFunctor1D(const GradFunctor1D & rhs) : // strange that this is required eventhough Impl is an abstract class - ImplBase(), - IGradientFunctionOneDim() + ImplBase() { - if (rhs.fImpl.get() != 0) - fImpl = std::auto_ptr<Impl>( rhs.fImpl->Copy() ); - } + if (rhs.fImpl.get() != 0) + fImpl = std::auto_ptr<Impl>( rhs.fImpl->Copy() ); + } - /** + /** Assignment operator - */ + */ GradFunctor1D & operator = (const GradFunctor1D & rhs) { - GradFunctor1D copy(rhs); + GradFunctor1D copy(rhs); // swap auto_ptr by hand - Impl * p = fImpl.release(); + Impl * p = fImpl.release(); fImpl.reset(copy.fImpl.release()); copy.fImpl.reset(p); return *this; } - // clone of the function handler (use copy-ctor) + // clone of the function handler (use copy-ctor) ImplBase * Clone() const { return new GradFunctor1D(*this); } private : - inline double DoEval (double x) const { - return (*fImpl)(x); - } + inline double DoEval (double x) const { + return (*fImpl)(x); + } - inline double DoDerivative (double x) const { + inline double DoDerivative (double x) const { return fImpl->Derivative(x); - } + } std::auto_ptr<Impl> fImpl; // pointer to base gradient functor handler -}; +}; diff --git a/ThirdParty/RootMinimizers/inc/Math/GSLFunctionAdapter.h b/ThirdParty/RootMinimizers/inc/Math/GSLFunctionAdapter.h index 0e1b85e4acff5960d3246c57c6dc7d220820b7c3..518b2f1b0461a49b2fe5d72aee8969494a4b06df 100644 --- a/ThirdParty/RootMinimizers/inc/Math/GSLFunctionAdapter.h +++ b/ThirdParty/RootMinimizers/inc/Math/GSLFunctionAdapter.h @@ -1,5 +1,5 @@ // @(#)root/mathmore:$Id$ -// Authors: L. Moneta, A. Zsenei 08/2005 +// Authors: L. Moneta, A. Zsenei 08/2005 /********************************************************************** * * @@ -24,13 +24,13 @@ // Header file for class GSLFunctionAdapter // -// Generic adapter for gsl_function signature -// usable for any c++ class which defines operator( ) -// +// Generic adapter for gsl_function signature +// usable for any c++ class which defines operator( ) +// // Created by: Lorenzo Moneta at Fri Nov 12 16:58:51 2004 -// +// // Last update: Fri Nov 12 16:58:51 2004 -// +// #ifndef ROOT_Math_GSLFunctionAdapter #define ROOT_Math_GSLFunctionAdapter @@ -46,45 +46,45 @@ namespace Math { /** - Class for adapting any C++ functor class to C function pointers used by GSL. - The templated C++ function class must implement: + Class for adapting any C++ functor class to C function pointers used by GSL. + The templated C++ function class must implement: <em> double operator( double x)</em> - and if the derivatives are required: + and if the derivatives are required: <em> double Gradient( double x)</em> - - This class defines static methods with will be used to fill the - \a gsl_function and \a gsl_function_fdf structs used by GSL. + + This class defines static methods with will be used to fill the + \a gsl_function and \a gsl_function_fdf structs used by GSL. See for examples the <A HREF="http://www.gnu.org/software/gsl/manual/gsl-ref_32.html#SEC432">GSL online manual</A> - */ - + */ + - template<class UserFunc> + template<class UserFunc> class GSLFunctionAdapter { - public: + public: GSLFunctionAdapter() {} - virtual ~GSLFunctionAdapter() {} - - static double F( double x, void * p) { - - UserFunc * function = reinterpret_cast< UserFunc *> (p); - return (*function)( x ); + virtual ~GSLFunctionAdapter() {} + + static double F( double x, void * p) { + + UserFunc * function = reinterpret_cast< UserFunc *> (p); + return (*function)( x ); } - - static double Df( double x, void * p) { - - UserFunc * function = reinterpret_cast< UserFunc *> (p); - return (*function).Derivative( x ); + + static double Df( double x, void * p) { + + UserFunc * function = reinterpret_cast< UserFunc *> (p); + return (*function).Derivative( x ); } - static void Fdf( double x, void * p, double *f, double *df ) { - - UserFunc * function = reinterpret_cast< UserFunc *> (p); - *f = (*function) ( x ); - *df = (*function).Derivative( x ); + static void Fdf( double x, void * p, double *f, double *df ) { + + UserFunc * function = reinterpret_cast< UserFunc *> (p); + *f = (*function) ( x ); + *df = (*function).Derivative( x ); } }; diff --git a/ThirdParty/RootMinimizers/inc/Math/GSLFunctionWrapper.h b/ThirdParty/RootMinimizers/inc/Math/GSLFunctionWrapper.h index 0dc090548011a5e748b6ecc4c29ef8dc174c312b..2b27bec48668aee6cb6fd71aa884e6cb727e7aed 100644 --- a/ThirdParty/RootMinimizers/inc/Math/GSLFunctionWrapper.h +++ b/ThirdParty/RootMinimizers/inc/Math/GSLFunctionWrapper.h @@ -1,5 +1,5 @@ // @(#)root/mathmore:$Id$ -// Authors: L. Moneta, A. Zsenei 08/2005 +// Authors: L. Moneta, A. Zsenei 08/2005 /********************************************************************** * * @@ -23,11 +23,11 @@ **********************************************************************/ // Header file for class GSLFunctionWrapper -// +// // Created by: moneta at Sat Nov 13 14:54:41 2004 -// +// // Last update: Sat Nov 13 14:54:41 2004 -// +// #ifndef ROOT_Math_GSLFunctionWrapper #define ROOT_Math_GSLFunctionWrapper @@ -47,98 +47,98 @@ typedef void ( * GSLFdfPointer ) ( double, void *, double *, double *); /** - Wrapper class to the gsl_function C structure. - This class to fill the GSL C structure gsl_function with - the C++ function objcet. - Use the class ROOT::Math::GSLFunctionAdapter to adapt the - C++ function object to the right signature (function pointer type) - requested by GSL + Wrapper class to the gsl_function C structure. + This class to fill the GSL C structure gsl_function with + the C++ function objcet. + Use the class ROOT::Math::GSLFunctionAdapter to adapt the + C++ function object to the right signature (function pointer type) + requested by GSL */ -class GSLFunctionWrapper { +class GSLFunctionWrapper { -public: +public: - GSLFunctionWrapper() + GSLFunctionWrapper() { - fFunc.function = 0; + fFunc.function = 0; fFunc.params = 0; } - /// set in the GSL C struct the pointer to the function evaluation - void SetFuncPointer( GSLFuncPointer f) { fFunc.function = f; } + /// set in the GSL C struct the pointer to the function evaluation + void SetFuncPointer( GSLFuncPointer f) { fFunc.function = f; } /// set in the GSL C struct the extra-object pointer void SetParams ( void * p) { fFunc.params = p; } - /// fill the GSL C struct from a generic C++ callable object - /// implementing operator() - template<class FuncType> - void SetFunction(const FuncType &f) { + /// fill the GSL C struct from a generic C++ callable object + /// implementing operator() + template<class FuncType> + void SetFunction(const FuncType &f) { const void * p = &f; - assert (p != 0); + assert (p != 0); SetFuncPointer(&GSLFunctionAdapter<FuncType >::F); SetParams(const_cast<void *>(p)); } - - gsl_function * GetFunc() { return &fFunc; } + + gsl_function * GetFunc() { return &fFunc; } GSLFuncPointer FunctionPtr() { return fFunc.function; } - // evaluate the function + // evaluate the function double operator() (double x) { return GSL_FN_EVAL(&fFunc, x); } - /// check if function is valid (has been set) - bool IsValid() { - return (fFunc.function != 0) ? true : false; + /// check if function is valid (has been set) + bool IsValid() { + return (fFunc.function != 0) ? true : false; } -private: - gsl_function fFunc; +private: + gsl_function fFunc; }; /** - class to wrap a gsl_function_fdf (with derivatives) + class to wrap a gsl_function_fdf (with derivatives) */ - class GSLFunctionDerivWrapper { + class GSLFunctionDerivWrapper { - public: + public: - GSLFunctionDerivWrapper() + GSLFunctionDerivWrapper() { - fFunc.f = 0; - fFunc.df = 0; - fFunc.fdf = 0; + fFunc.f = 0; + fFunc.df = 0; + fFunc.fdf = 0; fFunc.params = 0; } - void SetFuncPointer( GSLFuncPointer f) { fFunc.f = f; } - void SetDerivPointer( GSLFuncPointer f) { fFunc.df = f; } - void SetFdfPointer( GSLFdfPointer f) { fFunc.fdf = f; } + void SetFuncPointer( GSLFuncPointer f) { fFunc.f = f; } + void SetDerivPointer( GSLFuncPointer f) { fFunc.df = f; } + void SetFdfPointer( GSLFdfPointer f) { fFunc.fdf = f; } void SetParams ( void * p) { fFunc.params = p; } - - gsl_function_fdf * GetFunc() { return &fFunc; } + + gsl_function_fdf * GetFunc() { return &fFunc; } // evaluate the function and derivatives double operator() (double x) { return GSL_FN_FDF_EVAL_F(&fFunc, x); } - double Derivative (double x) { return GSL_FN_FDF_EVAL_DF(&fFunc, x); } + double Derivative (double x) { return GSL_FN_FDF_EVAL_DF(&fFunc, x); } - void Fdf(double x, double & f, double & df) { + void Fdf(double x, double & f, double & df) { return GSL_FN_FDF_EVAL_F_DF(&fFunc, x, &f, &df); } - /// check if function is valid (has been set) - bool IsValid() { - return (fFunc.f != 0 ) ? true : false; + /// check if function is valid (has been set) + bool IsValid() { + return (fFunc.f != 0 ) ? true : false; } - private: - gsl_function_fdf fFunc; + private: + gsl_function_fdf fFunc; }; diff --git a/ThirdParty/RootMinimizers/inc/Math/GSLMinimizer.h b/ThirdParty/RootMinimizers/inc/Math/GSLMinimizer.h index 7f85ecbaca0ac62abe4ecab460363046218c5ba5..cac104ae61353c5848fa440c7554f1bacbd46667 100644 --- a/ThirdParty/RootMinimizers/inc/Math/GSLMinimizer.h +++ b/ThirdParty/RootMinimizers/inc/Math/GSLMinimizer.h @@ -48,134 +48,134 @@ #include <vector> #include <map> -#include <string> +#include <string> -namespace ROOT { +namespace ROOT { -namespace Math { +namespace Math { /** enumeration specifying the types of GSL minimizers @ingroup MultiMin */ - enum EGSLMinimizerType { - kConjugateFR, - kConjugatePR, - kVectorBFGS, - kVectorBFGS2, + enum EGSLMinimizerType { + kConjugateFR, + kConjugatePR, + kVectorBFGS, + kVectorBFGS2, kSteepestDescent }; - class GSLMultiMinimizer; + class GSLMultiMinimizer; class MinimTransformFunction; //_____________________________________________________________________________________ -/** - GSLMinimizer class. - Implementation of the ROOT::Math::Minimizer interface using the GSL multi-dimensional +/** + GSLMinimizer class. + Implementation of the ROOT::Math::Minimizer interface using the GSL multi-dimensional minimization algorithms. - See <A HREF="http://www.gnu.org/software/gsl/manual/html_node/Multidimensional-Minimization.html">GSL doc</A> - from more info on the GSL minimization algorithms. + See <A HREF="http://www.gnu.org/software/gsl/manual/html_node/Multidimensional-Minimization.html">GSL doc</A> + from more info on the GSL minimization algorithms. - The class implements the ROOT::Math::Minimizer interface and can be instantiated using the - ROOT plugin manager (plugin name is "GSLMultiMin"). The varius minimization algorithms - (conjugatefr, conjugatepr, bfgs, etc..) can be passed as enumerations and also as a string. - The default algorithm is conjugatefr (Fletcher-Reeves conjugate gradient algorithm). + The class implements the ROOT::Math::Minimizer interface and can be instantiated using the + ROOT plugin manager (plugin name is "GSLMultiMin"). The varius minimization algorithms + (conjugatefr, conjugatepr, bfgs, etc..) can be passed as enumerations and also as a string. + The default algorithm is conjugatefr (Fletcher-Reeves conjugate gradient algorithm). @ingroup MultiMin -*/ +*/ class GSLMinimizer : public ROOT::Math::BasicMinimizer { -public: +public: - /** + /** Default constructor - */ - GSLMinimizer (ROOT::Math::EGSLMinimizerType type = ROOT::Math::kConjugateFR ); + */ + GSLMinimizer (ROOT::Math::EGSLMinimizerType type = ROOT::Math::kConjugateFR ); /** - Constructor with a string giving name of algorithm + Constructor with a string giving name of algorithm */ - GSLMinimizer (const char * type ); + GSLMinimizer (const char * type ); - /** - Destructor - */ - virtual ~GSLMinimizer (); + /** + Destructor + */ + virtual ~GSLMinimizer (); private: // usually copying is non trivial, so we make this unaccessible - /** + /** Copy constructor - */ + */ GSLMinimizer(const GSLMinimizer &) : BasicMinimizer() {} - /** + /** Assignment operator - */ - GSLMinimizer & operator = (const GSLMinimizer & rhs) { + */ + GSLMinimizer & operator = (const GSLMinimizer & rhs) { if (this == &rhs) return *this; // time saving self-test return *this; } -public: +public: /// set the function to minimize - virtual void SetFunction(const ROOT::Math::IMultiGenFunction & func); + virtual void SetFunction(const ROOT::Math::IMultiGenFunction & func); - /// set the function to minimize + /// set the function to minimize virtual void SetFunction(const ROOT::Math::IMultiGradFunction & func) { BasicMinimizer::SetFunction(func);} /// method to perform the minimization - virtual bool Minimize(); + virtual bool Minimize(); /// return expected distance reached from the minimum virtual double Edm() const { return 0; } // not impl. } - /// return pointer to gradient values at the minimum - virtual const double * MinGradient() const; + /// return pointer to gradient values at the minimum + virtual const double * MinGradient() const; - /// number of function calls to reach the minimum - virtual unsigned int NCalls() const; + /// number of function calls to reach the minimum + virtual unsigned int NCalls() const; /// minimizer provides error and error matrix - virtual bool ProvidesError() const { return false; } + virtual bool ProvidesError() const { return false; } - /// return errors at the minimum - virtual const double * Errors() const { + /// return errors at the minimum + virtual const double * Errors() const { return 0; } - /** return covariance matrices elements + /** return covariance matrices elements if the variable is fixed the matrix is zero The ordering of the variables is the same as in errors - */ + */ virtual double CovMatrix(unsigned int , unsigned int ) const { return 0; } -protected: +protected: + +private: + -private: - + ROOT::Math::GSLMultiMinimizer * fGSLMultiMin; - ROOT::Math::GSLMultiMinimizer * fGSLMultiMin; - double fLSTolerance; // Line Search Tolerance -}; +}; } // end namespace Fit diff --git a/ThirdParty/RootMinimizers/inc/Math/GSLMinimizer1D.h b/ThirdParty/RootMinimizers/inc/Math/GSLMinimizer1D.h index 3aa57443541e9756c6152d8d665f67e9ba5d233a..27395272711a468a6989e8a45172485305ab3b9e 100644 --- a/ThirdParty/RootMinimizers/inc/Math/GSLMinimizer1D.h +++ b/ThirdParty/RootMinimizers/inc/Math/GSLMinimizer1D.h @@ -22,11 +22,11 @@ **********************************************************************/ // Header file for class GSLMinimizer1D -// +// // Created by: moneta at Wed Dec 1 15:04:51 2004 -// +// // Last update: Wed Dec 1 15:04:51 2004 -// +// #ifndef ROOT_Math_GSLMinimizer1D #define ROOT_Math_GSLMinimizer1D @@ -35,43 +35,43 @@ #include "Math/GSLFunctionAdapter.h" -namespace ROOT { -namespace Math { +namespace ROOT { +namespace Math { namespace Minim1D { - - /** - Enumeration with One Dimensional Minimizer Algorithms. - The algorithms are implemented using GSL, see the + + /** + Enumeration with One Dimensional Minimizer Algorithms. + The algorithms are implemented using GSL, see the <A HREF="http://www.gnu.org/software/gsl/manual/gsl-ref_33.html#SEC447">GSL manual</A>. - - The algorithms available are: + + The algorithms available are: <ul> - <li><em>Golden Section Algorithm</em>, simplest method of bracketing the minimum of a function + <li><em>Golden Section Algorithm</em>, simplest method of bracketing the minimum of a function <li><em>Brent Algorithm</em>, which combines a parabolic interpolation with the golden section algorithm </ul> @ingroup Min1D */ - - enum Type {kGOLDENSECTION, + + enum Type {kGOLDENSECTION, kBRENT }; } - - class GSL1DMinimizerWrapper; + + class GSL1DMinimizerWrapper; class GSLFunctionWrapper; //______________________________________________________________________________________ -/** +/** -Minimizer for arbitrary one dimensional functions. +Minimizer for arbitrary one dimensional functions. -Implemented using GSL, for detailed description see: +Implemented using GSL, for detailed description see: <A HREF="http://www.gnu.org/software/gsl/manual/html_node/One-dimensional-Minimization.html">GSL online doc</A> -The algorithms uspported are only bracketing algorithm which do not use derivatives information. -The algorithms which can be chosen at construction time are GOLDENSECTION, whic is the simplest method -but the slowest and BRENT (the default one) which combines the golden section with a parabolic interpolation. +The algorithms uspported are only bracketing algorithm which do not use derivatives information. +The algorithms which can be chosen at construction time are GOLDENSECTION, whic is the simplest method +but the slowest and BRENT (the default one) which combines the golden section with a parabolic interpolation. This class does not support copying @@ -80,99 +80,99 @@ This class does not support copying class GSLMinimizer1D: public IMinimizer1D { - public: + public: /** Construct the minimizer passing the minimizer type using the Minim1D::Algorithm enumeration */ - + explicit GSLMinimizer1D(Minim1D::Type type=Minim1D::kBRENT); - + /** Destructor: free allocated resources */ - virtual ~GSLMinimizer1D(); + virtual ~GSLMinimizer1D(); private: // usually copying is non trivial, so we make this unaccessible - GSLMinimizer1D(const GSLMinimizer1D &); - GSLMinimizer1D & operator = (const GSLMinimizer1D &); - - public: - - - /** + GSLMinimizer1D(const GSLMinimizer1D &); + GSLMinimizer1D & operator = (const GSLMinimizer1D &); + + public: + + + /** Set, or reset, minimizer to use the function f and the initial search interval [xlow, xup], with a guess for the location of the minimum xmin. The condition : \f$ f(xlow) > f(xmin) < f(xup)\f$ must be satisfied */ - template <class UserFunc> - void SetFunction( const UserFunc & f, double xmin, double xlow, double xup) { - const void * p = &f; - SetFunction( &GSLFunctionAdapter<UserFunc>::F, const_cast<void *>(p), xmin, xlow, xup ); + template <class UserFunc> + void SetFunction( const UserFunc & f, double xmin, double xlow, double xup) { + const void * p = &f; + SetFunction( &GSLFunctionAdapter<UserFunc>::F, const_cast<void *>(p), xmin, xlow, xup ); } - - /** + + /** Set, or reset, minimizer to use the function f and the initial search interval [xlow, xup], with a guess for the location of the minimum xmin. The condition : \f$ f(xlow) > f(xmin) < f(xup) \f$ must be satisfied - - Method specialized on the GSL function type + + Method specialized on the GSL function type */ - void SetFunction( GSLFuncPointer f, void * params, double xmin, double xlow, double xup); - - /** - Perform a minimizer iteration and + void SetFunction( GSLFuncPointer f, void * params, double xmin, double xlow, double xup); + + /** + Perform a minimizer iteration and if an unexepcted problem occurr then an error code will be returned */ - int Iterate(); + int Iterate(); - /** + /** Return current estimate of the position of the minimum */ - double XMinimum() const; + double XMinimum() const; /** Return current lower bound of the minimization interval */ - double XLower() const; - + double XLower() const; + /** Return current upper bound of the minimization interval */ - double XUpper() const; + double XUpper() const; - /** + /** Return function value at current estimate of the minimum */ - double FValMinimum() const; + double FValMinimum() const; /** Return function value at current lower bound of the minimization interval */ - double FValLower() const; - + double FValLower() const; + /** Return function value at current upper bound of the minimization interval */ - double FValUpper() const; - - + double FValUpper() const; + + /** - Find minimum position iterating until convergence specified by the absolute and relative tolerance or - the maximum number of iteration is reached + Find minimum position iterating until convergence specified by the absolute and relative tolerance or + the maximum number of iteration is reached Return true is result is successfull \@param maxIter maximum number of iteration \@param absTol desired absolute error in the minimum position \@param absTol desired relative error in the minimum position */ - bool Minimize( int maxIter, double absTol, double relTol); + bool Minimize( int maxIter, double absTol, double relTol); /** Return number of iteration used to find minimum */ int Iterations() const { - return fIter; + return fIter; } /** @@ -183,38 +183,38 @@ This class does not support copying /** Return name of minimization algorithm */ - const char * Name() const; + const char * Name() const; /** - Test convergence of the interval. - The test returns success if + Test convergence of the interval. + The test returns success if \f[ |x_{min}-x_{truemin}| < epsAbs + epsRel *x_{truemin} \f] */ - static int TestInterval( double xlow, double xup, double epsAbs, double epsRel); + static int TestInterval( double xlow, double xup, double epsAbs, double epsRel); - protected: + protected: - private: + private: - double fXmin; + double fXmin; double fXlow; - double fXup; - double fMin; + double fXup; + double fMin; double fLow; - double fUp; - int fIter; + double fUp; + int fIter; int fStatus; // status of last minimization (==0 ok =1 failed) - bool fIsSet; + bool fIsSet; - GSL1DMinimizerWrapper * fMinimizer; - GSLFunctionWrapper * fFunction; + GSL1DMinimizerWrapper * fMinimizer; + GSLFunctionWrapper * fFunction; - }; + }; } // end namespace Math diff --git a/ThirdParty/RootMinimizers/inc/Math/GSLRndmEngines.h b/ThirdParty/RootMinimizers/inc/Math/GSLRndmEngines.h index f1abd5324015646559e9b280f80a56a1c5891163..53aa3aac52c4e554b606aad6c13481203a9b6373 100644 --- a/ThirdParty/RootMinimizers/inc/Math/GSLRndmEngines.h +++ b/ThirdParty/RootMinimizers/inc/Math/GSLRndmEngines.h @@ -1,5 +1,5 @@ // @(#)root/mathmore:$Id$ -// Author: L. Moneta, A. Zsenei 08/2005 +// Author: L. Moneta, A. Zsenei 08/2005 /********************************************************************** * * @@ -23,11 +23,11 @@ **********************************************************************/ // Header file for class GSLRandom -// +// // Created by: moneta at Sun Nov 21 16:26:03 2004 -// +// // Last update: Sun Nov 21 16:26:03 2004 -// +// #ifndef ROOT_Math_GSLRndmEngines #define ROOT_Math_GSLRndmEngines @@ -38,65 +38,65 @@ namespace ROOT { namespace Math { - class GSLRngWrapper; + class GSLRngWrapper; //_________________________________________________________________ /** GSLRandomEngine - Base class for all GSL random engines, + Base class for all GSL random engines, normally user instantiate the derived classes which creates internally the generator. - The main GSL generators (see + The main GSL generators (see <A HREF="http://www.gnu.org/software/gsl/manual/html_node/Random-number-generator-algorithms.html"> - here</A>) are available as derived classes - In addition to generate uniform numbers it provides method for - generating numbers according to pre-defined distributions - using the GSL functions from + here</A>) are available as derived classes + In addition to generate uniform numbers it provides method for + generating numbers according to pre-defined distributions + using the GSL functions from <A HREF="http://www.gnu.org/software/gsl/manual/html_node/Random-Number-Distributions.html"> - GSL random number distributions</A>. + GSL random number distributions</A>. + - @ingroup Random - */ - class GSLRandomEngine { + */ + class GSLRandomEngine { - public: + public: - /** - default constructor. No creation of rng is done. - If then Initialize() is called an engine is created - based on default GSL type (MT) + /** + default constructor. No creation of rng is done. + If then Initialize() is called an engine is created + based on default GSL type (MT) */ - GSLRandomEngine(); + GSLRandomEngine(); - /** - create from an existing rng. + /** + create from an existing rng. User manage the rng pointer which is then deleted olny by calling Terminate() */ - GSLRandomEngine( GSLRngWrapper * rng); + GSLRandomEngine( GSLRngWrapper * rng); /** Copy constructor : clone the contained GSL generator */ - GSLRandomEngine(const GSLRandomEngine & eng); + GSLRandomEngine(const GSLRandomEngine & eng); /** Assignment operator : make a deep copy of the contained GSL generator */ - GSLRandomEngine & operator=(const GSLRandomEngine & eng); + GSLRandomEngine & operator=(const GSLRandomEngine & eng); /** - initialize the generator - If no rng is present the default one based on Mersenne and Twister is created + initialize the generator + If no rng is present the default one based on Mersenne and Twister is created */ void Initialize(); /** - delete pointer to contained rng + delete pointer to contained rng */ - void Terminate(); + void Terminate(); /** call Terminate() @@ -107,50 +107,50 @@ namespace Math { Generate a random number between ]0,1] 0 is excluded and 1 is included */ - double operator() () const; + double operator() () const; - /** + /** Generate an integer number between [0,max-1] (including 0 and max-1) - if max is larger than available range of algorithm + if max is larger than available range of algorithm an error message is printed and zero is returned */ - unsigned int RndmInt(unsigned int max) const; + unsigned int RndmInt(unsigned int max) const; /** - Generate an array of random numbers. - The iterators points to the random numbers + Generate an array of random numbers. + The iterators points to the random numbers */ - template<class Iterator> - void RandomArray(Iterator begin, Iterator end) const { - for ( Iterator itr = begin; itr != end; ++itr ) { - *itr = this->operator()(); + template<class Iterator> + void RandomArray(Iterator begin, Iterator end) const { + for ( Iterator itr = begin; itr != end; ++itr ) { + *itr = this->operator()(); } } /** - Generate an array of random numbers - The iterators points to the random numbers + Generate an array of random numbers + The iterators points to the random numbers */ - void RandomArray(double * begin, double * end) const; + void RandomArray(double * begin, double * end) const; /** return name of generator - */ - std::string Name() const; + */ + std::string Name() const; + + /** + return the state size of generator + */ + unsigned int Size() const; /** - return the state size of generator - */ - unsigned int Size() const; - - /** - set the random generator seed - */ - void SetSeed(unsigned int seed) const; + set the random generator seed + */ + void SetSeed(unsigned int seed) const; - /** @name Random Distributions - Implemented using the + /** @name Random Distributions + Implemented using the <A HREF="http://www.gnu.org/software/gsl/manual/html_node/Random-Number-Distributions.html"> GSL Random number Distributions</A> **/ @@ -158,27 +158,27 @@ namespace Math { /** Gaussian distribution - default method is Box-Muller (polar method) */ - double Gaussian(double sigma) const; + double Gaussian(double sigma) const; /** Gaussian distribution - Ziggurat method */ - double GaussianZig(double sigma) const; + double GaussianZig(double sigma) const; /** Gaussian distribution - Ratio method */ - double GaussianRatio(double sigma) const; + double GaussianRatio(double sigma) const; /** Gaussian Tail distribution */ - double GaussianTail(double a, double sigma) const; - + double GaussianTail(double a, double sigma) const; + /** Bivariate Gaussian distribution with correlation */ void Gaussian2D(double sigmaX, double sigmaY, double rho, double &x, double &y) const; - + /** Exponential distribution */ @@ -187,12 +187,12 @@ namespace Math { /** Cauchy distribution */ - double Cauchy(double a) const; + double Cauchy(double a) const; /** Landau distribution */ - double Landau() const; + double Landau() const; /** Gamma distribution @@ -213,22 +213,22 @@ namespace Math { F distrbution */ double FDist(double nu1, double nu2) const; - + /** t student distribution */ double tDist(double nu) const; /** - generate random numbers in a 2D circle of radious 1 + generate random numbers in a 2D circle of radious 1 */ - void Dir2D(double &x, double &y) const; + void Dir2D(double &x, double &y) const; /** - generate random numbers in a 3D sphere of radious 1 + generate random numbers in a 3D sphere of radious 1 */ - void Dir3D(double &x, double &y, double &z) const; - + void Dir3D(double &x, double &y, double &z) const; + /** Poisson distribution */ @@ -247,39 +247,39 @@ namespace Math { /** Multinomial distribution */ - std::vector<unsigned int> Multinomial( unsigned int ntot, const std::vector<double> & p ) const; + std::vector<unsigned int> Multinomial( unsigned int ntot, const std::vector<double> & p ) const; //@} - - - protected: - /// internal method used by the derived class to set the type of generators - void SetType(GSLRngWrapper * r) { - fRng = r; + + protected: + + /// internal method used by the derived class to set the type of generators + void SetType(GSLRngWrapper * r) { + fRng = r; } - private: + private: GSLRngWrapper * fRng; // pointer to GSL generator wrapper (managed by the class) mutable unsigned int fCurTime; // current time used to seed the generator - - }; - + + }; + //_____________________________________________________________________________________ /** Mersenne-Twister generator - gsl_rng_mt19937 from + gsl_rng_mt19937 from <A HREF="http://www.gnu.org/software/gsl/manual/html_node/Random-number-generator-algorithms.html">here</A> - + @ingroup Random */ - class GSLRngMT : public GSLRandomEngine { - public: - GSLRngMT(); + class GSLRngMT : public GSLRandomEngine { + public: + GSLRngMT(); }; //_____________________________________________________________________________________ @@ -290,9 +290,9 @@ namespace Math { @ingroup Random */ - class GSLRngRanLux : public GSLRandomEngine { - public: - GSLRngRanLux(); + class GSLRngRanLux : public GSLRandomEngine { + public: + GSLRngRanLux(); }; //_____________________________________________________________________________________ @@ -303,9 +303,9 @@ namespace Math { @ingroup Random */ - class GSLRngRanLuxS1 : public GSLRandomEngine { - public: - GSLRngRanLuxS1(); + class GSLRngRanLuxS1 : public GSLRandomEngine { + public: + GSLRngRanLuxS1(); }; typedef GSLRngRanLuxS1 GSLRngRanLux1; // for backward compatibility @@ -317,9 +317,9 @@ namespace Math { @ingroup Random */ - class GSLRngRanLuxS2 : public GSLRandomEngine { - public: - GSLRngRanLuxS2(); + class GSLRngRanLuxS2 : public GSLRandomEngine { + public: + GSLRngRanLuxS2(); }; typedef GSLRngRanLuxS2 GSLRngRanLux2; // for backward compatibility @@ -331,9 +331,9 @@ namespace Math { @ingroup Random */ - class GSLRngRanLuxD1 : public GSLRandomEngine { - public: - GSLRngRanLuxD1(); + class GSLRngRanLuxD1 : public GSLRandomEngine { + public: + GSLRngRanLuxD1(); }; //_____________________________________________________________________________________ @@ -344,9 +344,9 @@ namespace Math { @ingroup Random */ - class GSLRngRanLuxD2 : public GSLRandomEngine { - public: - GSLRngRanLuxD2(); + class GSLRngRanLuxD2 : public GSLRandomEngine { + public: + GSLRngRanLuxD2(); }; typedef GSLRngRanLuxD2 GSLRngRanLux48; // for backward compatibility @@ -358,9 +358,9 @@ namespace Math { @ingroup Random */ - class GSLRngTaus : public GSLRandomEngine { - public: - GSLRngTaus(); + class GSLRngTaus : public GSLRandomEngine { + public: + GSLRngTaus(); }; //_____________________________________________________________________________________ @@ -370,9 +370,9 @@ namespace Math { @ingroup Random */ - class GSLRngGFSR4 : public GSLRandomEngine { - public: - GSLRngGFSR4(); + class GSLRngGFSR4 : public GSLRandomEngine { + public: + GSLRngGFSR4(); }; //_____________________________________________________________________________________ @@ -381,10 +381,10 @@ namespace Math { see <A HREF="http://www.gnu.org/software/gsl/manual/html_node/Random-number-generator-algorithms.html">here</A> @ingroup Random - */ - class GSLRngCMRG : public GSLRandomEngine { - public: - GSLRngCMRG(); + */ + class GSLRngCMRG : public GSLRandomEngine { + public: + GSLRngCMRG(); }; //_____________________________________________________________________________________ @@ -393,35 +393,35 @@ namespace Math { see <A HREF="http://www.gnu.org/software/gsl/manual/html_node/Random-number-generator-algorithms.html">here</A> @ingroup Random - */ - class GSLRngMRG : public GSLRandomEngine { - public: - GSLRngMRG(); + */ + class GSLRngMRG : public GSLRandomEngine { + public: + GSLRngMRG(); }; //_____________________________________________________________________________________ /** - BSD rand() generator - gsl_rmg_rand from + BSD rand() generator + gsl_rmg_rand from <A HREF="http://www.gnu.org/software/gsl/manual/html_node/Unix-random-number-generators.html">here</A> - + @ingroup Random */ - class GSLRngRand : public GSLRandomEngine { - public: - GSLRngRand(); + class GSLRngRand : public GSLRandomEngine { + public: + GSLRngRand(); }; //_____________________________________________________________________________________ /** - RANMAR generator + RANMAR generator see <A HREF="http://www.gnu.org/software/gsl/manual/html_node/Unix-random-number-generators.html">here</A> @ingroup Random */ - class GSLRngRanMar : public GSLRandomEngine { - public: - GSLRngRanMar(); + class GSLRngRanMar : public GSLRandomEngine { + public: + GSLRngRanMar(); }; //_____________________________________________________________________________________ @@ -431,11 +431,11 @@ namespace Math { @ingroup Random */ - class GSLRngMinStd : public GSLRandomEngine { - public: - GSLRngMinStd(); + class GSLRngMinStd : public GSLRandomEngine { + public: + GSLRngMinStd(); }; - + diff --git a/ThirdParty/RootMinimizers/inc/Math/GSLSimAnnealing.h b/ThirdParty/RootMinimizers/inc/Math/GSLSimAnnealing.h index eb5705ee02de76dad67e0570044bfb2626f17649..f6f4e83bfb1e46151c4ff8fa83dbc5d2bd957c7c 100644 --- a/ThirdParty/RootMinimizers/inc/Math/GSLSimAnnealing.h +++ b/ThirdParty/RootMinimizers/inc/Math/GSLSimAnnealing.h @@ -31,108 +31,108 @@ #include <vector> -namespace ROOT { +namespace ROOT { - namespace Math { + namespace Math { class GSLRandomEngine; //_____________________________________________________________________________ /** - GSLSimAnFunc class description. - Interface class for the objetive function to be used in simulated annealing + GSLSimAnFunc class description. + Interface class for the objetive function to be used in simulated annealing If user wants to re-implement some of the methods (like the one defining the metric) which are used by the the simulated annealing algorithm must build a user derived class. NOTE: Derived classes must re-implement the assignment and copy constructor to call them of the parent class @ingroup MultiMin */ -class GSLSimAnFunc { -public: +class GSLSimAnFunc { +public: /** construct from an interface of a multi-dimensional function */ - GSLSimAnFunc(const ROOT::Math::IMultiGenFunction & func, const double * x); + GSLSimAnFunc(const ROOT::Math::IMultiGenFunction & func, const double * x); /** construct from an interface of a multi-dimensional function Use optionally a scale factor (for each coordinate) which can be used to scale the step sizes (this is used for example by the minimization algorithm) */ - GSLSimAnFunc(const ROOT::Math::IMultiGenFunction & func, const double * x, const double * scale); - -protected: + GSLSimAnFunc(const ROOT::Math::IMultiGenFunction & func, const double * x, const double * scale); + +protected: /** - derived classes might need to re-define completely the class + derived classes might need to re-define completely the class */ - GSLSimAnFunc() : + GSLSimAnFunc() : fFunc(0) {} -public: +public: - /// virtual distructor (no operations) + /// virtual distructor (no operations) virtual ~GSLSimAnFunc() { } // /** fast copy method called by GSL simuated annealing internally - copy only the things which have been changed + copy only the things which have been changed must be re-implemented by derived classes if needed */ - virtual GSLSimAnFunc & FastCopy(const GSLSimAnFunc & f); + virtual GSLSimAnFunc & FastCopy(const GSLSimAnFunc & f); /** - clone method. Needs to be re-implemented by the derived classes for deep copying + clone method. Needs to be re-implemented by the derived classes for deep copying */ - virtual GSLSimAnFunc * Clone() const { - return new GSLSimAnFunc(*this); + virtual GSLSimAnFunc * Clone() const { + return new GSLSimAnFunc(*this); } /** - evaluate the energy ( objective function value) + evaluate the energy ( objective function value) re-implement by derived classes if needed to be modified */ - virtual double Energy() const; + virtual double Energy() const; /** change the x[i] value using a random value urndm generated between [0,1] up to a maximum value maxstep - re-implement by derived classes if needed to be modified + re-implement by derived classes if needed to be modified */ virtual void Step(const GSLRandomEngine & r, double maxstep); /** calculate the distance (metric) between this one and another configuration - Presently a cartesian metric is used. - re-implement by derived classes if needed to be modified + Presently a cartesian metric is used. + re-implement by derived classes if needed to be modified */ - virtual double Distance(const GSLSimAnFunc & func) const; + virtual double Distance(const GSLSimAnFunc & func) const; /** - print the position in the standard output ostream + print the position in the standard output std::ostream GSL prints in addition n iteration, n function calls, temperature and energy re-implement by derived classes if necessary */ virtual void Print(); - /** + /** change the x values (used by sim annealing to take a step) - */ - void SetX(const double * x) { + */ + void SetX(const double * x) { std::copy(x, x+ fX.size(), fX.begin() ); } - template <class IT> - void SetX(IT begin, IT end) { + template <class IT> + void SetX(IT begin, IT end) { std::copy(begin, end, fX.begin() ); } - unsigned int NDim() const { return fX.size(); } + unsigned int NDim() const { return fX.size(); } double X(unsigned int i) const { return fX[i]; } @@ -140,20 +140,20 @@ public: double Scale(unsigned int i) const { return fScale[i]; } - void SetX(unsigned int i, double x) { fX[i] = x; } + void SetX(unsigned int i, double x) { fX[i] = x; } - // use compiler generated copy ctror and assignment operators + // use compiler generated copy ctror and assignment operators -private: +private: - std::vector<double> fX; - std::vector<double> fScale; + std::vector<double> fX; + std::vector<double> fScale; const ROOT::Math::IMultiGenFunction * fFunc; - -}; + +}; //_____________________________________________________ -/** +/** structure holding the simulated annealing parameters @ingroup MultiMin @@ -161,93 +161,93 @@ private: struct GSLSimAnParams { // constructor with some default values - GSLSimAnParams() { - n_tries = 200; - iters_fixed_T = 10; - step_size = 10; + GSLSimAnParams() { + n_tries = 200; + iters_fixed_T = 10; + step_size = 10; // the following parameters are for the Boltzmann distribution */ - k = 1.0; - t_initial = 0.002; - mu = 1.005; + k = 1.0; + t_initial = 0.002; + mu = 1.005; t_min = 2.0E-6; } - + int n_tries; // number of points to try for each step int iters_fixed_T; // number of iterations at each temperature double step_size; // max step size used in random walk /// parameters for the Boltzman distribution - double k; - double t_initial; - double mu; - double t_min; -}; + double k; + double t_initial; + double mu; + double t_min; +}; //___________________________________________________________________________ -/** - GSLSimAnnealing class for performing a simulated annealing search of +/** + GSLSimAnnealing class for performing a simulated annealing search of a multidimensional function @ingroup MultiMin -*/ +*/ class GSLSimAnnealing { -public: +public: - /** + /** Default constructor - */ + */ GSLSimAnnealing (); - /** + /** Destructor (no operations) - */ - ~GSLSimAnnealing () {} + */ + ~GSLSimAnnealing () {} private: // usually copying is non trivial, so we make this unaccessible - /** + /** Copy constructor - */ - GSLSimAnnealing(const GSLSimAnnealing &) {} + */ + GSLSimAnnealing(const GSLSimAnnealing &) {} - /** + /** Assignment operator - */ + */ GSLSimAnnealing & operator = (const GSLSimAnnealing & rhs) { if (this == &rhs) return *this; // time saving self-test return *this; } -public: +public: /** - solve the simulated annealing given a multi-dim function, the initial vector parameters - and a vector containing the scaling factors for the parameters + solve the simulated annealing given a multi-dim function, the initial vector parameters + and a vector containing the scaling factors for the parameters */ - int Solve(const ROOT::Math::IMultiGenFunction & func, const double * x0, const double * scale, double * xmin, bool debug = false); + int Solve(const ROOT::Math::IMultiGenFunction & func, const double * x0, const double * scale, double * xmin, bool debug = false); /** - solve the simulated annealing given a GSLSimAnFunc object + solve the simulated annealing given a GSLSimAnFunc object The object will contain the initial state at the beginning and the final minimum state at the end */ - int Solve(GSLSimAnFunc & func, bool debug = false); + int Solve(GSLSimAnFunc & func, bool debug = false); GSLSimAnParams & Params() { return fParams; } const GSLSimAnParams & Params() const { return fParams; } - -protected: +protected: -private: + +private: GSLSimAnParams fParams; // parameters for GSLSimAnnealig -}; +}; } // end namespace Math diff --git a/ThirdParty/RootMinimizers/inc/Math/GenAlgoOptions.h b/ThirdParty/RootMinimizers/inc/Math/GenAlgoOptions.h index 61f01448f501e947a6cc2e0470dcc1d9fabdd5f0..d880f7edaffad988cec8f062e023159e5f27b430 100644 --- a/ThirdParty/RootMinimizers/inc/Math/GenAlgoOptions.h +++ b/ThirdParty/RootMinimizers/inc/Math/GenAlgoOptions.h @@ -1,4 +1,4 @@ -// @(#)root/mathcore:$Id$ +// @(#)root/mathcore:$Id$ // Author: L. Moneta Nov 2010 /********************************************************************** @@ -19,13 +19,13 @@ #include <map> #include <iomanip> -namespace ROOT { - namespace Math { +namespace ROOT { + namespace Math { //_______________________________________________________________________________ -/** +/** class implementing generic options for a numerical algorithm - Just store the options in a map of string-value pairs + Just store the options in a map of string-value pairs @ingroup NumAlgo */ @@ -44,35 +44,35 @@ public: // methods implementing the IOptions interface - virtual IOptions * Clone() const { + virtual IOptions * Clone() const { return new GenAlgoOptions(*this); } - // t.b.d need probably to implement in a .cxx file for CINT + // t.b.d need probably to implement in a .cxx file for CINT - virtual bool GetRealValue(const char * name, double & val) const { + virtual bool GetRealValue(const char * name, double & val) const { const double * pval = FindValue(name, fRealOpts); - if (!pval) return false; + if (!pval) return false; val = *pval; - return true; + return true; } - virtual bool GetIntValue(const char * name, int & val) const { + virtual bool GetIntValue(const char * name, int & val) const { const int * pval = FindValue(name, fIntOpts); if (!pval) return false; val = *pval; - return true; + return true; } - virtual bool GetNamedValue(const char * name, std::string & val) const { + virtual bool GetNamedValue(const char * name, std::string & val) const { const std::string * pval = FindValue(name, fNamOpts); - if (!pval) return false; + if (!pval) return false; val = *pval; return true; } - /// method wich need to be re-implemented by the derived classes + /// method wich need to be re-implemented by the derived classes virtual void SetRealValue(const char * name, double val) { InsertValue(name, fRealOpts, val); } @@ -86,68 +86,68 @@ public: } - /// print options + /// print options virtual void Print(std::ostream & os = std::cout ) const { Print(fNamOpts,os); Print(fIntOpts,os); Print(fRealOpts,os); - } + } - // static methods to retrieve the default options + // static methods to retrieve the default options - // find the option given a name + // find the option given a name // return 0 if the option is not found static IOptions * FindDefault(const char * algoname); - // retrieve options given the name - // if option is not found create a new GenAlgoOption for the given name + // retrieve options given the name + // if option is not found create a new GenAlgoOption for the given name static IOptions & Default(const char * algoname); /// print all the default options - static void PrintAllDefault(std::ostream & os = std::cout); + static void PrintAllDefault(std::ostream & os = std::cout); + +protected: -protected: - -private: - - template<class M> +private: + + template<class M> static const typename M::mapped_type * FindValue(const std::string & name, const M & opts) { - typename M::const_iterator pos; - pos = opts.find(name); - if (pos == opts.end()) { - return 0; + typename M::const_iterator pos; + pos = opts.find(name); + if (pos == opts.end()) { + return 0; } - return &((*pos).second); - } + return &((*pos).second); + } - template<class M> + template<class M> static void InsertValue(const std::string &name, M & opts, const typename M::mapped_type & value) { - typename M::iterator pos; - pos = opts.find(name); - if (pos != opts.end()) { - pos->second = value; + typename M::iterator pos; + pos = opts.find(name); + if (pos != opts.end()) { + pos->second = value; } - else { + else { opts.insert(typename M::value_type(name, value) ); } - } + } - template<class M> + template<class M> static void Print( const M & opts, std::ostream & os) { - //const std::ios_base::fmtflags prevFmt = os.flags(); - for (typename M::const_iterator pos = opts.begin(); pos != opts.end(); ++pos) + //const std::ios_base::fmtflags prevFmt = os.flags(); + for (typename M::const_iterator pos = opts.begin(); pos != opts.end(); ++pos) os << std::setw(25) << pos->first << " : " << std::setw(15) << pos->second << std::endl; - } + } - std::map<std::string, double> fRealOpts; // map of the real options - std::map<std::string, int> fIntOpts; // map of the integer options + std::map<std::string, double> fRealOpts; // map of the real options + std::map<std::string, int> fIntOpts; // map of the integer options std::map<std::string, std::string> fNamOpts; // map of the named options - + }; diff --git a/ThirdParty/RootMinimizers/inc/Math/GeneticMinimizer.h b/ThirdParty/RootMinimizers/inc/Math/GeneticMinimizer.h index 46e3a0f4e5e0644c81cc43fadc380ecf695e4c1d..db8b83cee4631328d5498b0bcec28f83a55099f0 100644 --- a/ThirdParty/RootMinimizers/inc/Math/GeneticMinimizer.h +++ b/ThirdParty/RootMinimizers/inc/Math/GeneticMinimizer.h @@ -19,41 +19,41 @@ #include "TMVA/IFitterTarget.h" #include "TMVA/Interval.h" -namespace ROOT { - namespace Math { +namespace ROOT { + namespace Math { //_______________________________________________________________________________ /* - structure containing the parameters of the genetic minimizer - */ -struct GeneticMinimizerParameters { + structure containing the parameters of the genetic minimizer + */ +struct GeneticMinimizerParameters { Int_t fPopSize; Int_t fNsteps; - Int_t fCycles; + Int_t fCycles; Int_t fSC_steps; Int_t fSC_rate; Double_t fSC_factor; Double_t fConvCrit; - Int_t fSeed; - + Int_t fSeed; + // constructor with default value - GeneticMinimizerParameters(); + GeneticMinimizerParameters(); }; //_______________________________________________________________________________ -/** +/** GeneticMinimizer @ingroup MultiMin */ class GeneticMinimizer: public ROOT::Math::Minimizer { -public: +public: //GeneticMinimizer (int = 0); GeneticMinimizer (int i = 0); @@ -61,26 +61,26 @@ public: virtual void Clear(); using ROOT::Math::Minimizer::SetFunction; - virtual void SetFunction(const ROOT::Math::IMultiGenFunction & func); + virtual void SetFunction(const ROOT::Math::IMultiGenFunction & func); virtual bool SetLimitedVariable(unsigned int , const std::string& , double , double , double, double); - virtual bool SetVariable(unsigned int ivar, const std::string & name, double val, double step); - virtual bool SetFixedVariable(unsigned int ivar , const std::string & name , double val); + virtual bool SetVariable(unsigned int ivar, const std::string & name, double val, double step); + virtual bool SetFixedVariable(unsigned int ivar , const std::string & name , double val); - virtual bool Minimize(); - virtual double MinValue() const; - virtual double Edm() const; - virtual const double * X() const; - virtual const double * MinGradient() const; - virtual unsigned int NCalls() const; + virtual bool Minimize(); + virtual double MinValue() const; + virtual double Edm() const; + virtual const double * X() const; + virtual const double * MinGradient() const; + virtual unsigned int NCalls() const; - virtual unsigned int NDim() const; - virtual unsigned int NFree() const; + virtual unsigned int NDim() const; + virtual unsigned int NFree() const; - virtual bool ProvidesError() const; + virtual bool ProvidesError() const; virtual const double * Errors() const; - virtual double CovMatrix(unsigned int i, unsigned int j) const; + virtual double CovMatrix(unsigned int i, unsigned int j) const; void SetParameters(const GeneticMinimizerParameters & params ); @@ -88,22 +88,22 @@ public: const GeneticMinimizerParameters & MinimizerParameters() const { return fParameters; } - virtual ROOT::Math::MinimizerOptions Options() const; + virtual ROOT::Math::MinimizerOptions Options() const; virtual void SetOptions(const ROOT::Math::MinimizerOptions & opt); protected: - void GetGeneticOptions(ROOT::Math::MinimizerOptions & opt) const; + void GetGeneticOptions(ROOT::Math::MinimizerOptions & opt) const; std::vector<TMVA::Interval*> fRanges; TMVA::IFitterTarget* fFitness; double fMinValue; std::vector<double> fResult; - GeneticMinimizerParameters fParameters; + GeneticMinimizerParameters fParameters; -}; +}; } // end namespace Math diff --git a/ThirdParty/RootMinimizers/inc/Math/IFunction.h b/ThirdParty/RootMinimizers/inc/Math/IFunction.h index 8077c274d212cc0616f8223e4196243ac172e399..99480319616807ff2ea444dc6c9548c14cb0eb79 100644 --- a/ThirdParty/RootMinimizers/inc/Math/IFunction.h +++ b/ThirdParty/RootMinimizers/inc/Math/IFunction.h @@ -1,5 +1,5 @@ // @(#)root/mathcore:$Id$ -// Authors: L. Moneta 11/2006 +// Authors: L. Moneta 11/2006 /********************************************************************** * * @@ -8,28 +8,28 @@ * * **********************************************************************/ -// Header file for function interfaces -// +// Header file for function interfaces +// // Generic Interfaces for one or multi-dimensional functions // // Created by: Lorenzo Moneta : Wed Nov 13 2006 -// -// +// +// #ifndef ROOT_Math_IFunction #define ROOT_Math_IFunction -/** +/** @defgroup CppFunctions Function Classes and Interfaces - Interfaces (abstract classes) and Base classes used in MathCore and MathMore numerical methods - for describing function classes. They define function and gradient evaluation and as well the - functionality for dealing with parameters in the case of parametric functions which are used for - fitting and data modeling. - Included are also adapter classes, such as functors, to wrap generic callable C++ objects - in the desired interface. + Interfaces (abstract classes) and Base classes used in MathCore and MathMore numerical methods + for describing function classes. They define function and gradient evaluation and as well the + functionality for dealing with parameters in the case of parametric functions which are used for + fitting and data modeling. + Included are also adapter classes, such as functors, to wrap generic callable C++ objects + in the desired interface. */ -//typedefs and tags definitions +//typedefs and tags definitions #ifndef ROOT_Math_IFunctionfwd #include "Math/IFunctionfwd.h" #endif @@ -44,50 +44,50 @@ namespace Math { */ //___________________________________________________________________________________ - /** + /** Documentation for the abstract class IBaseFunctionMultiDim. - Interface (abstract class) for generic functions objects of multi-dimension - Provides a method to evaluate the function given a vector of coordinate values, + Interface (abstract class) for generic functions objects of multi-dimension + Provides a method to evaluate the function given a vector of coordinate values, by implementing operator() (const double *). - In addition it defines the interface for copying functions via the pure virtual method Clone() - and the interface for getting the function dimension via the NDim() method. - Derived classes must implement the pure private virtual method DoEval(const double *) for the - function evaluation in addition to NDim() and Clone(). - + In addition it defines the interface for copying functions via the pure virtual method Clone() + and the interface for getting the function dimension via the NDim() method. + Derived classes must implement the pure private virtual method DoEval(const double *) for the + function evaluation in addition to NDim() and Clone(). + @ingroup GenFunc */ class IBaseFunctionMultiDim { - - public: - typedef IBaseFunctionMultiDim BaseFunc; + public: + + typedef IBaseFunctionMultiDim BaseFunc; IBaseFunctionMultiDim() {} /** - virtual destructor + virtual destructor */ virtual ~IBaseFunctionMultiDim() {} - /** - Clone a function. - Each derived class must implement his version of the Clone method + /** + Clone a function. + Each derived class must implement their version of the Clone method */ - virtual IBaseFunctionMultiDim * Clone() const = 0; + virtual IBaseFunctionMultiDim * Clone() const = 0; /** Retrieve the dimension of the function */ - virtual unsigned int NDim() const = 0; + virtual unsigned int NDim() const = 0; - /** - Evaluate the function at a point x[]. + /** + Evaluate the function at a point x[]. Use the pure virtual private method DoEval which must be implemented by the sub-classes - */ - double operator() (const double* x) const { - return DoEval(x); + */ + double operator() (const double* x) const { + return DoEval(x); } #ifdef LATER @@ -96,80 +96,80 @@ namespace Math { User is responsible to provide correct size for the iterator */ template <class Iterator> - double operator() (const Iterator it ) const { - return DoEval( &(*it) ); + double operator() (const Iterator it ) const { + return DoEval( &(*it) ); } #endif - private: + private: /** Implementation of the evaluation function. Must be implemented by derived classes */ - virtual double DoEval(const double * x) const = 0; + virtual double DoEval(const double * x) const = 0; - }; + }; //___________________________________________________________________________________ - /** - Interface (abstract class) for generic functions objects of one-dimension - Provides a method to evaluate the function given a value (simple double) + /** + Interface (abstract class) for generic functions objects of one-dimension + Provides a method to evaluate the function given a value (simple double) by implementing operator() (const double ). - In addition it defines the interface for copying functions via the pure virtual method Clone(). - Derived classes must implement the pure virtual private method DoEval(double ) for the - function evaluation in addition to Clone(). - An interface for evaluating the function passing a vector (like for multidim functions) is also + In addition it defines the interface for copying functions via the pure virtual method Clone(). + Derived classes must implement the pure virtual private method DoEval(double ) for the + function evaluation in addition to Clone(). + An interface for evaluating the function passing a vector (like for multidim functions) is also provided - + @ingroup GenFunc */ - class IBaseFunctionOneDim { + class IBaseFunctionOneDim { - public: + public: - typedef IBaseFunctionOneDim BaseFunc; + typedef IBaseFunctionOneDim BaseFunc; IBaseFunctionOneDim() {} /** - virtual destructor + virtual destructor */ virtual ~IBaseFunctionOneDim() {} - /** - Clone a function. - Each derived class will implement his version of the provate DoClone method + /** + Clone a function. + Each derived class will implement their version of the provate DoClone method */ - virtual IBaseFunctionOneDim * Clone() const = 0; + virtual IBaseFunctionOneDim * Clone() const = 0; - /** - Evaluate the function at a point x + /** + Evaluate the function at a point x Use the a pure virtual private method DoEval which must be implemented by sub-classes - */ - double operator() (double x) const { - return DoEval(x); + */ + double operator() (double x) const { + return DoEval(x); } - /** - Evaluate the function at a point x[]. + /** + Evaluate the function at a point x[]. Compatible method with multi-dimensional functions - */ - double operator() (const double * x) const { - return DoEval(*x); + */ + double operator() (const double * x) const { + return DoEval(*x); } - private: + private: - // use private virtual inheritance + // use private virtual inheritance /// implementation of the evaluation function. Must be implemented by derived classes - virtual double DoEval(double x) const = 0; + virtual double DoEval(double x) const = 0; }; @@ -178,107 +178,107 @@ namespace Math { //___________________________________________________________________________________ /** - Gradient interface (abstract class) defining the signature for calculating the gradient of a - multi-dimensional function. - Three methods are provided: + Gradient interface (abstract class) defining the signature for calculating the gradient of a + multi-dimensional function. + Three methods are provided: - Gradient(const double *x, double * grad) evaluate the full gradient vector at the vector value x - Derivative(const double * x, int icoord) evaluate the partial derivative for the icoord coordinate - - FdF(const double *x, double &f, double * g) evaluate at the same time gradient and function/ + - FdF(const double *x, double &f, double * g) evaluate at the same time gradient and function/ - Concrete classes should derive from ROOT::Math::IGradientFunctionMultiDim and not from this class. + Concrete classes should derive from ROOT::Math::IGradientFunctionMultiDim and not from this class. @ingroup GenFunc */ - class IGradientMultiDim { + class IGradientMultiDim { - public: + public: - /// virual destructor + /// virual destructor virtual ~IGradientMultiDim() {} - /** + /** Evaluate all the vector of function derivatives (gradient) at a point x. Derived classes must re-implement if it is more efficient than evaluting one at a time */ - virtual void Gradient(const double *x, double * grad) const = 0; + virtual void Gradient(const double *x, double * grad) const = 0; /** - Return the partial derivative with respect to the passed coordinate + Return the partial derivative with respect to the passed coordinate */ - double Derivative(const double * x, unsigned int icoord = 0) const { - return DoDerivative(x, icoord); + double Derivative(const double * x, unsigned int icoord = 0) const { + return DoDerivative(x, icoord); } - - /** + + /** Optimized method to evaluate at the same time the function value and derivative at a point x. Often both value and derivatives are needed and it is often more efficient to compute them at the same time. - Derived class should implement this method if performances play an important role and if it is faster to + Derived class should implement this method if performances play an important role and if it is faster to evaluate value and derivative at the same time - + */ - virtual void FdF (const double * x, double & f, double * df) const = 0; + virtual void FdF (const double * x, double & f, double * df) const = 0; - private: + private: /** - function to evaluate the derivative with respect each coordinate. To be implemented by the derived class - */ - virtual double DoDerivative(const double * x, unsigned int icoord ) const = 0; + function to evaluate the derivative with respect each coordinate. To be implemented by the derived class + */ + virtual double DoDerivative(const double * x, unsigned int icoord ) const = 0; }; //___________________________________________________________________________________ /** Specialized Gradient interface(abstract class) for one dimensional functions - It provides a method to evaluate the derivative of the function, Derivative and a - method to evaluate at the same time the function and the derivative FdF + It provides a method to evaluate the derivative of the function, Derivative and a + method to evaluate at the same time the function and the derivative FdF - Concrete classes should derive from ROOT::Math::IGradientFunctionOneDim and not from this class. + Concrete classes should derive from ROOT::Math::IGradientFunctionOneDim and not from this class. @ingroup GenFunc */ - class IGradientOneDim { + class IGradientOneDim { - public: + public: - /// virtual destructor + /// virtual destructor virtual ~IGradientOneDim() {} /** - Return the derivative of the function at a point x - Use the private method DoDerivative + Return the derivative of the function at a point x + Use the private method DoDerivative */ - double Derivative(double x ) const { - return DoDerivative(x ); + double Derivative(double x ) const { + return DoDerivative(x ); } - - /** + + /** Optimized method to evaluate at the same time the function value and derivative at a point x. Often both value and derivatives are needed and it is often more efficient to compute them at the same time. - Derived class should implement this method if performances play an important role and if it is faster to + Derived class should implement this method if performances play an important role and if it is faster to evaluate value and derivative at the same time - + */ - virtual void FdF (double x, double & f, double & df) const = 0; + virtual void FdF (double x, double & f, double & df) const = 0; /** Compatibility method with multi-dimensional interface for partial derivative */ - double Derivative(const double * x) const { - return DoDerivative( *x); + double Derivative(const double * x) const { + return DoDerivative( *x); } /** Compatibility method with multi-dimensional interface for Gradient */ - void Gradient(const double * x, double *g) const { - g[0] = DoDerivative( *x); + void Gradient(const double * x, double *g) const { + g[0] = DoDerivative( *x); } /** @@ -287,129 +287,129 @@ namespace Math { void FdF(const double * x, double & f, double * df) const { FdF(*x, f, *df); } - - private: + + private: /** - function to evaluate the derivative with respect each coordinate. To be implemented by the derived class - */ - virtual double DoDerivative(double x ) const = 0; + function to evaluate the derivative with respect each coordinate. To be implemented by the derived class + */ + virtual double DoDerivative(double x ) const = 0; }; //___________________________________________________________________________________ -/** - Interface (abstract class) for multi-dimensional functions providing a gradient calculation. - It implements both the ROOT::Math::IBaseFunctionMultiDim and +/** + Interface (abstract class) for multi-dimensional functions providing a gradient calculation. + It implements both the ROOT::Math::IBaseFunctionMultiDim and ROOT::Math::IGradientMultiDim interfaces. - The method ROOT::Math::IFunction::Gradient calculates the full gradient vector, - ROOT::Math::IFunction::Derivative calculates the partial derivative for each coordinate and - ROOT::Math::Fdf calculates the gradient and the function value at the same time. - The pure private virtual method DoDerivative() must be implemented by the derived classes, while - Gradient and FdF are by default implemented using DoDerivative, butthey can be overloaded by the - derived classes to improve the efficiency in the derivative calculation. + The method ROOT::Math::IFunction::Gradient calculates the full gradient vector, + ROOT::Math::IFunction::Derivative calculates the partial derivative for each coordinate and + ROOT::Math::Fdf calculates the gradient and the function value at the same time. + The pure private virtual method DoDerivative() must be implemented by the derived classes, while + Gradient and FdF are by default implemented using DoDerivative, butthey can be overloaded by the + derived classes to improve the efficiency in the derivative calculation. @ingroup GenFunc -*/ +*/ - class IGradientFunctionMultiDim : - virtual public IBaseFunctionMultiDim , - public IGradientMultiDim { - + class IGradientFunctionMultiDim : + virtual public IBaseFunctionMultiDim , + public IGradientMultiDim { - public: - typedef IBaseFunctionMultiDim BaseFunc; - typedef IGradientMultiDim BaseGrad; + public: + typedef IBaseFunctionMultiDim BaseFunc; + typedef IGradientMultiDim BaseGrad; - /** + + /** Virtual Destructor (no operations) - */ + */ virtual ~IGradientFunctionMultiDim () {} - /** + /** Evaluate all the vector of function derivatives (gradient) at a point x. Derived classes must re-implement it if more efficient than evaluting one at a time */ - virtual void Gradient(const double *x, double * grad) const { - unsigned int ndim = NDim(); - for (unsigned int icoord = 0; icoord < ndim; ++icoord) - grad[icoord] = BaseGrad::Derivative(x,icoord); + virtual void Gradient(const double *x, double * grad) const { + unsigned int ndim = NDim(); + for (unsigned int icoord = 0; icoord < ndim; ++icoord) + grad[icoord] = BaseGrad::Derivative(x,icoord); } using BaseFunc::NDim; - - /** + + /** Optimized method to evaluate at the same time the function value and derivative at a point x. Often both value and derivatives are needed and it is often more efficient to compute them at the same time. - Derived class should implement this method if performances play an important role and if it is faster to + Derived class should implement this method if performances play an important role and if it is faster to evaluate value and derivative at the same time - + */ - virtual void FdF (const double * x, double & f, double * df) const { - f = BaseFunc::operator()(x); + virtual void FdF (const double * x, double & f, double * df) const { + f = BaseFunc::operator()(x); Gradient(x,df); } - }; + }; //___________________________________________________________________________________ -/** - Interface (abstract class) for one-dimensional functions providing a gradient calculation. - It implements both the ROOT::Math::IBaseFunctionOneDim and +/** + Interface (abstract class) for one-dimensional functions providing a gradient calculation. + It implements both the ROOT::Math::IBaseFunctionOneDim and ROOT::Math::IGradientOneDim interfaces. - The method ROOT::Math::IFunction::Derivative calculates the derivative and - ROOT::Math::Fdf calculates the derivative and the function values at the same time. - The pure private virtual method DoDerivative() must be implemented by the derived classes, while - FdF is by default implemented using DoDerivative, but it can be overloaded by the - derived classes to improve the efficiency in the derivative calculation. + The method ROOT::Math::IFunction::Derivative calculates the derivative and + ROOT::Math::Fdf calculates the derivative and the function values at the same time. + The pure private virtual method DoDerivative() must be implemented by the derived classes, while + FdF is by default implemented using DoDerivative, but it can be overloaded by the + derived classes to improve the efficiency in the derivative calculation. @ingroup GenFunc -*/ +*/ //template <> - class IGradientFunctionOneDim : - virtual public IBaseFunctionOneDim , - public IGradientOneDim { - + class IGradientFunctionOneDim : + virtual public IBaseFunctionOneDim , + public IGradientOneDim { + - public: + public: - typedef IBaseFunctionOneDim BaseFunc; - typedef IGradientOneDim BaseGrad; + typedef IBaseFunctionOneDim BaseFunc; + typedef IGradientOneDim BaseGrad; - /** + /** Virtual Destructor (no operations) - */ + */ virtual ~IGradientFunctionOneDim () {} - /** + /** Optimized method to evaluate at the same time the function value and derivative at a point x. Often both value and derivatives are needed and it is often more efficient to compute them at the same time. - Derived class should implement this method if performances play an important role and if it is faster to + Derived class should implement this method if performances play an important role and if it is faster to evaluate value and derivative at the same time - + */ - virtual void FdF (double x, double & f, double & df) const { - f = operator()(x); + virtual void FdF (double x, double & f, double & df) const { + f = operator()(x); df = Derivative(x); } - }; + }; + - } // namespace Math } // namespace ROOT diff --git a/ThirdParty/RootMinimizers/inc/Math/IFunctionfwd.h b/ThirdParty/RootMinimizers/inc/Math/IFunctionfwd.h index 22597d1e1d8b5aad299d712a998dff001ade7956..6c88a599c3c934f01455e001ec2d72ccca47eb6b 100644 --- a/ThirdParty/RootMinimizers/inc/Math/IFunctionfwd.h +++ b/ThirdParty/RootMinimizers/inc/Math/IFunctionfwd.h @@ -8,28 +8,28 @@ * * **********************************************************************/ -// Defines Forward declaration for template IFunction class and useful typedefs +// Defines Forward declaration for template IFunction class and useful typedefs #ifndef ROOT_Math_IFunctionfwd #define ROOT_Math_IFunctionfwd -namespace ROOT { +namespace ROOT { - namespace Math { + namespace Math { - class IBaseFunctionOneDim; - class IGradientFunctionOneDim; - class IBaseFunctionMultiDim; - class IGradientFunctionMultiDim; + class IBaseFunctionOneDim; + class IGradientFunctionOneDim; + class IBaseFunctionMultiDim; + class IGradientFunctionMultiDim; - typedef IBaseFunctionOneDim IGenFunction; - typedef IBaseFunctionMultiDim IMultiGenFunction; + typedef IBaseFunctionOneDim IGenFunction; + typedef IBaseFunctionMultiDim IMultiGenFunction; + + typedef IGradientFunctionOneDim IGradFunction; + typedef IGradientFunctionMultiDim IMultiGradFunction; - typedef IGradientFunctionOneDim IGradFunction; - typedef IGradientFunctionMultiDim IMultiGradFunction; - } // end namespace Math diff --git a/ThirdParty/RootMinimizers/inc/Math/IMinimizer1D.h b/ThirdParty/RootMinimizers/inc/Math/IMinimizer1D.h index 10206bed80da08218fd767ea81a8b8f5a28c5aad..7dfee80f3845742d915757a572030b0c538aba59 100644 --- a/ThirdParty/RootMinimizers/inc/Math/IMinimizer1D.h +++ b/ThirdParty/RootMinimizers/inc/Math/IMinimizer1D.h @@ -22,68 +22,68 @@ **********************************************************************/ // Header file for class Minimizer1D -// +// // Created by: Maline at Fri Feb 1 11:30:26 2008 -// +// #ifndef ROOT_Math_IMinimizer1D #define ROOT_Math_IMinimizer1D /** - @defgroup Min1D One-dimensional Minimization + @defgroup Min1D One-dimensional Minimization @ingroup NumAlgo */ -namespace ROOT { -namespace Math { +namespace ROOT { +namespace Math { //___________________________________________________________________________________________ /** Interface class for numerical methods for one-dimensional minimization @ingroup Min1D - + */ class IMinimizer1D { - - public: - - IMinimizer1D() {} - virtual ~IMinimizer1D() {} - - public: - + + public: + + IMinimizer1D() {} + virtual ~IMinimizer1D() {} + + public: + /** * Return current estimate of the position of the minimum */ - virtual double XMinimum() const = 0; + virtual double XMinimum() const = 0; /** * Return current lower bound of the minimization interval */ - virtual double XLower() const = 0; + virtual double XLower() const = 0; /** * Return current upper bound of the minimization interval */ - virtual double XUpper() const = 0; + virtual double XUpper() const = 0; /** * Return function value at current estimate of the minimum */ - virtual double FValMinimum() const = 0; + virtual double FValMinimum() const = 0; /** * Return function value at current lower bound of the minimization interval */ - virtual double FValLower() const = 0; + virtual double FValLower() const = 0; /** * Return function value at current upper bound of the minimization interval */ - virtual double FValUpper() const = 0; + virtual double FValUpper() const = 0; /** * Find minimum position iterating until convergence specified by the absolute and relative tolerance or @@ -93,7 +93,7 @@ namespace Math { * \@param absTol desired absolute error in the minimum position * \@param absTol desired relative error in the minimum position */ - virtual bool Minimize( int maxIter, double absTol, double relTol) = 0; + virtual bool Minimize( int maxIter, double absTol, double relTol) = 0; /** * Return number of iteration used to find minimum @@ -103,16 +103,16 @@ namespace Math { /** * Return name of minimization algorithm */ - virtual const char * Name() const = 0; + virtual const char * Name() const = 0; /** Returns the status of the previous estimate */ - virtual int Status() const = 0; + virtual int Status() const = 0; }; // end class IMinimizer1D - + } // end namespace Math - + } // end namespace ROOT #endif /* ROOT_Math_IMinimizer1D */ diff --git a/ThirdParty/RootMinimizers/inc/Math/IOptions.h b/ThirdParty/RootMinimizers/inc/Math/IOptions.h index 5d03142c7ce3deac4d9a6c173e69e5ee94bbd8bc..9a744b0a500d2798b0f86c75e46e1bf10571789c 100644 --- a/ThirdParty/RootMinimizers/inc/Math/IOptions.h +++ b/ThirdParty/RootMinimizers/inc/Math/IOptions.h @@ -1,4 +1,4 @@ -// @(#)root/mathcore:$Id$ +// @(#)root/mathcore:$Id$ // Author: L. Moneta Fri Aug 15 2008 /********************************************************************** @@ -18,13 +18,13 @@ #include <iostream> -namespace ROOT { - +namespace ROOT { - namespace Math { + + namespace Math { //_______________________________________________________________________________ -/** +/** Generic interface for defining configuration options of a numerical algorithm @ingroup NumAlgo @@ -37,49 +37,49 @@ public: virtual ~IOptions() {}// { if (fExtraOptions) delete fExtraOptions; } - // copy the options - virtual IOptions * Clone() const = 0; + // copy the options + virtual IOptions * Clone() const = 0; /** generic methods for retrivieng options */ - /// set option value + /// set option value void SetValue(const char * name, double val) { SetRealValue(name,val);} void SetValue(const char * name, int val) { SetIntValue(name,val);} void SetValue(const char * name, const char * val) { SetNamedValue(name,val);} - + double RValue(const char * name) const { double val = 0; bool ret = GetRealValue(name,val); - if (!ret ) MATH_ERROR_MSGVAL("IOptions::RValue"," return 0 - real option not found",name); + if (!ret ) MATH_ERROR_MSGVAL("IOptions::RValue"," return 0 - real option not found",name); return val; } int IValue(const char * name) const { int val = 0; bool ret = GetIntValue(name,val); - if (!ret ) MATH_ERROR_MSGVAL("IOptions::IValue"," return 0 - integer option not found",name); + if (!ret ) MATH_ERROR_MSGVAL("IOptions::IValue"," return 0 - integer option not found",name); return val; } std::string NamedValue(const char * name) const { std::string val; bool ret = GetNamedValue(name,val); - if (!ret ) MATH_ERROR_MSGVAL("IOptions::NamedValue"," return empty string - named option not found",name); + if (!ret ) MATH_ERROR_MSGVAL("IOptions::NamedValue"," return empty string - named option not found",name); return val; } - // generic method to retrieve a type + // generic method to retrieve a type template <typename T> - bool GetValue(const char * name, T & t) const { + bool GetValue(const char * name, T & t) const { bool ret = DoGetValue(name, t); - //if (!ret ) MATH_ERROR_MSG("IOptions::GetValue","option is not existing - returns 0"); - return ret; + //if (!ret ) MATH_ERROR_MSG("IOptions::GetValue","option is not existing - returns 0"); + return ret; } - // methods to be re-implemented in the derived classes + // methods to be re-implemented in the derived classes virtual bool GetRealValue(const char *, double &) const { return false; } @@ -88,7 +88,7 @@ public: virtual bool GetNamedValue(const char *, std::string &) const { return false; } - /// method wich need to be re-implemented by the derived classes + /// method wich need to be re-implemented by the derived classes virtual void SetRealValue(const char * , double ) {MATH_ERROR_MSG("IOptions::SetRealValue","Invalid setter method called"); } virtual void SetIntValue(const char * , int ) {MATH_ERROR_MSG("IOptions::SetIntValue","Invalid setter method called"); } @@ -96,11 +96,11 @@ public: virtual void SetNamedValue(const char * , const char * ) {MATH_ERROR_MSG("IOptions::SetNamedValue","Invalid setter method called"); } - /// print options + /// print options virtual void Print(std::ostream & = std::cout ) const {MATH_INFO_MSG("IOptions::Print","it is not implemented");} -private: +private: bool DoGetValue(const char *name, double &val) const { return GetRealValue(name,val); } @@ -108,7 +108,7 @@ private: bool DoGetValue(const char *name, std::string &val) const { return GetNamedValue(name,val); } - + }; diff --git a/ThirdParty/RootMinimizers/inc/Math/IParamFunction.h b/ThirdParty/RootMinimizers/inc/Math/IParamFunction.h index 26e0e42edec5815bb942570942140c5a355b2bfb..f083dd28d68de6d968fdd3635f5f0f13c662f43a 100644 --- a/ThirdParty/RootMinimizers/inc/Math/IParamFunction.h +++ b/ThirdParty/RootMinimizers/inc/Math/IParamFunction.h @@ -26,39 +26,39 @@ #endif -#include <cassert> +#include <cassert> /** - @defgroup ParamFunc Interfaces for parametric functions + @defgroup ParamFunc Interfaces for parametric functions @ingroup CppFunctions */ -namespace ROOT { +namespace ROOT { -namespace Math { +namespace Math { //___________________________________________________________________ -/** +/** Documentation for the abstract class IBaseParam. It defines the interface for dealing with the function parameters - This is used only for internal convinience, to avoid redefining the Parameter API - for the one and the multi-dim functions. - Concrete class should derive from ROOT::Math::IParamFunction and not from this class. - + This is used only for internal convinience, to avoid redefining the Parameter API + for the one and the multi-dim functions. + Concrete class should derive from ROOT::Math::IParamFunction and not from this class. + @ingroup ParamFunc -*/ +*/ class IBaseParam { -public: +public: - /** + /** Virtual Destructor (no operations) - */ - virtual ~IBaseParam () {} + */ + virtual ~IBaseParam () {} /** @@ -68,25 +68,25 @@ public: /** Set the parameter values - @param p vector of doubles containing the parameter values. + @param p vector of doubles containing the parameter values. - to be defined: can user change number of params ? At the moment no. + to be defined: can user change number of params ? At the moment no. */ virtual void SetParameters(const double * p ) = 0; - + /** Return the number of Parameters */ - virtual unsigned int NPar() const = 0; + virtual unsigned int NPar() const = 0; /** Return the name of the i-th parameter (starting from zero) - Overwrite if want to avoid the default name ("Par_0, Par_1, ...") + Overwrite if want to avoid the default name ("Par_0, Par_1, ...") */ - virtual std::string ParameterName(unsigned int i) const { - assert(i < NPar() ); + virtual std::string ParameterName(unsigned int i) const { + assert(i < NPar() ); return "Par_" + Util::ToString(i); } @@ -94,87 +94,87 @@ public: }; //___________________________________________________________________ -/** +/** IParamFunction interface (abstract class) describing multi-dimensional parameteric functions - It is a derived class from ROOT::Math::IBaseFunctionMultiDim and + It is a derived class from ROOT::Math::IBaseFunctionMultiDim and ROOT::Math::IBaseParam - Provides the interface for evaluating a function passing a coordinate vector and a parameter vector. + Provides the interface for evaluating a function passing a coordinate vector and a parameter vector. @ingroup ParamFunc -*/ +*/ -class IParametricFunctionMultiDim : - virtual public IBaseFunctionMultiDim , +class IParametricFunctionMultiDim : + virtual public IBaseFunctionMultiDim , public IBaseParam { -public: +public: - typedef IBaseFunctionMultiDim BaseFunc; + typedef IBaseFunctionMultiDim BaseFunc; /** Evaluate function at a point x and for given parameters p. - This method does not change the internal status of the function (internal parameter values). - If for some reason one prefers caching the parameter values, SetParameters(p) and then operator()(x) should be + This method does not change the internal status of the function (internal parameter values). + If for some reason one prefers caching the parameter values, SetParameters(p) and then operator()(x) should be called. Use the pure virtual function DoEvalPar to implement it */ - double operator() (const double * x, const double * p ) const { - return DoEvalPar(x, p); + double operator() (const double * x, const double * p ) const { + return DoEvalPar(x, p); } using BaseFunc::operator(); -private: +private: /** - Implementation of the evaluation function using the x values and the parameters. + Implementation of the evaluation function using the x values and the parameters. Must be implemented by derived classes */ - virtual double DoEvalPar(const double * x, const double * p) const = 0; + virtual double DoEvalPar(const double * x, const double * p) const = 0; /** Implement the ROOT::Math::IBaseFunctionMultiDim interface DoEval(x) using the cached parameter values */ - virtual double DoEval(const double *x) const { - return DoEvalPar( x, Parameters() ); + virtual double DoEval(const double *x) const { + return DoEvalPar( x, Parameters() ); } -}; +}; //___________________________________________________________________ -/** +/** Specialized IParamFunction interface (abstract class) for one-dimensional parametric functions - It is a derived class from ROOT::Math::IBaseFunctionOneDim and + It is a derived class from ROOT::Math::IBaseFunctionOneDim and ROOT::Math::IBaseParam @ingroup ParamFunc -*/ +*/ -class IParametricFunctionOneDim : - virtual public IBaseFunctionOneDim, - public IBaseParam { +class IParametricFunctionOneDim : + virtual public IBaseFunctionOneDim, + public IBaseParam { -public: +public: - typedef IBaseFunctionOneDim BaseFunc; + typedef IBaseFunctionOneDim BaseFunc; using BaseFunc::operator(); /** Evaluate function at a point x and for given parameters p. - This method does not change the internal status of the function (internal parameter values). - If for some reason one prefers caching the parameter values, SetParameters(p) and then operator()(x) should be + This method does not change the internal status of the function (internal parameter values). + If for some reason one prefers caching the parameter values, SetParameters(p) and then operator()(x) should be called. Use the pure virtual function DoEvalPar to implement it */ - double operator() ( double x, const double * p ) const { - return DoEvalPar(x, p); + double operator() ( double x, const double * p ) const { + return DoEvalPar(x, p); } @@ -182,59 +182,59 @@ public: multidim-like interface */ double operator() (const double * x, const double * p ) const - { - return DoEvalPar(*x, p); + { + return DoEvalPar(*x, p); } private: /** - Implementation of the evaluation function using the x value and the parameters. + Implementation of the evaluation function using the x value and the parameters. Must be implemented by derived classes */ - virtual double DoEvalPar(double x, const double * p) const = 0; + virtual double DoEvalPar(double x, const double * p) const = 0; /** Implement the ROOT::Math::IBaseFunctionOneDim interface DoEval(x) using the cached parameter values */ - virtual double DoEval(double x) const { - return DoEvalPar( x, Parameters() ); + virtual double DoEval(double x) const { + return DoEvalPar( x, Parameters() ); } -}; +}; //_______________________________________________________________________________ -/** - Interface (abstract class) for parametric gradient multi-dimensional functions providing - in addition to function evaluation with respect to the coordinates - also the gradient with respect to the parameters, via the method ParameterGradient. +/** + Interface (abstract class) for parametric gradient multi-dimensional functions providing + in addition to function evaluation with respect to the coordinates + also the gradient with respect to the parameters, via the method ParameterGradient. It is a derived class from ROOT::Math::IParametricFunctionMultiDim. - The pure private virtual method DoParameterGradient must be implemented by the derived classes - in addition to those inherited by the base abstract classes. + The pure private virtual method DoParameterGradient must be implemented by the derived classes + in addition to those inherited by the base abstract classes. @ingroup ParamFunc -*/ +*/ -class IParametricGradFunctionMultiDim : - public IParametricFunctionMultiDim -// ,public IGradientFunctionMultiDim +class IParametricGradFunctionMultiDim : + public IParametricFunctionMultiDim +// ,public IGradientFunctionMultiDim { -public: +public: - typedef IParametricFunctionMultiDim BaseParamFunc; - typedef IGradientFunctionMultiDim BaseGradFunc; - typedef IParametricFunctionMultiDim::BaseFunc BaseFunc; + typedef IParametricFunctionMultiDim BaseParamFunc; + typedef IGradientFunctionMultiDim BaseGradFunc; + typedef IParametricFunctionMultiDim::BaseFunc BaseFunc; - /** + /** Virtual Destructor (no operations) - */ - virtual ~IParametricGradFunctionMultiDim () {} + */ + virtual ~IParametricGradFunctionMultiDim () {} @@ -244,74 +244,74 @@ public: Evaluate the all the derivatives (gradient vector) of the function with respect to the parameters at a point x. It is optional to be implemented by the derived classes for better efficiency */ - virtual void ParameterGradient(const double * x , const double * p, double * grad ) const { - unsigned int npar = NPar(); - for (unsigned int ipar = 0; ipar < npar; ++ipar) - grad[ipar] = DoParameterDerivative(x,p,ipar); - } + virtual void ParameterGradient(const double * x , const double * p, double * grad ) const { + unsigned int npar = NPar(); + for (unsigned int ipar = 0; ipar < npar; ++ipar) + grad[ipar] = DoParameterDerivative(x,p,ipar); + } /** Evaluate the partial derivative w.r.t a parameter ipar from values and parameters */ - double ParameterDerivative(const double * x, const double * p, unsigned int ipar = 0) const { - return DoParameterDerivative(x, p, ipar); - } + double ParameterDerivative(const double * x, const double * p, unsigned int ipar = 0) const { + return DoParameterDerivative(x, p, ipar); + } /** Evaluate all derivatives using cached parameter values */ - void ParameterGradient(const double * x , double * grad ) const { - return ParameterGradient(x, Parameters(), grad); + void ParameterGradient(const double * x , double * grad ) const { + return ParameterGradient(x, Parameters(), grad); } /** Evaluate partial derivative using cached parameter values */ - double ParameterDerivative(const double * x, unsigned int ipar = 0) const { - return DoParameterDerivative(x, Parameters() , ipar); + double ParameterDerivative(const double * x, unsigned int ipar = 0) const { + return DoParameterDerivative(x, Parameters() , ipar); } -private: +private: /** Evaluate the partial derivative w.r.t a parameter ipar , to be implemented by the derived classes */ - virtual double DoParameterDerivative(const double * x, const double * p, unsigned int ipar) const = 0; + virtual double DoParameterDerivative(const double * x, const double * p, unsigned int ipar) const = 0; }; //_______________________________________________________________________________ -/** - Interface (abstract class) for parametric one-dimensional gradient functions providing - in addition to function evaluation with respect the coordinates - also the gradient with respect to the parameters, via the method ParameterGradient. +/** + Interface (abstract class) for parametric one-dimensional gradient functions providing + in addition to function evaluation with respect the coordinates + also the gradient with respect to the parameters, via the method ParameterGradient. It is a derived class from ROOT::Math::IParametricFunctionOneDim. - - The pure private virtual method DoParameterGradient must be implemented by the derived classes - in addition to those inherited by the base abstract classes. + + The pure private virtual method DoParameterGradient must be implemented by the derived classes + in addition to those inherited by the base abstract classes. @ingroup ParamFunc -*/ +*/ -class IParametricGradFunctionOneDim : +class IParametricGradFunctionOneDim : public IParametricFunctionOneDim // ,public IGradientFunctionOneDim { -public: +public: - typedef IParametricFunctionOneDim BaseParamFunc; - typedef IGradientFunctionOneDim BaseGradFunc; - typedef IParametricFunctionOneDim::BaseFunc BaseFunc; + typedef IParametricFunctionOneDim BaseParamFunc; + typedef IGradientFunctionOneDim BaseGradFunc; + typedef IParametricFunctionOneDim::BaseFunc BaseFunc; - /** + /** Virtual Destructor (no operations) - */ - virtual ~IParametricGradFunctionOneDim () {} + */ + virtual ~IParametricGradFunctionOneDim () {} using BaseParamFunc::operator(); @@ -320,73 +320,73 @@ public: Evaluate the derivatives of the function with respect to the parameters at a point x. It is optional to be implemented by the derived classes for better efficiency if needed */ - virtual void ParameterGradient(double x , const double * p, double * grad ) const { - unsigned int npar = NPar(); - for (unsigned int ipar = 0; ipar < npar; ++ipar) - grad[ipar] = DoParameterDerivative(x, p, ipar); - } + virtual void ParameterGradient(double x , const double * p, double * grad ) const { + unsigned int npar = NPar(); + for (unsigned int ipar = 0; ipar < npar; ++ipar) + grad[ipar] = DoParameterDerivative(x, p, ipar); + } /** Evaluate all derivatives using cached parameter values */ - void ParameterGradient(double x , double * grad ) const { - return ParameterGradient( x, Parameters(), grad); + void ParameterGradient(double x , double * grad ) const { + return ParameterGradient( x, Parameters(), grad); } /** - Compatibility interface with multi-dimensional functions + Compatibility interface with multi-dimensional functions */ - void ParameterGradient(const double * x , const double * p, double * grad ) const { - ParameterGradient(*x, p, grad); - } + void ParameterGradient(const double * x , const double * p, double * grad ) const { + ParameterGradient(*x, p, grad); + } /** Evaluate all derivatives using cached parameter values (multi-dim like interface) */ - void ParameterGradient(const double * x , double * grad ) const { - return ParameterGradient( *x, Parameters(), grad); + void ParameterGradient(const double * x , double * grad ) const { + return ParameterGradient( *x, Parameters(), grad); } /** Partial derivative with respect a parameter */ - double ParameterDerivative(double x, const double * p, unsigned int ipar = 0) const { - return DoParameterDerivative(x, p, ipar); + double ParameterDerivative(double x, const double * p, unsigned int ipar = 0) const { + return DoParameterDerivative(x, p, ipar); } /** Evaluate partial derivative using cached parameter values */ - double ParameterDerivative(double x, unsigned int ipar = 0) const { - return DoParameterDerivative(x, Parameters() , ipar); + double ParameterDerivative(double x, unsigned int ipar = 0) const { + return DoParameterDerivative(x, Parameters() , ipar); } /** Partial derivative with respect a parameter - Compatibility interface with multi-dimensional functions + Compatibility interface with multi-dimensional functions */ - double ParameterDerivative(const double * x, const double * p, unsigned int ipar = 0) const { - return DoParameterDerivative(*x, p, ipar); + double ParameterDerivative(const double * x, const double * p, unsigned int ipar = 0) const { + return DoParameterDerivative(*x, p, ipar); } /** Evaluate partial derivative using cached parameter values (multi-dim like interface) */ - double ParameterDerivative(const double * x, unsigned int ipar = 0) const { - return DoParameterDerivative( *x, Parameters() , ipar); + double ParameterDerivative(const double * x, unsigned int ipar = 0) const { + return DoParameterDerivative( *x, Parameters() , ipar); } -private: +private: /** Evaluate the gradient, to be implemented by the derived classes */ - virtual double DoParameterDerivative(double x, const double * p, unsigned int ipar ) const = 0; + virtual double DoParameterDerivative(double x, const double * p, unsigned int ipar ) const = 0; }; diff --git a/ThirdParty/RootMinimizers/inc/Math/IParamFunctionfwd.h b/ThirdParty/RootMinimizers/inc/Math/IParamFunctionfwd.h index b0446c40f2b1ca9c0c76f7b48b5a2b1ef0b3a0ac..082d2b121745009c2ac1e3146e862ec6d99d77a9 100644 --- a/ThirdParty/RootMinimizers/inc/Math/IParamFunctionfwd.h +++ b/ThirdParty/RootMinimizers/inc/Math/IParamFunctionfwd.h @@ -17,20 +17,20 @@ #include "Math/IFunctionfwd.h" #endif -namespace ROOT { +namespace ROOT { - namespace Math { + namespace Math { - class IParametricFunctionOneDim; - class IParametricGradFunctionOneDim; - class IParametricFunctionMultiDim; - class IParametricGradFunctionMultiDim; + class IParametricFunctionOneDim; + class IParametricGradFunctionOneDim; + class IParametricFunctionMultiDim; + class IParametricGradFunctionMultiDim; - typedef IParametricFunctionOneDim IParamFunction; - typedef IParametricFunctionMultiDim IParamMultiFunction; + typedef IParametricFunctionOneDim IParamFunction; + typedef IParametricFunctionMultiDim IParamMultiFunction; - typedef IParametricGradFunctionOneDim IParamGradFunction; - typedef IParametricGradFunctionMultiDim IParamMultiGradFunction; + typedef IParametricGradFunctionOneDim IParamGradFunction; + typedef IParametricGradFunctionMultiDim IParamMultiGradFunction; } // end namespace Math diff --git a/ThirdParty/RootMinimizers/inc/Math/MinimTransformFunction.h b/ThirdParty/RootMinimizers/inc/Math/MinimTransformFunction.h index 467de406fc7546f7334c51f92df4cb5fb84027c4..59410da37e82c91dc83e08a15c67043642083860 100644 --- a/ThirdParty/RootMinimizers/inc/Math/MinimTransformFunction.h +++ b/ThirdParty/RootMinimizers/inc/Math/MinimTransformFunction.h @@ -24,69 +24,69 @@ #endif -#include <vector> +#include <vector> #include <map> -namespace ROOT { +namespace ROOT { - namespace Math { + namespace Math { -/** - MinimTransformFunction class to perform a transformations on the +/** + MinimTransformFunction class to perform a transformations on the variables to deal with fixed or limited variables (support both double and single bounds) - The class manages the passed function pointer + The class manages the passed function pointer @ingroup MultiMin -*/ -class MinimTransformFunction : public IMultiGradFunction { +*/ +class MinimTransformFunction : public IMultiGradFunction { -public: +public: - typedef ROOT::Math::IMultiGradFunction BaseGradFunc; - typedef ROOT::Math::IMultiGradFunction::BaseFunc BaseFunc; + typedef ROOT::Math::IMultiGradFunction BaseGradFunc; + typedef ROOT::Math::IMultiGradFunction::BaseFunc BaseFunc; - /** - Constructor from a IMultiGradFunction interface (which is managed by the class) + /** + Constructor from a IMultiGradFunction interface (which is managed by the class) vector specifying the variable types (free, bounded or fixed, defined in enum EMinimVariableTypes ) variable values (used for the fixed ones) and a map with the bounds (for the bounded variables) - */ - MinimTransformFunction ( const IMultiGradFunction * f, const std::vector<ROOT::Math::EMinimVariableType> & types, const std::vector<double> & values, - const std::map<unsigned int, std::pair<double, double> > & bounds); + */ + MinimTransformFunction ( const IMultiGradFunction * f, const std::vector<ROOT::Math::EMinimVariableType> & types, const std::vector<double> & values, + const std::map<unsigned int, std::pair<double, double> > & bounds); - /** + /** Destructor (delete function pointer) - */ - ~MinimTransformFunction () { - if (fFunc) delete fFunc; - } + */ + ~MinimTransformFunction () { + if (fFunc) delete fFunc; + } - // method inherited from IFunction interface + // method inherited from IFunction interface - unsigned int NDim() const { return fIndex.size(); } + unsigned int NDim() const { return fIndex.size(); } - unsigned int NTot() const { return fFunc->NDim(); } + unsigned int NTot() const { return fFunc->NDim(); } /// clone: not supported (since auto_ptr used in the fVariables) - IMultiGenFunction * Clone() const { - return 0; + IMultiGenFunction * Clone() const { + return 0; } - /// transform from internal to external + /// transform from internal to external /// result is cached also inside the class const double * Transformation( const double * x) const { - Transformation(x, &fX[0]); - return &fX.front(); + Transformation(x, &fX[0]); + return &fX.front(); } - /// transform from internal to external + /// transform from internal to external void Transformation( const double * xint, double * xext) const; /// inverse transformation (external -> internal) @@ -96,58 +96,58 @@ public: void InvStepTransformation(const double * x, const double * sext, double * sint) const; ///transform gradient vector (external -> internal) at internal point x - void GradientTransformation(const double * x, const double *gExt, double * gInt) const; + void GradientTransformation(const double * x, const double *gExt, double * gInt) const; ///transform covariance matrix (internal -> external) at internal point x /// use row storages for matrices m(i,j) = rep[ i * dim + j] - void MatrixTransformation(const double * x, const double *covInt, double * covExt) const; + void MatrixTransformation(const double * x, const double *covInt, double * covExt) const; // return original function - const IMultiGradFunction *OriginalFunction() const { return fFunc; } + const IMultiGradFunction *OriginalFunction() const { return fFunc; } -private: +private: /// function evaluation - virtual double DoEval(const double * x) const { -#ifndef DO_THREADSAFE - return (*fFunc)(Transformation(x)); + virtual double DoEval(const double * x) const { +#ifndef DO_THREADSAFE + return (*fFunc)(Transformation(x)); #else std::vector<double> xext(fVariables.size() ); Transformation(x, &xext[0]); - return (*fFunc)(&xext[0]); + return (*fFunc)(&xext[0]); #endif } /// calculate derivatives - virtual double DoDerivative (const double * x, unsigned int icoord ) const { - const MinimTransformVariable & var = fVariables[ fIndex[icoord] ]; + virtual double DoDerivative (const double * x, unsigned int icoord ) const { + const MinimTransformVariable & var = fVariables[ fIndex[icoord] ]; double dExtdInt = (var.IsLimited() ) ? var.DerivativeIntToExt( x[icoord] ) : 1.0; - double deriv = fFunc->Derivative( Transformation(x) , fIndex[icoord] ); + double deriv = fFunc->Derivative( Transformation(x) , fIndex[icoord] ); //std::cout << "Derivative icoord (ext)" << fIndex[icoord] << " dtrafo " << dExtdInt << " " << deriv << std::endl; - return deriv * dExtdInt; - } + return deriv * dExtdInt; + } - // copy constructor for this class (disable by having it private) - MinimTransformFunction( const MinimTransformFunction & ) : + // copy constructor for this class (disable by having it private) + MinimTransformFunction( const MinimTransformFunction & ) : BaseFunc(), BaseGradFunc() {} - // assignment operator for this class (disable by having it private) - MinimTransformFunction & operator= ( const MinimTransformFunction & ) { + // assignment operator for this class (disable by having it private) + MinimTransformFunction & operator= ( const MinimTransformFunction & ) { return *this; } - - -private: + + +private: mutable std::vector<double> fX; // internal cached of external values std::vector<MinimTransformVariable> fVariables; // vector of variable settings and tranformation function - std::vector<unsigned int> fIndex; // vector with external indices for internal variables - const IMultiGradFunction * fFunc; // user function + std::vector<unsigned int> fIndex; // vector with external indices for internal variables + const IMultiGradFunction * fFunc; // user function -}; +}; } // end namespace Math diff --git a/ThirdParty/RootMinimizers/inc/Math/MinimTransformVariable.h b/ThirdParty/RootMinimizers/inc/Math/MinimTransformVariable.h index 296d0dde928bf010aecc8aee51f2b88d557890e8..78a24dc7bac5e0b2c6cb3c6e3220d59fa40eceb5 100644 --- a/ThirdParty/RootMinimizers/inc/Math/MinimTransformVariable.h +++ b/ThirdParty/RootMinimizers/inc/Math/MinimTransformVariable.h @@ -18,17 +18,17 @@ #include <memory> -namespace ROOT { +namespace ROOT { - namespace Math { + namespace Math { /** Enumeration describing the status of the variable The enumeration are used in the minimizer classes to categorize the variables */ - enum EMinimVariableType { + enum EMinimVariableType { kDefault, // free variable (unlimited) - kFix, // fixed variable + kFix, // fixed variable kBounds, // variable has two bounds kLowBound, // variable has a lower bound kUpBound // variable has an upper bounds @@ -36,81 +36,81 @@ namespace ROOT { -/** - MinimTransformVariable class +/** + MinimTransformVariable class Contains meta information of the variables such as bounds, fix flags and deals with transformation of the variable The class does not contain the values and the step size (error) of the variable This is an internal class used by the MinimTransformFunction class @ingroup MultiMin -*/ +*/ -class MinimTransformVariable { +class MinimTransformVariable { -public: +public: - /** + /** Default Constructor for an unlimited variable - */ - MinimTransformVariable () : - fFix(false), fLowBound(false), fUpBound(false), fBounds(false), + */ + MinimTransformVariable () : + fFix(false), fLowBound(false), fUpBound(false), fBounds(false), fTransform(0), fLower(1), fUpper(0) {} // constructor for fixed variable - MinimTransformVariable (double value) : - fFix(true), fLowBound(false), fUpBound(false), fBounds(false), - fTransform(0), fLower(value), fUpper(value) + MinimTransformVariable (double value) : + fFix(true), fLowBound(false), fUpBound(false), fBounds(false), + fTransform(0), fLower(value), fUpper(value) {} // constructor for double bound variable - MinimTransformVariable (double lower, double upper, SinVariableTransformation * trafo) : - fFix(false), fLowBound(false), fUpBound(false), fBounds(true), + MinimTransformVariable (double lower, double upper, SinVariableTransformation * trafo) : + fFix(false), fLowBound(false), fUpBound(false), fBounds(true), fTransform(trafo), fLower(lower), fUpper(upper) { } // constructor for lower bound variable - MinimTransformVariable (double lower, SqrtLowVariableTransformation * trafo) : - fFix(false), fLowBound(true), fUpBound(false), fBounds(false), - fTransform(trafo), fLower(lower), fUpper(lower) + MinimTransformVariable (double lower, SqrtLowVariableTransformation * trafo) : + fFix(false), fLowBound(true), fUpBound(false), fBounds(false), + fTransform(trafo), fLower(lower), fUpper(lower) {} // constructor for upper bound variable - MinimTransformVariable (double upper, SqrtUpVariableTransformation * trafo) : - fFix(false), fLowBound(true), fUpBound(false), fBounds(false), - fTransform(trafo), fLower(upper), fUpper(upper) + MinimTransformVariable (double upper, SqrtUpVariableTransformation * trafo) : + fFix(false), fLowBound(true), fUpBound(false), fBounds(false), + fTransform(trafo), fLower(upper), fUpper(upper) {} - // copy constructor - MinimTransformVariable (const MinimTransformVariable & rhs) : - fFix(rhs.fFix), fLowBound(rhs.fLowBound), fUpBound(rhs.fUpBound), fBounds(rhs.fBounds), + // copy constructor + MinimTransformVariable (const MinimTransformVariable & rhs) : + fFix(rhs.fFix), fLowBound(rhs.fLowBound), fUpBound(rhs.fUpBound), fBounds(rhs.fBounds), fLower(rhs.fLower), fUpper(rhs.fUpper) { // swap auto_ptr - fTransform.reset( const_cast<MinimTransformVariable &>( rhs).fTransform.release() ) ; + fTransform.reset( const_cast<MinimTransformVariable &>( rhs).fTransform.release() ) ; } - // assignment + // assignment MinimTransformVariable & operator= (const MinimTransformVariable & rhs) { - if (&rhs == this) return *this; + if (&rhs == this) return *this; fFix = rhs.fFix; - fLowBound = rhs.fLowBound; - fUpBound = rhs.fUpBound; - fBounds = rhs.fBounds; + fLowBound = rhs.fLowBound; + fUpBound = rhs.fUpBound; + fBounds = rhs.fBounds; fLower = rhs.fLower; fUpper = rhs.fUpper; // swap auto_ptr - fTransform.reset( const_cast<MinimTransformVariable &>( rhs).fTransform.release() ) ; + fTransform.reset( const_cast<MinimTransformVariable &>( rhs).fTransform.release() ) ; return *this; } - + bool IsFixed() const { return fFix; } - - bool IsLimited() const { return fBounds || fLowBound || fUpBound; } + + bool IsLimited() const { return fBounds || fLowBound || fUpBound; } bool HasLowerBound() const { return fLowBound || fBounds; } @@ -122,32 +122,32 @@ public: double FixValue() const { return fLower; } - // internal to external transformation - double InternalToExternal( double x) const { - return (fTransform.get() ) ? fTransform->Int2ext(x, fLower, fUpper) : x; + // internal to external transformation + double InternalToExternal( double x) const { + return (fTransform.get() ) ? fTransform->Int2ext(x, fLower, fUpper) : x; } // derivative of the internal to external transformation ( d Int2Ext / d int ) - double DerivativeIntToExt ( double x) const { - return (fTransform.get() ) ? fTransform->DInt2Ext( x, fLower, fUpper) : 1.0; + double DerivativeIntToExt ( double x) const { + return (fTransform.get() ) ? fTransform->DInt2Ext( x, fLower, fUpper) : 1.0; } // etxernal to internal transformation - double ExternalToInternal(double x) const { - return (fTransform.get() ) ? fTransform->Ext2int(x, fLower, fUpper) : x; + double ExternalToInternal(double x) const { + return (fTransform.get() ) ? fTransform->Ext2int(x, fLower, fUpper) : x; } -private: +private: bool fFix; // fix variable - bool fLowBound; // has lower bound - bool fUpBound; // has uppper bound param + bool fLowBound; // has lower bound + bool fUpBound; // has uppper bound param bool fBounds; // has double bound - std::auto_ptr< MinimizerVariableTransformation> fTransform; // pointer to the minimizer transformation + std::auto_ptr< MinimizerVariableTransformation> fTransform; // pointer to the minimizer transformation double fLower; // lower parameter limit double fUpper; // upper parameter limit - -}; + +}; } // end namespace Math diff --git a/ThirdParty/RootMinimizers/inc/Math/Minimizer.h b/ThirdParty/RootMinimizers/inc/Math/Minimizer.h index 9ea966dfd9c3065cc3631eced6cba22da6e1719c..abdb60367eb56e09cd4ffc49575555dde00d3af5 100644 --- a/ThirdParty/RootMinimizers/inc/Math/Minimizer.h +++ b/ThirdParty/RootMinimizers/inc/Math/Minimizer.h @@ -31,74 +31,74 @@ -#include <vector> -#include <string> +#include <vector> +#include <string> -#include <limits> +#include <limits> #include <cmath> -namespace ROOT { +namespace ROOT { - namespace Fit { + namespace Fit { class ParameterSettings; } - - namespace Math { + + namespace Math { /** @defgroup MultiMin Multi-dimensional Minimization @ingroup NumAlgo - Classes implementing algorithms for multi-dimensional minimization + Classes implementing algorithms for multi-dimensional minimization */ //_______________________________________________________________________________ -/** +/** Abstract Minimizer class, defining the interface for the various minimizer - (like Minuit2, Minuit, GSL, etc..) - Plug-in's exist in ROOT to be able to instantiate the derived classes like - ROOT::Math::GSLMinimizer or ROOT::Math::Minuit2Minimizer via the + (like Minuit2, Minuit, GSL, etc..) + Plug-in's exist in ROOT to be able to instantiate the derived classes like + ROOT::Math::GSLMinimizer or ROOT::Math::Minuit2Minimizer via the plug-in manager. - Provides interface for setting the function to be minimized. + Provides interface for setting the function to be minimized. The function must implemente the multi-dimensional generic interface - ROOT::Math::IBaseFunctionMultiDim. - If the function provides gradient calculation - (implements the ROOT::Math::IGradientFunctionMultiDim interface) this will be - used by the Minimizer. + ROOT::Math::IBaseFunctionMultiDim. + If the function provides gradient calculation + (implements the ROOT::Math::IGradientFunctionMultiDim interface) this will be + used by the Minimizer. - It Defines also interface for setting the initial values for the function variables (which are the parameters in - of the model function in case of solving for fitting) and especifying their limits. + It Defines also interface for setting the initial values for the function variables (which are the parameters in + of the model function in case of solving for fitting) and especifying their limits. - It defines the interface to set and retrieve basic minimization parameters - (for specific Minimizer parameters one must use the derived classes). + It defines the interface to set and retrieve basic minimization parameters + (for specific Minimizer parameters one must use the derived classes). - Then it defines the interface to retrieve the result of minimization ( minimum X values, function value, + Then it defines the interface to retrieve the result of minimization ( minimum X values, function value, gradient, error on the mimnimum, etc...) @ingroup MultiMin */ - + class Minimizer { -public: +public: - /** + /** Default constructor - */ - Minimizer () : + */ + Minimizer () : fValidError(false), fStatus(-1) - {} + {} - /** + /** Destructor (no operations) - */ - virtual ~Minimizer () {} + */ + virtual ~Minimizer () {} @@ -106,142 +106,141 @@ public: private: // usually copying is non trivial, so we make this unaccessible - /** + /** Copy constructor - */ - Minimizer(const Minimizer &) {} + */ + Minimizer(const Minimizer &) {} - /** + /** Assignment operator - */ + */ Minimizer & operator = (const Minimizer & rhs) { if (this == &rhs) return *this; // time saving self-test return *this; } -public: - - /// reset for consecutive minimizations - implement if needed +public: + + /// reset for consecutive minimizations - implement if needed virtual void Clear() {} /// set the function to minimize - virtual void SetFunction(const ROOT::Math::IMultiGenFunction & func) = 0; + virtual void SetFunction(const ROOT::Math::IMultiGenFunction & func) = 0; - /// set a function to minimize using gradient - virtual void SetFunction(const ROOT::Math::IMultiGradFunction & func) + /// set a function to minimize using gradient + virtual void SetFunction(const ROOT::Math::IMultiGradFunction & func) { SetFunction(static_cast<const ::ROOT::Math::IMultiGenFunction &> (func)); } - + /// add variables . Return number of variables successfully added - template<class VariableIterator> - int SetVariables(const VariableIterator & begin, const VariableIterator & end) { - unsigned int ivar = 0; - for ( VariableIterator vitr = begin; vitr != end; ++vitr) { - bool iret = false; + template<class VariableIterator> + int SetVariables(const VariableIterator & begin, const VariableIterator & end) { + unsigned int ivar = 0; + for ( VariableIterator vitr = begin; vitr != end; ++vitr) { + bool iret = false; if (vitr->IsFixed() ) - iret = SetFixedVariable(ivar, vitr->Name(), vitr->Value() ); + iret = SetFixedVariable(ivar, vitr->Name(), vitr->Value() ); else if (vitr->IsDoubleBound() ) iret = SetLimitedVariable(ivar, vitr->Name(), vitr->Value(), vitr->StepSize(), vitr->LowerLimit(), vitr->UpperLimit() ); else if (vitr->HasLowerLimit() ) iret = SetLowerLimitedVariable(ivar, vitr->Name(), vitr->Value(), vitr->StepSize(), vitr->LowerLimit() ); else if (vitr->HasUpperLimit() ) iret = SetUpperLimitedVariable(ivar, vitr->Name(), vitr->Value(), vitr->StepSize(), vitr->UpperLimit() ); - else - iret = SetVariable( ivar, vitr->Name(), vitr->Value(), vitr->StepSize() ); + else + iret = SetVariable( ivar, vitr->Name(), vitr->Value(), vitr->StepSize() ); - if (iret) ivar++; + if (iret) ivar++; // an error message should be eventually be reported in the virtual single SetVariable methods } - return ivar; + return ivar; } - /// set a new free variable - virtual bool SetVariable(unsigned int ivar, const std::string & name, double val, double step) = 0; + /// set a new free variable + virtual bool SetVariable(unsigned int ivar, const std::string & name, double val, double step) = 0; /// set a new lower limit variable (override if minimizer supports them ) - virtual bool SetLowerLimitedVariable(unsigned int ivar , const std::string & name , double val , double step , double lower ) { - return SetLimitedVariable(ivar, name, val, step, lower, std::numeric_limits<double>::infinity() ); - } + virtual bool SetLowerLimitedVariable(unsigned int ivar , const std::string & name , double val , double step , double lower ) { + return SetLimitedVariable(ivar, name, val, step, lower, std::numeric_limits<double>::infinity() ); + } /// set a new upper limit variable (override if minimizer supports them ) - virtual bool SetUpperLimitedVariable(unsigned int ivar , const std::string & name , double val , double step , double upper ) { - return SetLimitedVariable(ivar, name, val, step, - std::numeric_limits<double>::infinity(), upper ); - } + virtual bool SetUpperLimitedVariable(unsigned int ivar , const std::string & name , double val , double step , double upper ) { + return SetLimitedVariable(ivar, name, val, step, - std::numeric_limits<double>::infinity(), upper ); + } /// set a new upper/lower limited variable (override if minimizer supports them ) otherwise as default set an unlimited variable - virtual bool SetLimitedVariable(unsigned int ivar , const std::string & name , double val , double step , - double lower , double upper ) { + virtual bool SetLimitedVariable(unsigned int ivar , const std::string & name , double val , double step , + double lower , double upper ) { MATH_WARN_MSG("Minimizer::SetLimitedVariable","Setting of limited variable not implemented - set as unlimited"); - MATH_UNUSED(lower); MATH_UNUSED(upper); + MATH_UNUSED(lower); MATH_UNUSED(upper); return SetVariable(ivar, name, val, step); } /// set a new fixed variable (override if minimizer supports them ) - virtual bool SetFixedVariable(unsigned int ivar , const std::string & name , double val ) { + virtual bool SetFixedVariable(unsigned int ivar , const std::string & name , double val ) { MATH_ERROR_MSG("Minimizer::SetFixedVariable","Setting of fixed variable not implemented"); - MATH_UNUSED(ivar); MATH_UNUSED(name); MATH_UNUSED(val); - return false; + MATH_UNUSED(ivar); MATH_UNUSED(name); MATH_UNUSED(val); + return false; } - /// set the value of an already existing variable - virtual bool SetVariableValue(unsigned int ivar , double value) { + /// set the value of an already existing variable + virtual bool SetVariableValue(unsigned int ivar , double value) { MATH_ERROR_MSG("Minimizer::SetVariableValue","Set of a variable value not implemented"); MATH_UNUSED(ivar); MATH_UNUSED(value); - return false; + return false; } /// set the values of all existing variables (array must be dimensioned to the size of the existing parameters) - virtual bool SetVariableValues(const double * x) { - bool ret = true; + virtual bool SetVariableValues(const double * x) { + bool ret = true; unsigned int i = 0; - while ( i <= NDim() && ret) { - ret &= SetVariableValue(i,x[i] ); i++; + while ( i <= NDim() && ret) { + ret &= SetVariableValue(i,x[i] ); i++; } - return ret; + return ret; } /// set the step size of an already existing variable virtual bool SetVariableStepSize(unsigned int ivar, double value ) { MATH_ERROR_MSG("Minimizer::SetVariableStepSize","Setting an existing variable step size not implemented"); MATH_UNUSED(ivar); MATH_UNUSED(value); - return false; + return false; } - /// set the lower-limit of an already existing variable - virtual bool SetVariableLowerLimit(unsigned int ivar, double lower) { + /// set the lower-limit of an already existing variable + virtual bool SetVariableLowerLimit(unsigned int ivar, double lower) { MATH_ERROR_MSG("Minimizer::SetVariableLowerLimit","Setting an existing variable limit not implemented"); MATH_UNUSED(ivar); MATH_UNUSED(lower); - return false; + return false; } - /// set the upper-limit of an already existing variable - virtual bool SetVariableUpperLimit(unsigned int ivar, double upper) { + /// set the upper-limit of an already existing variable + virtual bool SetVariableUpperLimit(unsigned int ivar, double upper) { MATH_ERROR_MSG("Minimizer::SetVariableUpperLimit","Setting an existing variable limit not implemented"); MATH_UNUSED(ivar); MATH_UNUSED(upper); - return false; + return false; } - /// set the limits of an already existing variable - virtual bool SetVariableLimits(unsigned int ivar, double lower, double upper) { + /// set the limits of an already existing variable + virtual bool SetVariableLimits(unsigned int ivar, double lower, double upper) { return SetVariableLowerLimit(ivar,lower) && SetVariableUpperLimit(ivar,upper); } /// fix an existing variable - virtual bool FixVariable(unsigned int ivar) { - MATH_ERROR_MSG("Minimizer::FixVariable","Fixing an existing variable not implemented"); + virtual bool FixVariable(unsigned int ivar) { + MATH_ERROR_MSG("Minimizer::FixVariable","Fixing an existing variable not implemented"); MATH_UNUSED(ivar); - return false; + return false; } /// release an existing variable virtual bool ReleaseVariable(unsigned int ivar) { - MATH_ERROR_MSG("Minimizer::ReleaseVariable","Releasing an existing variable not implemented"); + MATH_ERROR_MSG("Minimizer::ReleaseVariable","Releasing an existing variable not implemented"); MATH_UNUSED(ivar); - return false; + return false; } /// query if an existing variable is fixed (i.e. considered constant in the minimization) - /// note that by default all variables are not fixed + /// note that by default all variables are not fixed virtual bool IsFixedVariable(unsigned int ivar) const { - MATH_ERROR_MSG("Minimizer::IsFixedVariable","Quering an existing variable not implemented"); + MATH_ERROR_MSG("Minimizer::IsFixedVariable","Quering an existing variable not implemented"); MATH_UNUSED(ivar); - return false; + return false; } /// get variable settings in a variable object (like ROOT::Fit::ParamsSettings) - virtual bool GetVariableSettings(unsigned int ivar, ROOT::Fit::ParameterSettings & /*pars */ ) const { - MATH_ERROR_MSG("Minimizer::GetVariableSettings","Quering an existing variable not implemented"); - MATH_UNUSED(ivar); - //MATH_UNUSED(pars); - return false; + virtual bool GetVariableSettings(unsigned int ivar, ROOT::Fit::ParameterSettings & pars) const { + MATH_ERROR_MSG("Minimizer::GetVariableSettings","Quering an existing variable not implemented"); + MATH_UNUSED(ivar); MATH_UNUSED(pars); + return false; } @@ -251,229 +250,229 @@ public: } /// method to perform the minimization - virtual bool Minimize() = 0; + virtual bool Minimize() = 0; /// return minimum function value - virtual double MinValue() const = 0; + virtual double MinValue() const = 0; - /// return pointer to X values at the minimum - virtual const double * X() const = 0; + /// return pointer to X values at the minimum + virtual const double * X() const = 0; /// return expected distance reached from the minimum (re-implement if minimizer provides it - virtual double Edm() const { return -1; } + virtual double Edm() const { return -1; } - /// return pointer to gradient values at the minimum + /// return pointer to gradient values at the minimum virtual const double * MinGradient() const { return NULL; } - /// number of function calls to reach the minimum + /// number of function calls to reach the minimum virtual unsigned int NCalls() const { return 0; } - /// number of iterations to reach the minimum - virtual unsigned int NIterations() const { return NCalls(); } + /// number of iterations to reach the minimum + virtual unsigned int NIterations() const { return NCalls(); } - /// this is <= Function().NDim() which is the total - /// number of variables (free+ constrained ones) - virtual unsigned int NDim() const = 0; + /// this is <= Function().NDim() which is the total + /// number of variables (free+ constrained ones) + virtual unsigned int NDim() const = 0; - /// number of free variables (real dimension of the problem) - /// this is <= Function().NDim() which is the total + /// number of free variables (real dimension of the problem) + /// this is <= Function().NDim() which is the total /// (re-implement if minimizer supports bounded parameters) virtual unsigned int NFree() const { return NDim(); } /// minimizer provides error and error matrix virtual bool ProvidesError() const { return false; } - /// return errors at the minimum + /// return errors at the minimum virtual const double * Errors() const { return NULL; } /** return covariance matrices element for variables ivar,jvar if the variable is fixed the return value is zero - The ordering of the variables is the same as in the parameter and errors vectors - */ + The ordering of the variables is the same as in the parameter and errors vectors + */ virtual double CovMatrix(unsigned int ivar , unsigned int jvar ) const { MATH_UNUSED(ivar); MATH_UNUSED(jvar); - return 0; + return 0; } - /** - Fill the passed array with the covariance matrix elements - if the variable is fixed or const the value is zero. + /** + Fill the passed array with the covariance matrix elements + if the variable is fixed or const the value is zero. The array will be filled as cov[i *ndim + j] - The ordering of the variables is the same as in errors and parameter value. - This is different from the direct interface of Minuit2 or TMinuit where the + The ordering of the variables is the same as in errors and parameter value. + This is different from the direct interface of Minuit2 or TMinuit where the values were obtained only to variable parameters - */ - virtual bool GetCovMatrix(double * covMat) const { + */ + virtual bool GetCovMatrix(double * covMat) const { MATH_UNUSED(covMat); - return false; - } + return false; + } - /** - Fill the passed array with the Hessian matrix elements - The Hessian matrix is the matrix of the second derivatives + /** + Fill the passed array with the Hessian matrix elements + The Hessian matrix is the matrix of the second derivatives and is the inverse of the covariance matrix - If the variable is fixed or const the values for that variables are zero. + If the variable is fixed or const the values for that variables are zero. The array will be filled as h[i *ndim + j] - */ - virtual bool GetHessianMatrix(double * hMat) const { + */ + virtual bool GetHessianMatrix(double * hMat) const { MATH_UNUSED(hMat); - return false; + return false; } - ///return status of covariance matrix + ///return status of covariance matrix /// using Minuit convention {0 not calculated 1 approximated 2 made pos def , 3 accurate} /// Minimizer who implements covariance matrix calculation will re-implement the method - virtual int CovMatrixStatus() const { - return 0; + virtual int CovMatrixStatus() const { + return 0; } /** return correlation coefficient between variable i and j. If the variable is fixed or const the return value is zero */ - virtual double Correlation(unsigned int i, unsigned int j ) const { + virtual double Correlation(unsigned int i, unsigned int j ) const { double tmp = CovMatrix(i,i) * CovMatrix(j,j); - return ( tmp < 0) ? 0 : CovMatrix(i,j) / std::sqrt( tmp ); + return ( tmp < 0) ? 0 : CovMatrix(i,j) / std::sqrt( tmp ); } /** return global correlation coefficient for variable i - This is a number between zero and one which gives - the correlation between the i-th parameter and that linear combination of all + This is a number between zero and one which gives + the correlation between the i-th parameter and that linear combination of all other parameters which is most strongly correlated with i. - Minimizer must overload method if implemented + Minimizer must overload method if implemented */ virtual double GlobalCC(unsigned int ivar) const { MATH_UNUSED(ivar); - return -1; + return -1; } /** - minos error for variable i, return false if Minos failed or not supported + minos error for variable i, return false if Minos failed or not supported and the lower and upper errors are returned in errLow and errUp An extra flag specifies if only the lower (option=-1) or the upper (option=+1) error calculation is run (This feature is not yet implemented) */ - virtual bool GetMinosError(unsigned int ivar , double & errLow, double & errUp, int option = 0) { - MATH_ERROR_MSG("Minimizer::GetMinosError","Minos Error not implemented"); - MATH_UNUSED(ivar); MATH_UNUSED(errLow); MATH_UNUSED(errUp); MATH_UNUSED(option); - return false; - } + virtual bool GetMinosError(unsigned int ivar , double & errLow, double & errUp, int option = 0) { + MATH_ERROR_MSG("Minimizer::GetMinosError","Minos Error not implemented"); + MATH_UNUSED(ivar); MATH_UNUSED(errLow); MATH_UNUSED(errUp); MATH_UNUSED(option); + return false; + } /** perform a full calculation of the Hessian matrix for error calculation */ - virtual bool Hesse() { - MATH_ERROR_MSG("Minimizer::Hesse","Hesse not implemented"); - return false; + virtual bool Hesse() { + MATH_ERROR_MSG("Minimizer::Hesse","Hesse not implemented"); + return false; } /** - scan function minimum for variable i. Variable and function must be set before using Scan + scan function minimum for variable i. Variable and function must be set before using Scan Return false if an error or if minimizer does not support this functionality */ - virtual bool Scan(unsigned int ivar , unsigned int & nstep , double * x , double * y , + virtual bool Scan(unsigned int ivar , unsigned int & nstep , double * x , double * y , double xmin = 0, double xmax = 0) { - MATH_ERROR_MSG("Minimizer::Scan","Scan not implemented"); - MATH_UNUSED(ivar); MATH_UNUSED(nstep); MATH_UNUSED(x); MATH_UNUSED(y); + MATH_ERROR_MSG("Minimizer::Scan","Scan not implemented"); + MATH_UNUSED(ivar); MATH_UNUSED(nstep); MATH_UNUSED(x); MATH_UNUSED(y); MATH_UNUSED(xmin); MATH_UNUSED(xmax); - return false; + return false; } /** find the contour points (xi, xj) of the function for parameter ivar and jvar around the minimum The contour will be find for value of the function = Min + ErrorUp(); */ - virtual bool Contour(unsigned int ivar , unsigned int jvar, unsigned int & npoints, - double * xi , double * xj ) { - MATH_ERROR_MSG("Minimizer::Contour","Contour not implemented"); - MATH_UNUSED(ivar); MATH_UNUSED(jvar); MATH_UNUSED(npoints); + virtual bool Contour(unsigned int ivar , unsigned int jvar, unsigned int & npoints, + double * xi , double * xj ) { + MATH_ERROR_MSG("Minimizer::Contour","Contour not implemented"); + MATH_UNUSED(ivar); MATH_UNUSED(jvar); MATH_UNUSED(npoints); MATH_UNUSED(xi); MATH_UNUSED(xj); - return false; + return false; } /// return reference to the objective function - ///virtual const ROOT::Math::IGenFunction & Function() const = 0; + ///virtual const ROOT::Math::IGenFunction & Function() const = 0; /// print the result according to set level (implemented for TMinuit for mantaining Minuit-style printing) virtual void PrintResults() {} /// get name of variables (override if minimizer support storing of variable names) /// return an empty string if variable is not found - virtual std::string VariableName(unsigned int ivar) const { + virtual std::string VariableName(unsigned int ivar) const { MATH_UNUSED(ivar); - return std::string(); // return empty string - } + return std::string(); // return empty string + } /// get index of variable given a variable given a name /// return -1 if variable is not found virtual int VariableIndex(const std::string & name) const { - MATH_ERROR_MSG("Minimizer::VariableIndex","Getting variable index from name not implemented"); + MATH_ERROR_MSG("Minimizer::VariableIndex","Getting variable index from name not implemented"); MATH_UNUSED(name); - return -1; + return -1; } - + /** minimizer configuration parameters **/ /// set print level int PrintLevel() const { return fOptions.PrintLevel(); } /// max number of function calls - unsigned int MaxFunctionCalls() const { return fOptions.MaxFunctionCalls(); } + unsigned int MaxFunctionCalls() const { return fOptions.MaxFunctionCalls(); } /// max iterations - unsigned int MaxIterations() const { return fOptions.MaxIterations(); } + unsigned int MaxIterations() const { return fOptions.MaxIterations(); } - /// absolute tolerance + /// absolute tolerance double Tolerance() const { return fOptions.Tolerance(); } /// precision of minimizer in the evaluation of the objective function /// ( a value <=0 corresponds to the let the minimizer choose its default one) double Precision() const { return fOptions.Precision(); } - - /// strategy + + /// strategy int Strategy() const { return fOptions.Strategy(); } - /// status code of minimizer - int Status() const { return fStatus; } + /// status code of minimizer + int Status() const { return fStatus; } /// return the statistical scale used for calculate the error /// is typically 1 for Chi2 and 0.5 for likelihood minimization - double ErrorDef() const { return fOptions.ErrorDef(); } + double ErrorDef() const { return fOptions.ErrorDef(); } ///return true if Minimizer has performed a detailed error validation (e.g. run Hesse for Minuit) bool IsValidError() const { return fValidError; } /// retrieve the minimizer options (implement derived class if needed) - virtual MinimizerOptions Options() const { + virtual MinimizerOptions Options() const { return fOptions; } /// set print level void SetPrintLevel(int level) { fOptions.SetPrintLevel(level); } - ///set maximum of function calls + ///set maximum of function calls void SetMaxFunctionCalls(unsigned int maxfcn) { if (maxfcn > 0) fOptions.SetMaxFunctionCalls(maxfcn); } - /// set maximum iterations (one iteration can have many function calls) - void SetMaxIterations(unsigned int maxiter) { if (maxiter > 0) fOptions.SetMaxIterations(maxiter); } + /// set maximum iterations (one iteration can have many function calls) + void SetMaxIterations(unsigned int maxiter) { if (maxiter > 0) fOptions.SetMaxIterations(maxiter); } /// set the tolerance void SetTolerance(double tol) { fOptions.SetTolerance(tol); } - /// set in the minimizer the objective function evaluation precision + /// set in the minimizer the objective function evaluation precision /// ( a value <=0 means the minimizer will choose its optimal value automatically, i.e. default case) void SetPrecision(double prec) { fOptions.SetPrecision(prec); } - ///set the strategy - void SetStrategy(int strategyLevel) { fOptions.SetStrategy(strategyLevel); } + ///set the strategy + void SetStrategy(int strategyLevel) { fOptions.SetStrategy(strategyLevel); } /// set scale for calculating the errors void SetErrorDef(double up) { fOptions.SetErrorDef(up); } /// flag to check if minimizer needs to perform accurate error analysis (e.g. run Hesse for Minuit) - void SetValidError(bool on) { fValidError = on; } + void SetValidError(bool on) { fValidError = on; } /// set all options in one go void SetOptions(const MinimizerOptions & opt) { @@ -485,19 +484,19 @@ public: fOptions.ResetToDefaultOptions(); } -protected: +protected: + +//private: -//private: + // keep protected to be accessible by the derived classes - // keep protected to be accessible by the derived classes - bool fValidError; // flag to control if errors have been validated (Hesse has been run in case of Minuit) MinimizerOptions fOptions; // minimizer options - int fStatus; // status of minimizer -}; + int fStatus; // status of minimizer +}; } // end namespace Math diff --git a/ThirdParty/RootMinimizers/inc/Math/MinimizerVariableTransformation.h b/ThirdParty/RootMinimizers/inc/Math/MinimizerVariableTransformation.h index a253fa6541663d1a05802f25849878f999f6e919..7e00c4c7d27a26efececf5a17b4e95ccb1a46782 100644 --- a/ThirdParty/RootMinimizers/inc/Math/MinimizerVariableTransformation.h +++ b/ThirdParty/RootMinimizers/inc/Math/MinimizerVariableTransformation.h @@ -6,23 +6,23 @@ #ifndef ROOT_Math_MinimizerVariableTransformation #define ROOT_Math_MinimizerVariableTransformation -namespace ROOT { +namespace ROOT { - namespace Math { + namespace Math { -/** - Base class for MinimizerVariable transformations defining the functions to deal +/** + Base class for MinimizerVariable transformations defining the functions to deal with bounded parameters @ingroup MultiMin -*/ +*/ class MinimizerVariableTransformation { -public: +public: virtual ~MinimizerVariableTransformation() {} - + virtual double Int2ext(double value, double lower, double upper) const = 0; virtual double Ext2int(double value, double lower, double upper) const = 0; virtual double DInt2Ext(double value, double lower, double upper) const = 0; @@ -30,7 +30,7 @@ public: }; -/** +/** Sin Transformation class for dealing with double bounded variables @ingroup MultiMin @@ -38,25 +38,25 @@ public: class SinVariableTransformation : public MinimizerVariableTransformation { public: - + virtual ~SinVariableTransformation() {} double Int2ext(double value, double lower, double upper) const; double Ext2int(double value, double lower, double upper) const; double DInt2Ext(double value, double lower, double upper) const; -private: +private: - -}; -/** +}; + +/** Sqrt Transformation class for dealing with lower bounded variables @ingroup MultiMin */ -class SqrtLowVariableTransformation : public MinimizerVariableTransformation { -public: +class SqrtLowVariableTransformation : public MinimizerVariableTransformation { +public: virtual ~SqrtLowVariableTransformation() {} @@ -66,13 +66,13 @@ public: }; -/** +/** Sqrt Transformation class for dealing with upper bounded variables @ingroup MultiMin */ -class SqrtUpVariableTransformation : public MinimizerVariableTransformation { -public: +class SqrtUpVariableTransformation : public MinimizerVariableTransformation { +public: virtual ~SqrtUpVariableTransformation() {} diff --git a/ThirdParty/RootMinimizers/inc/Math/MultiNumGradFunction.h b/ThirdParty/RootMinimizers/inc/Math/MultiNumGradFunction.h index 54af24d6c6e74faf324ef20206f14e6ca4a0a071..d5774657527b46a19f4bd6f75a440fa261dc2e9c 100644 --- a/ThirdParty/RootMinimizers/inc/Math/MultiNumGradFunction.h +++ b/ThirdParty/RootMinimizers/inc/Math/MultiNumGradFunction.h @@ -37,42 +37,42 @@ #endif -namespace ROOT { +namespace ROOT { - namespace Math { + namespace Math { -/** +/** MultiNumGradFunction class to wrap a normal function in a - gradient function using numerical gradient calculation + gradient function using numerical gradient calculation provided by the class Derivator (based on GSL numerical derivation) @ingroup MultiMin -*/ -class MultiNumGradFunction : public IMultiGradFunction { +*/ +class MultiNumGradFunction : public IMultiGradFunction { -public: +public: - /** + /** Constructor from a IMultiGenFunction interface - */ - MultiNumGradFunction (const IMultiGenFunction & f) : - fFunc(&f), + */ + MultiNumGradFunction (const IMultiGenFunction & f) : + fFunc(&f), fDim(f.NDim() ), fNCalls(0), fOwner(false) {} - /** + /** Constructor from a generic function (pointer or reference) and number of dimension implementiong operator () (double * x) - */ + */ - template<class FuncType> - MultiNumGradFunction (FuncType f, int n) : - fDim( n ), + template<class FuncType> + MultiNumGradFunction (FuncType f, int n) : + fDim( n ), fNCalls(0), fOwner(true) { @@ -80,27 +80,27 @@ public: fFunc = new ROOT::Math::WrappedMultiFunction<FuncType> (f, n); } - /** + /** Destructor (no operations) - */ + */ ~MultiNumGradFunction () { - if (fOwner) delete fFunc; - } + if (fOwner) delete fFunc; + } - // method inheritaed from IFunction interface + // method inheritaed from IFunction interface - unsigned int NDim() const { return fDim; } + unsigned int NDim() const { return fDim; } unsigned int NCalls() const { return fNCalls; } - IMultiGenFunction * Clone() const { - if (!fOwner) - return new MultiNumGradFunction(*fFunc); - else { + IMultiGenFunction * Clone() const { + if (!fOwner) + return new MultiNumGradFunction(*fFunc); + else { // we need to copy the pointer to the wrapped function MultiNumGradFunction * f = new MultiNumGradFunction(*(fFunc->Clone()) ); - f->fOwner = true; + f->fOwner = true; return f; } } @@ -108,34 +108,34 @@ public: // set ownership void SetOwnership(bool on = true) { fOwner = on; } - /// precision value used for calculating the derivative step-size + /// precision value used for calculating the derivative step-size /// h = eps * |x|. The default is 0.001, give a smaller in case function chanes rapidly - static void SetDerivPrecision(double eps); + static void SetDerivPrecision(double eps); - /// get precision value used for calculating the derivative step-size + /// get precision value used for calculating the derivative step-size static double GetDerivPrecision(); -private: +private: - double DoEval(const double * x) const { + double DoEval(const double * x) const { fNCalls++; - return (*fFunc)(x); + return (*fFunc)(x); } - // calculate derivative using mathcore derivator + // calculate derivative using mathcore derivator double DoDerivative (const double * x, unsigned int icoord ) const; // adapat internal function type to IMultiGenFunction needed by derivative calculation - const IMultiGenFunction * fFunc; - unsigned int fDim; + const IMultiGenFunction * fFunc; + unsigned int fDim; mutable unsigned int fNCalls; - bool fOwner; + bool fOwner; static double fgEps; // epsilon used in derivative calculation h ~ eps |x| -}; +}; } // end namespace Math diff --git a/ThirdParty/RootMinimizers/inc/Math/OneDimFunctionAdapter.h b/ThirdParty/RootMinimizers/inc/Math/OneDimFunctionAdapter.h index f060f7d7a1d11dabbbb7f4509bdded70d8b4a78a..e4674552e15697c155550465c85d65152f6a8922 100644 --- a/ThirdParty/RootMinimizers/inc/Math/OneDimFunctionAdapter.h +++ b/ThirdParty/RootMinimizers/inc/Math/OneDimFunctionAdapter.h @@ -20,105 +20,105 @@ #include "Math/IParamFunction.h" #endif -#include <cassert> +#include <cassert> -namespace ROOT { +namespace ROOT { -namespace Math { +namespace Math { -// struct using for evaluating the function +// struct using for evaluating the function template<class MultiFuncType> -struct EvaluatorOneDim { - // evaluate function (in general case no param) - static double F (MultiFuncType f, const double * x, const double * = 0 ) { +struct EvaluatorOneDim { + // evaluate function (in general case no param) + static double F (MultiFuncType f, const double * x, const double * = 0 ) { return f( x ); } }; // specialized for param functions template<> -struct EvaluatorOneDim< const ROOT::Math::IParamMultiFunction &> { - static double F ( const ROOT::Math::IParamMultiFunction & f, const double * x, const double * p = 0 ) { +struct EvaluatorOneDim< const ROOT::Math::IParamMultiFunction &> { + static double F ( const ROOT::Math::IParamMultiFunction & f, const double * x, const double * p = 0 ) { return f( x, p ); } }; -/** - OneDimMultiFunctionAdapter class to wrap a multidimensional function in - one dimensional one. +/** + OneDimMultiFunctionAdapter class to wrap a multidimensional function in + one dimensional one. Given a f(x1,x2,x3,....xn) transforms in a f( x_i) given the coordinate intex i and the vector x[] - of the coordinates. - It provides the possibility to copy and own the data array of the coordinates or to maintain internally a pointer to an external array - for being more efficient. In this last case the user must garantee the life of the given passed pointer + of the coordinates. + It provides the possibility to copy and own the data array of the coordinates or to maintain internally a pointer to an external array + for being more efficient. In this last case the user must garantee the life of the given passed pointer @ingroup GenFunc - -*/ -template <class MultiFuncType = const ROOT::Math::IMultiGenFunction &> + +*/ +template <class MultiFuncType = const ROOT::Math::IMultiGenFunction &> class OneDimMultiFunctionAdapter : public ROOT::Math::IGenFunction { -public: +public: + - - /** - Constructor from the function object , pointer to an external array of x values + /** + Constructor from the function object , pointer to an external array of x values and coordinate we want to adapt - */ - OneDimMultiFunctionAdapter (MultiFuncType f, const double * x, unsigned int icoord =0, const double * p = 0 ) : - fFunc(f), - fX( const_cast<double *>(x) ), // wee need to modify x but then we restore it as before + */ + OneDimMultiFunctionAdapter (MultiFuncType f, const double * x, unsigned int icoord =0, const double * p = 0 ) : + fFunc(f), + fX( const_cast<double *>(x) ), // wee need to modify x but then we restore it as before fParams(p), - fCoord(icoord), - fDim(0), + fCoord(icoord), + fDim(0), fOwn(false) { - assert(fX != 0); - } - /** - Constructor from the function object , dimension of the function and - and coordinate we want to adapt. - The coordinate cached vector is created inside and eventually the values must be passed + assert(fX != 0); + } + /** + Constructor from the function object , dimension of the function and + and coordinate we want to adapt. + The coordinate cached vector is created inside and eventually the values must be passed later with the SetX which will copy them - */ - OneDimMultiFunctionAdapter (MultiFuncType f, unsigned int dim = 1, unsigned int icoord =0, const double * p = 0 ) : - fFunc(f), - fX(0 ), + */ + OneDimMultiFunctionAdapter (MultiFuncType f, unsigned int dim = 1, unsigned int icoord =0, const double * p = 0 ) : + fFunc(f), + fX(0 ), fParams(p), - fCoord(icoord), + fCoord(icoord), fDim(dim), fOwn(true) { - fX = new double[dim]; - } + fX = new double[dim]; + } - /** + /** Destructor (no operations) - */ - virtual ~OneDimMultiFunctionAdapter () { if (fOwn && fX) delete [] fX; } + */ + virtual ~OneDimMultiFunctionAdapter () { if (fOwn && fX) delete [] fX; } /** clone */ - virtual OneDimMultiFunctionAdapter * Clone( ) const { - if (fOwn) { - OneDimMultiFunctionAdapter * f = new OneDimMultiFunctionAdapter( fFunc, fDim, fCoord, fParams); - std::copy(fX, fX+fDim, f->fX); - return f; + virtual OneDimMultiFunctionAdapter * Clone( ) const { + if (fOwn) { + OneDimMultiFunctionAdapter * f = new OneDimMultiFunctionAdapter( fFunc, fDim, fCoord, fParams); + std::copy(fX, fX+fDim, f->fX); + return f; } - else - return new OneDimMultiFunctionAdapter( fFunc, fX, fCoord, fParams); + else + return new OneDimMultiFunctionAdapter( fFunc, fX, fCoord, fParams); } -public: +public: - /** - Set X values in case vector is own, iterator size must match previous + /** + Set X values in case vector is own, iterator size must match previous set dimension - */ + */ template<class Iterator> - void SetX(Iterator begin, Iterator end) { + void SetX(Iterator begin, Iterator end) { if (fOwn) std::copy(begin, end, fX); } @@ -126,16 +126,16 @@ public: /** set pointer without copying the values */ - void SetX(double * x) { - if (!fOwn) fX = x; + void SetX(double * x) { + if (!fOwn) fX = x; } - /** - set values + /** + set values */ - void SetX(const double * x) { + void SetX(const double * x) { if (fOwn) std::copy(x, x+fDim, fX); - else + else SetX( const_cast<double *>(x) ); // wee need to modify x but then we restore it as before } @@ -143,134 +143,134 @@ public: void SetCoord(int icoord) { fCoord=icoord;} // copy constructor - OneDimMultiFunctionAdapter( const OneDimMultiFunctionAdapter & rhs) : - fFunc(rhs.fFunc), + OneDimMultiFunctionAdapter( const OneDimMultiFunctionAdapter & rhs) : + fFunc(rhs.fFunc), fParams(rhs.fParams), fCoord(rhs.fCoord), - fDim(rhs.fDim), + fDim(rhs.fDim), fOwn(rhs.fOwn) - { - if (fOwn) { - fX = new double[fDim]; + { + if (fOwn) { + fX = new double[fDim]; std::copy( rhs.fX, rhs.fX+fDim, fX); - } - else fX = rhs.fX; + } + else fX = rhs.fX; } -private: +private: - // dummy assignment (should never be called and clone must be used) - OneDimMultiFunctionAdapter & operator= ( const OneDimMultiFunctionAdapter & rhs) { + // dummy assignment (should never be called and clone must be used) + OneDimMultiFunctionAdapter & operator= ( const OneDimMultiFunctionAdapter & rhs) { if (this == &rhs) return *this; - assert(false); + assert(false); } /** - evaluate function at the values x[] given in the constructor and - as function of the coordinate fCoord. + evaluate function at the values x[] given in the constructor and + as function of the coordinate fCoord. */ double DoEval(double x) const { - if (fOwn) { - fX[fCoord] = x; + if (fOwn) { + fX[fCoord] = x; return EvaluatorOneDim<MultiFuncType>::F( fFunc, fX, fParams ); } - else { + else { // case vector fX represents useful values needed later // need to modify fX and restore afterwards the original values double xprev = fX[fCoord]; // keep original value to restore in fX - fX[fCoord] = x; + fX[fCoord] = x; double y = EvaluatorOneDim<MultiFuncType>::F( fFunc, fX, fParams ); // restore original values - fX[fCoord] = xprev; - return y; + fX[fCoord] = xprev; + return y; } } -private: +private: - MultiFuncType fFunc; + MultiFuncType fFunc; mutable double * fX; const double * fParams; unsigned int fCoord; - unsigned int fDim; + unsigned int fDim; bool fOwn; -}; +}; -/** - OneDimParamFunctionAdapter class to wrap a multi-dim parameteric function in - one dimensional one. +/** + OneDimParamFunctionAdapter class to wrap a multi-dim parameteric function in + one dimensional one. Given a f(x[],p1,...pn) transforms in a f( p_i) given the param index i and the vectors x[] and p[] of the coordinates and parameters - It has to be used carefully, since for efficiency reason it does not copy the parameter object - but re-uses the given pointer for the p[] vector. + It has to be used carefully, since for efficiency reason it does not copy the parameter object + but re-uses the given pointer for the p[] vector. The ParamFuncType reference by default is not const because the operator()(x,p) is not a const method @ingroup GenFunc - -*/ -template <class ParamFuncType = ROOT::Math::IParamMultiFunction &> + +*/ +template <class ParamFuncType = ROOT::Math::IParamMultiFunction &> class OneDimParamFunctionAdapter : public ROOT::Math::IGenFunction { -public: +public: + - - /** + /** Constructor from the function object , x value and coordinate we want to adapt - */ - OneDimParamFunctionAdapter (ParamFuncType f, const double * x, const double * p, unsigned int ipar =0 ) : - fFunc(f), - fX(x ), - fParams(p), + */ + OneDimParamFunctionAdapter (ParamFuncType f, const double * x, const double * p, unsigned int ipar =0 ) : + fFunc(f), + fX(x ), + fParams(p), fIpar(ipar) { - assert(fX != 0); - assert(fParams != 0); - } + assert(fX != 0); + assert(fParams != 0); + } - /** + /** Destructor (no operations) - */ - ~OneDimParamFunctionAdapter () {} + */ + ~OneDimParamFunctionAdapter () {} /** clone */ - virtual OneDimParamFunctionAdapter * Clone( ) const { + virtual OneDimParamFunctionAdapter * Clone( ) const { return new OneDimParamFunctionAdapter(fFunc, fX, fParams, fIpar); } // can use default copy constructor -private: +private: /** - evaluate function at the values x[] given in the constructor and - as function of the coordinate fCoord. + evaluate function at the values x[] given in the constructor and + as function of the coordinate fCoord. */ double DoEval(double x) const { // HACK: use const_cast to modify the function values x[] and restore afterwards the original ones - double * p = const_cast<double *>(fParams); + double * p = const_cast<double *>(fParams); double pprev = fParams[fIpar]; // keep original value to restore in fX - p[fIpar] = x; + p[fIpar] = x; double y = fFunc( fX, p ); - p[fIpar] = pprev; - return y; + p[fIpar] = pprev; + return y; } -private: +private: - ParamFuncType fFunc; - const double * fX; - const double * fParams; + ParamFuncType fFunc; + const double * fX; + const double * fParams; unsigned int fIpar; -}; +}; diff --git a/ThirdParty/RootMinimizers/inc/Math/WrappedFunction.h b/ThirdParty/RootMinimizers/inc/Math/WrappedFunction.h index 6652cadb972fe84d80225167243fe53712bf2506..4c48d645e60233dd8713ddce51acecc5a40f6967 100644 --- a/ThirdParty/RootMinimizers/inc/Math/WrappedFunction.h +++ b/ThirdParty/RootMinimizers/inc/Math/WrappedFunction.h @@ -1,5 +1,5 @@ // @(#)root/mathcore:$Id$ -// Authors: L. Moneta, A. Zsenei 08/2005 +// Authors: L. Moneta, A. Zsenei 08/2005 /********************************************************************** * * @@ -36,19 +36,19 @@ namespace Math { -struct NullTypeFunc1D {}; +struct NullTypeFunc1D {}; typedef double(*FreeFunctionPtr)(double); -typedef double(*FreeMultiFunctionPtr)(const double*); +typedef double(*FreeMultiFunctionPtr)(const double*); /** - Template class to wrap any C++ callable object which takes one argument + Template class to wrap any C++ callable object which takes one argument i.e. implementing operator() (double x) in a One-dimensional function interface. It provides a ROOT::Math::IGenFunction-like signature - Note: If you want to wrap just the reference (to avoid copying) you need to use - Func& or const Func & as template parameter. The former should be used when the + Note: If you want to wrap just the reference (to avoid copying) you need to use + Func& or const Func & as template parameter. The former should be used when the operator() is not a const method of Func @ingroup GenFunc @@ -63,8 +63,8 @@ class WrappedFunction : public IGenFunction { /** construct from the pointer to the object and the member function */ - WrappedFunction( Func f ) : - fFunc( f ) + WrappedFunction( Func f ) : + fFunc( f ) { /* no op */ } // use default copy contructor and assignment operator @@ -73,7 +73,7 @@ class WrappedFunction : public IGenFunction { WrappedFunction * Clone() const { return new WrappedFunction(fFunc); } - + // virtual ~WrappedFunction() { /**/ } private: @@ -83,21 +83,21 @@ private: } - Func fFunc; + Func fFunc; }; // WrappedFunction /** - Template class to wrap any member function of a class + Template class to wrap any member function of a class taking a double and returning a double in a 1D function interface - For example, if you have a class like: - struct X { - double Eval(double x); + For example, if you have a class like: + struct X { + double Eval(double x); }; - you can wrapped in the following way: - WrappedMemFunction<X, double ( X::* ) (double) > f; + you can wrapped in the following way: + WrappedMemFunction<X, double ( X::* ) (double) > f; @ingroup GenFunc @@ -113,9 +113,9 @@ class WrappedMemFunction : public IGenFunction { /** construct from the pointer to the object and the member function */ - WrappedMemFunction( FuncObj & obj, MemFuncPtr memFn ) : - fObj(&obj), - fMemFunc( memFn ) + WrappedMemFunction( FuncObj & obj, MemFuncPtr memFn ) : + fObj(&obj), + fMemFunc( memFn ) { /* no op */ } // use default copy contructor and assignment operator @@ -124,7 +124,7 @@ class WrappedMemFunction : public IGenFunction { WrappedMemFunction * Clone() const { return new WrappedMemFunction(*fObj,fMemFunc); } - + private: @@ -133,7 +133,7 @@ private: } - FuncObj * fObj; + FuncObj * fObj; MemFuncPtr fMemFunc; @@ -141,12 +141,12 @@ private: /** - Template class to wrap any C++ callable object + Template class to wrap any C++ callable object implementing operator() (const double * x) in a multi-dimensional function interface. It provides a ROOT::Math::IGenMultiFunction-like signature - Note: If you want to wrap just the reference (to avoid copying) you need to use - Func& or const Func & as template parameter. The former should be used when the + Note: If you want to wrap just the reference (to avoid copying) you need to use + Func& or const Func & as template parameter. The former should be used when the operator() is not a const method of Func @ingroup GenFunc @@ -161,8 +161,8 @@ class WrappedMultiFunction : public IMultiGenFunction { /** construct from the pointer to the object and the member function */ - WrappedMultiFunction( Func f , unsigned int dim = 1) : - fFunc( f ), + WrappedMultiFunction( Func f , unsigned int dim = 1) : + fFunc( f ), fDim( dim) { /* no op */ } @@ -174,7 +174,7 @@ class WrappedMultiFunction : public IMultiGenFunction { } unsigned int NDim() const { return fDim; } - + // virtual ~WrappedFunction() { /**/ } private: @@ -184,8 +184,8 @@ private: } - Func fFunc; - unsigned int fDim; + Func fFunc; + unsigned int fDim; }; // WrappedMultiFunction @@ -200,8 +200,8 @@ class WrappedMemMultiFunction : public IMultiGenFunction { /** construct from the pointer to the object and the member function */ - WrappedMemMultiFunction( FuncObj & obj, MemFuncPtr memFn, unsigned int dim = 1 ) : - fObj(&obj), + WrappedMemMultiFunction( FuncObj & obj, MemFuncPtr memFn, unsigned int dim = 1 ) : + fObj(&obj), fMemFunc( memFn ), fDim(dim) { /* no op */ } @@ -212,7 +212,7 @@ class WrappedMemMultiFunction : public IMultiGenFunction { WrappedMemMultiFunction * Clone() const { return new WrappedMemMultiFunction(*fObj,fMemFunc,fDim); } - + unsigned int NDim() const { return fDim; } @@ -223,7 +223,7 @@ private: } - FuncObj * fObj; + FuncObj * fObj; MemFuncPtr fMemFunc; unsigned int fDim; diff --git a/ThirdParty/RootMinimizers/inc/Math/WrappedParamFunction.h b/ThirdParty/RootMinimizers/inc/Math/WrappedParamFunction.h index c01320d4d083df339ee721b44ec75e66e2f6fc2c..1446f4ef2097e01e8d37a596a317a77ea7cb15e0 100644 --- a/ThirdParty/RootMinimizers/inc/Math/WrappedParamFunction.h +++ b/ThirdParty/RootMinimizers/inc/Math/WrappedParamFunction.h @@ -211,8 +211,6 @@ private: /// evaluate the function (re-implement for being more efficient) double DoEval(const double * x) const { - unsigned int npar = NPar(); - // std::cout << this << fDim << " x : "; // std::ostream_iterator<double> oix(std::cout," , "); // std::copy(x, x+fDim, oix); @@ -223,7 +221,7 @@ private: for (unsigned int i = 0; i < fDim; ++i) { unsigned int j = fVarIndices[i]; - assert ( j < npar + fDim); + assert ( j < NPar() + fDim); fX[ j ] = x[i]; } // std::cout << "X : ("; diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/ABObj.h b/ThirdParty/RootMinimizers/inc/Minuit2/ABObj.h index 4e8667425409fb10692d58b560513bec82b60e0d..38ac37d15904a624c3d229cf7124f2e62661554f 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/ABObj.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/ABObj.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -35,7 +35,7 @@ private: template<class a, class b, class c> ABObj& operator=(const ABObj<a,b,c>&) {return *this;} - + public: ABObj(const M& obj) : fObject(obj), fFactor(T(1.)) {} @@ -44,11 +44,11 @@ public: ~ABObj() {} - ABObj(const ABObj& obj) : + ABObj(const ABObj& obj) : fObject(obj.fObject), fFactor(obj.fFactor) {} template<class b, class c> - ABObj(const ABObj<mtype,b,c>& obj) : + ABObj(const ABObj<mtype,b,c>& obj) : fObject(M(obj.Obj() )), fFactor(T(obj.f() )) {} const M& Obj() const {return fObject;} @@ -71,7 +71,7 @@ public: private: ABObj& operator=(const ABObj&) {return *this;} - + public: ABObj(const LAVector& obj) : fObject(obj), fFactor(double(1.)) {} @@ -80,13 +80,13 @@ public: ~ABObj() {} - // remove copy constructure to Fix a problem in AIX + // remove copy constructure to Fix a problem in AIX // should be able to use the compiler generated one -// ABObj(const ABObj& obj) : +// ABObj(const ABObj& obj) : // fObject(obj.fObject), fFactor(obj.fFactor) {} template<class c> - ABObj(const ABObj<vec,LAVector,c>& obj) : + ABObj(const ABObj<vec,LAVector,c>& obj) : fObject(obj.fObject), fFactor(double(obj.fFactor)) {} const LAVector& Obj() const {return fObject;} @@ -109,7 +109,7 @@ public: private: ABObj& operator=(const ABObj&) {return *this;} - + public: ABObj(const LASymMatrix& obj) : fObject(obj), fFactor(double(1.)) {} @@ -118,11 +118,11 @@ public: ~ABObj() {} - ABObj(const ABObj& obj) : + ABObj(const ABObj& obj) : fObject(obj.fObject), fFactor(obj.fFactor) {} template<class c> - ABObj(const ABObj<vec,LASymMatrix,c>& obj) : + ABObj(const ABObj<vec,LASymMatrix,c>& obj) : fObject(obj.fObject), fFactor(double(obj.fFactor)) {} const LASymMatrix& Obj() const {return fObject;} diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/ABProd.h b/ThirdParty/RootMinimizers/inc/Minuit2/ABProd.h index 2aa603c51745eababc6ad780766c76c8ada15fb2..5669dfe80e1bce5a4058335c8c8ed8e05e22ebc8 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/ABProd.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/ABProd.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -28,7 +28,7 @@ private: template<class MI1, class MI2> ABProd& operator=(const ABProd<MI1,MI2>&) {return *this;} - + public: ABProd(const M1& a, const M2& b): fA(a), fB(b) {} @@ -42,7 +42,7 @@ public: const M1& A() const {return fA;} const M2& B() const {return fB;} - + private: M1 fA; diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/ABSum.h b/ThirdParty/RootMinimizers/inc/Minuit2/ABSum.h index 39868cf130f265c9aacd950aad9e068887f64b86..fa5a1acf28afc577f21fdd50e3d2d79b0d688a5b 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/ABSum.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/ABSum.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/ABTypes.h b/ThirdParty/RootMinimizers/inc/Minuit2/ABTypes.h index fc4b573112c1177460a0227629f304ce4b7eac70..a7228cf023f4c62497b9a5722d24b13151b46235 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/ABTypes.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/ABTypes.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/AnalyticalGradientCalculator.h b/ThirdParty/RootMinimizers/inc/Minuit2/AnalyticalGradientCalculator.h index 494d7a8640fb84d96327ae6ec8f7f652b8959f21..888dd8f9de735ce70f9160c96f776631e9b75d88 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/AnalyticalGradientCalculator.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/AnalyticalGradientCalculator.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -28,7 +28,7 @@ public: ~AnalyticalGradientCalculator() {} - + virtual FunctionGradient operator()(const MinimumParameters&) const; virtual FunctionGradient operator()(const MinimumParameters&, diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/BasicFunctionGradient.h b/ThirdParty/RootMinimizers/inc/Minuit2/BasicFunctionGradient.h index 11e454ca33abffb479b1676757766bdf206f5824..318262455d5e92a56c8a49e3dc63d15a1771b19a 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/BasicFunctionGradient.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/BasicFunctionGradient.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -26,23 +26,23 @@ class BasicFunctionGradient { private: public: - + explicit BasicFunctionGradient(unsigned int n) : fGradient(MnAlgebraicVector(n)), fG2ndDerivative(MnAlgebraicVector(n)), - fGStepSize(MnAlgebraicVector(n)), fValid(false), + fGStepSize(MnAlgebraicVector(n)), fValid(false), fAnalytical(false) {} - - explicit BasicFunctionGradient(const MnAlgebraicVector& grd) : + + explicit BasicFunctionGradient(const MnAlgebraicVector& grd) : fGradient(grd), fG2ndDerivative(MnAlgebraicVector(grd.size())), - fGStepSize(MnAlgebraicVector(grd.size())), fValid(true), + fGStepSize(MnAlgebraicVector(grd.size())), fValid(true), fAnalytical(true) {} - BasicFunctionGradient(const MnAlgebraicVector& grd, const MnAlgebraicVector& g2, const MnAlgebraicVector& gstep) : + BasicFunctionGradient(const MnAlgebraicVector& grd, const MnAlgebraicVector& g2, const MnAlgebraicVector& gstep) : fGradient(grd), fG2ndDerivative(g2), fGStepSize(gstep), fValid(true), fAnalytical(false) {} - + ~BasicFunctionGradient() {} - + BasicFunctionGradient(const BasicFunctionGradient& grad) : fGradient(grad.fGradient), fG2ndDerivative(grad.fG2ndDerivative), fGStepSize(grad.fGStepSize), fValid(grad.fValid) {} BasicFunctionGradient& operator=(const BasicFunctionGradient& grad) { @@ -56,7 +56,7 @@ public: void* operator new(size_t nbytes) { return StackAllocatorHolder::Get().Allocate(nbytes); } - + void operator delete(void* p, size_t /*nbytes */) { StackAllocatorHolder::Get().Deallocate(p); } diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/BasicFunctionMinimum.h b/ThirdParty/RootMinimizers/inc/Minuit2/BasicFunctionMinimum.h index 252f9abb9672e61001daa06f38793f14a900c40f..d43eda2d205be1444cc4030cdf4a2f617f8154d1 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/BasicFunctionMinimum.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/BasicFunctionMinimum.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -26,7 +26,7 @@ namespace ROOT { //extern StackAllocator gStackAllocator; -/** result of the minimization; +/** result of the minimization; both internal and external (MnUserParameterState) representation available For the parameters at the Minimum */ @@ -39,22 +39,22 @@ public: class MnAboveMaxEdm {}; public: - - /// constructor from only MinimumSeed. Minimum is only from seed result not the full minimization + + /// constructor from only MinimumSeed. Minimum is only from seed result not the full minimization BasicFunctionMinimum(const MinimumSeed& seed, double up) : fSeed(seed), fStates(std::vector<MinimumState>(1, MinimumState(seed.Parameters(), seed.Error(), seed.Gradient(), seed.Parameters().Fval(), seed.NFcn()))), fErrorDef(up), fAboveMaxEdm(false), fReachedCallLimit(false), fUserState(MnUserParameterState()) {} - - /// constructor at the end of a successfull minimization from seed and vector of states + + /// constructor at the end of a successfull minimization from seed and vector of states BasicFunctionMinimum(const MinimumSeed& seed, const std::vector<MinimumState>& states, double up) : fSeed(seed), fStates(states), fErrorDef(up), fAboveMaxEdm(false), fReachedCallLimit(false), fUserState(MnUserParameterState()) {} - - /// constructor at the end of a failed minimization due to exceeding function call limit + + /// constructor at the end of a failed minimization due to exceeding function call limit BasicFunctionMinimum(const MinimumSeed& seed, const std::vector<MinimumState>& states, double up, MnReachedCallLimit) : fSeed(seed), fStates(states), fErrorDef(up), fAboveMaxEdm(false), fReachedCallLimit(true), fUserState(MnUserParameterState()) {} - + /// constructor at the end of a failed minimization due to edm above maximum value BasicFunctionMinimum(const MinimumSeed& seed, const std::vector<MinimumState>& states, double up, MnAboveMaxEdm) : fSeed(seed), fStates(states), fErrorDef(up), fAboveMaxEdm(true), fReachedCallLimit(false), fUserState(MnUserParameterState()) {} /// copy constructor BasicFunctionMinimum(const BasicFunctionMinimum& min) : fSeed(min.fSeed), fStates(min.fStates), fErrorDef(min.fErrorDef), fAboveMaxEdm(min.fAboveMaxEdm), fReachedCallLimit(min.fReachedCallLimit), fUserState(min.fUserState) {} - + BasicFunctionMinimum& operator=(const BasicFunctionMinimum& min) { fSeed = min.fSeed; fStates = min.fStates; @@ -70,15 +70,15 @@ public: /// add latest minimization state (for example add Hesse result after Migrad) void Add(const MinimumState& state ) { fStates.push_back(state); - // LM : update also the user state + // LM : update also the user state fUserState = MnUserParameterState(State(), Up(), Seed().Trafo()); - // reset maxedm flag. If new state has edm over max other method must be used + // reset maxedm flag. If new state has edm over max other method must be used fAboveMaxEdm = false; } - ///Add a new state and flag that edm is above maximum + ///Add a new state and flag that edm is above maximum void Add(const MinimumState& state, MnAboveMaxEdm) { - Add(state); + Add(state); fAboveMaxEdm = true; } @@ -87,17 +87,17 @@ public: // user representation of state at Minimum const MnUserParameterState& UserState() const { - if(!fUserState.IsValid()) + if(!fUserState.IsValid()) fUserState = MnUserParameterState(State(), Up(), Seed().Trafo()); return fUserState; } const MnUserParameters& UserParameters() const { - if(!fUserState.IsValid()) + if(!fUserState.IsValid()) fUserState = MnUserParameterState(State(), Up(), Seed().Trafo()); return fUserState.Parameters(); } const MnUserCovariance& UserCovariance() const { - if(!fUserState.IsValid()) + if(!fUserState.IsValid()) fUserState = MnUserParameterState(State(), Up(), Seed().Trafo()); return fUserState.Covariance(); } @@ -105,7 +105,7 @@ public: void* operator new(size_t nbytes) { return StackAllocatorHolder::Get().Allocate(nbytes); } - + void operator delete(void* p, size_t /*nbytes */) { StackAllocatorHolder::Get().Deallocate(p); } @@ -117,8 +117,8 @@ public: const FunctionGradient& Grad() const {return fStates.back().Gradient();} double Fval() const {return fStates.back().Fval();} double Edm() const {return fStates.back().Edm();} - int NFcn() const {return fStates.back().NFcn();} - + int NFcn() const {return fStates.back().NFcn();} + double Up() const {return fErrorDef;} bool IsValid() const { return State().IsValid() && !IsAboveMaxEdm() && !HasReachedCallLimit(); @@ -133,8 +133,8 @@ public: bool IsAboveMaxEdm() const {return fAboveMaxEdm;} bool HasReachedCallLimit() const {return fReachedCallLimit;} - void SetErrorDef( double up) { - fErrorDef = up; + void SetErrorDef( double up) { + fErrorDef = up; // update user state for new valeu of up (scaling of errors) fUserState = MnUserParameterState(State(), up, Seed().Trafo()); } diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/BasicMinimumError.h b/ThirdParty/RootMinimizers/inc/Minuit2/BasicMinimumError.h index 5dbd2bb70cf6dda711e136cd4f4ba5bc1afc576c..e545ef2045f30f0f7a7154832b255523c438489f 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/BasicMinimumError.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/BasicMinimumError.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -30,38 +30,38 @@ namespace ROOT { //extern StackAllocator gStackAllocator; /** - Internal Class containing the error information on the - estimated minimum : + Internal Class containing the error information on the + estimated minimum : Error matrix + dcovar + additional flags for quality and validity checks */ class BasicMinimumError { public: - + class MnNotPosDef {}; class MnMadePosDef {}; class MnHesseFailed {}; class MnInvertFailed {}; public: - - BasicMinimumError(unsigned int n) : + + BasicMinimumError(unsigned int n) : fMatrix(MnAlgebraicSymMatrix(n)), fDCovar(1.), fValid(false), fPosDef(false), fMadePosDef(false), fHesseFailed(false), fInvertFailed(false), fAvailable(false) {} - - BasicMinimumError(const MnAlgebraicSymMatrix& mat, double dcov) : + + BasicMinimumError(const MnAlgebraicSymMatrix& mat, double dcov) : fMatrix(mat), fDCovar(dcov), fValid(true), fPosDef(true), fMadePosDef(false), fHesseFailed(false), fInvertFailed(false), fAvailable(true) {} - - BasicMinimumError(const MnAlgebraicSymMatrix& mat, MnHesseFailed) : + + BasicMinimumError(const MnAlgebraicSymMatrix& mat, MnHesseFailed) : fMatrix(mat), fDCovar(1.), fValid(false), fPosDef(false), fMadePosDef(false), fHesseFailed(true), fInvertFailed(false), fAvailable(true) {} - BasicMinimumError(const MnAlgebraicSymMatrix& mat, MnMadePosDef) : + BasicMinimumError(const MnAlgebraicSymMatrix& mat, MnMadePosDef) : fMatrix(mat), fDCovar(1.), fValid(true), fPosDef(false), fMadePosDef(true), fHesseFailed(false), fInvertFailed(false), fAvailable(true) {} - BasicMinimumError(const MnAlgebraicSymMatrix& mat, MnInvertFailed) : + BasicMinimumError(const MnAlgebraicSymMatrix& mat, MnInvertFailed) : fMatrix(mat), fDCovar(1.), fValid(false), fPosDef(true), fMadePosDef(false), fHesseFailed(false), fInvertFailed(true), fAvailable(true) {} - BasicMinimumError(const MnAlgebraicSymMatrix& mat, MnNotPosDef) : + BasicMinimumError(const MnAlgebraicSymMatrix& mat, MnNotPosDef) : fMatrix(mat), fDCovar(1.), fValid(false), fPosDef(false), fMadePosDef(false), fHesseFailed(false), fInvertFailed(false), fAvailable(true) {} ~BasicMinimumError() {} @@ -83,7 +83,7 @@ public: void* operator new(size_t nbytes) { return StackAllocatorHolder::Get().Allocate(nbytes); } - + void operator delete(void* p, size_t /*nbytes */) { StackAllocatorHolder::Get().Deallocate(p); } diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/BasicMinimumParameters.h b/ThirdParty/RootMinimizers/inc/Minuit2/BasicMinimumParameters.h index 6469257ab95b1671c1514d20e9686af363903e79..ecc424741b47d240e112969a4e944670b26e312c 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/BasicMinimumParameters.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/BasicMinimumParameters.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -26,12 +26,12 @@ class BasicMinimumParameters { public: BasicMinimumParameters(unsigned int n) : fParameters(MnAlgebraicVector(n)), fStepSize(MnAlgebraicVector(n)), fFVal(0.), fValid(false), fHasStep(false) {} - - BasicMinimumParameters(const MnAlgebraicVector& avec, double fval) : + + BasicMinimumParameters(const MnAlgebraicVector& avec, double fval) : fParameters(avec), fStepSize(avec.size()), fFVal(fval), fValid(true), fHasStep(false) {} - + BasicMinimumParameters(const MnAlgebraicVector& avec, const MnAlgebraicVector& dirin, double fval) : fParameters(avec), fStepSize(dirin), fFVal(fval), fValid(true), fHasStep(true) {} - + ~BasicMinimumParameters() {} BasicMinimumParameters(const BasicMinimumParameters& par) : fParameters(par.fParameters), fStepSize(par.fStepSize), fFVal(par.fFVal), fValid(par.fValid), fHasStep(par.fHasStep) {} @@ -40,7 +40,7 @@ public: fParameters = par.fParameters; fStepSize = par.fStepSize; fFVal = par.fFVal; - fValid = par.fValid; + fValid = par.fValid; fHasStep = par.fHasStep; return *this; } @@ -48,7 +48,7 @@ public: void* operator new(size_t nbytes) { return StackAllocatorHolder::Get().Allocate(nbytes); } - + void operator delete(void* p, size_t /*nbytes*/) { StackAllocatorHolder::Get().Deallocate(p); } diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/BasicMinimumSeed.h b/ThirdParty/RootMinimizers/inc/Minuit2/BasicMinimumSeed.h index cbb944edad390fab4d13e35d160dfd15313e1fb8..d810a87fccb08d540109de5f9318549d94048b0b 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/BasicMinimumSeed.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/BasicMinimumSeed.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -28,13 +28,13 @@ namespace ROOT { class BasicMinimumSeed { public: - + BasicMinimumSeed(const MinimumState& state, const MnUserTransformation& trafo) : fState(state), fTrafo(trafo), fValid(true) {} - + ~BasicMinimumSeed() {} BasicMinimumSeed(const BasicMinimumSeed& seed) : fState(seed.fState), fTrafo(seed.fTrafo), fValid(seed.fValid) {} - + BasicMinimumSeed& operator=(const BasicMinimumSeed& seed) { fState = seed.fState; fTrafo = seed.fTrafo; @@ -45,7 +45,7 @@ public: void* operator new(size_t nbytes) { return StackAllocatorHolder::Get().Allocate(nbytes); } - + void operator delete(void* p, size_t /*nbytes*/) { StackAllocatorHolder::Get().Deallocate(p); } diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/BasicMinimumState.h b/ThirdParty/RootMinimizers/inc/Minuit2/BasicMinimumState.h index e79b88994c9055f28d2af688ffd15b908397a8ea..12311e17c5d08fe1c81122d0f5c1777f7f797eba 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/BasicMinimumState.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/BasicMinimumState.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -27,22 +27,22 @@ class BasicMinimumState { public: - BasicMinimumState(unsigned int n) : + BasicMinimumState(unsigned int n) : fParameters(MinimumParameters(n)), fError(MinimumError(n)), fGradient(FunctionGradient(n)), fEDM(0.), fNFcn(0) {} - BasicMinimumState(const MinimumParameters& states, const MinimumError& err, + BasicMinimumState(const MinimumParameters& states, const MinimumError& err, const FunctionGradient& grad, double edm, int nfcn) : fParameters(states), fError(err), fGradient(grad), fEDM(edm), fNFcn(nfcn) {} - + BasicMinimumState(const MinimumParameters& states, double edm, int nfcn) : fParameters(states), fError(MinimumError(states.Vec().size())), fGradient(FunctionGradient(states.Vec().size())), fEDM(edm), fNFcn(nfcn) {} - + ~BasicMinimumState() {} - BasicMinimumState(const BasicMinimumState& state) : + BasicMinimumState(const BasicMinimumState& state) : fParameters(state.fParameters), fError(state.fError), fGradient(state.fGradient), fEDM(state.fEDM), fNFcn(state.fNFcn) {} - + BasicMinimumState& operator=(const BasicMinimumState& state) { - fParameters = state.fParameters; + fParameters = state.fParameters; fError = state.fError; fGradient = state.fGradient; fEDM = state.fEDM; @@ -53,7 +53,7 @@ public: void* operator new(size_t nbytes) { return StackAllocatorHolder::Get().Allocate(nbytes); } - + void operator delete(void* p, size_t /*nbytes */) { StackAllocatorHolder::Get().Deallocate(p); } @@ -68,17 +68,17 @@ public: double Edm() const {return fEDM;} int NFcn() const {return fNFcn;} - bool IsValid() const { - if(HasParameters() && HasCovariance()) + bool IsValid() const { + if(HasParameters() && HasCovariance()) return Parameters().IsValid() && Error().IsValid(); else if(HasParameters()) return Parameters().IsValid(); else return false; - } + } bool HasParameters() const {return fParameters.IsValid();} bool HasCovariance() const {return fError.IsAvailable();} - + private: - + MinimumParameters fParameters; MinimumError fError; FunctionGradient fGradient; diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/CombinedMinimizer.h b/ThirdParty/RootMinimizers/inc/Minuit2/CombinedMinimizer.h index 343f08ce5fdda86523c1c4c66db19061e1c8cd5f..109797c59c91d0c790aca4685c0842c24de6ba64 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/CombinedMinimizer.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/CombinedMinimizer.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -23,8 +23,8 @@ namespace ROOT { Combined minimizer: combination of Migrad and Simplex. I If the Migrad method fails at first attempt, a simplex minimization is performed and then migrad is tried again. - - + + */ class CombinedMinimizer : public ModularFunctionMinimizer { @@ -33,7 +33,7 @@ public: CombinedMinimizer() : fMinSeedGen(MnSeedGenerator()), fMinBuilder(CombinedMinimumBuilder()) {} - + ~CombinedMinimizer() {} const MinimumSeedGenerator& SeedGenerator() const {return fMinSeedGen;} diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/CombinedMinimumBuilder.h b/ThirdParty/RootMinimizers/inc/Minuit2/CombinedMinimumBuilder.h index b2af7b82912a45fc61d3f1497d759a6dd7bf821e..de1614c14e4b228c29314fb237e0fd9605d662cb 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/CombinedMinimumBuilder.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/CombinedMinimumBuilder.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -23,7 +23,7 @@ class CombinedMinimumBuilder : public MinimumBuilder { public: - CombinedMinimumBuilder() : fVMMinimizer(VariableMetricMinimizer()), + CombinedMinimumBuilder() : fVMMinimizer(VariableMetricMinimizer()), fSimplexMinimizer(SimplexMinimizer()) {} ~CombinedMinimumBuilder() {} @@ -31,12 +31,12 @@ public: virtual FunctionMinimum Minimum(const MnFcn&, const GradientCalculator&, const MinimumSeed&, const MnStrategy&, unsigned int, double) const; //re-implement setter of base class. Need also to store in the base class for consistency - virtual void SetPrintLevel(int level) { + virtual void SetPrintLevel(int level) { MinimumBuilder::SetPrintLevel(level); fVMMinimizer.Builder().SetPrintLevel(level); fSimplexMinimizer.Builder().SetPrintLevel(level); } - virtual void SetStorageLevel(int level) { + virtual void SetStorageLevel(int level) { MinimumBuilder::SetStorageLevel(level); fVMMinimizer.Builder().SetStorageLevel(level); fSimplexMinimizer.Builder().SetStorageLevel(level); diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/ContoursError.h b/ThirdParty/RootMinimizers/inc/Minuit2/ContoursError.h index d572aeceed4b83395fdae80f7e1cc294a8fcdd4a..0752555d0e35e6a6e72e4e039ef9364098082c8e 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/ContoursError.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/ContoursError.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -67,7 +67,7 @@ public: unsigned int NFcn() const {return fNFcn;} double XMin() const {return fXMinos.Min();} double YMin() const {return fYMinos.Min();} - + private: unsigned int fParX; diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/DavidonErrorUpdator.h b/ThirdParty/RootMinimizers/inc/Minuit2/DavidonErrorUpdator.h index dcf4c2b4ee43494d76a5ae5eeddf5a25cfbb1157..b46a6f8c6d0d7dc7cfbb4fdcaf147ff6cb21f82e 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/DavidonErrorUpdator.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/DavidonErrorUpdator.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -27,7 +27,7 @@ class DavidonErrorUpdator : public MinimumErrorUpdator { public: DavidonErrorUpdator() {} - + virtual ~DavidonErrorUpdator() {} virtual MinimumError Update(const MinimumState&, const MinimumParameters&, diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/FCNAdapter.h b/ThirdParty/RootMinimizers/inc/Minuit2/FCNAdapter.h index bdec9b52388d46bd26e564b38046510d69bf7713..b245595d7b449e6e483200f2cb192dbfedaebfc6 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/FCNAdapter.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/FCNAdapter.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Author: L. Moneta 10/2006 +// Author: L. Moneta 10/2006 /********************************************************************** * * @@ -18,7 +18,7 @@ namespace ROOT { namespace Minuit2 { -/** +/** template wrapped class for adapting to FCNBase signature @@ -29,37 +29,37 @@ template wrapped class for adapting to FCNBase signature */ -template< class Function> +template< class Function> class FCNAdapter : public FCNBase { public: - FCNAdapter(const Function & f, double up = 1.) : - fFunc(f) , + FCNAdapter(const Function & f, double up = 1.) : + fFunc(f) , fUp (up) {} ~FCNAdapter() {} - - double operator()(const std::vector<double>& v) const { - return fFunc.operator()(&v[0]); + + double operator()(const std::vector<double>& v) const { + return fFunc.operator()(&v[0]); } - double operator()(const double * v) const { - return fFunc.operator()(v); + double operator()(const double * v) const { + return fFunc.operator()(v); } double Up() const {return fUp;} - void SetErrorDef(double up) { fUp = up; } - + void SetErrorDef(double up) { fUp = up; } + //virtual std::vector<double> Gradient(const std::vector<double>&) const; // forward interface //virtual double operator()(int npar, double* params,int iflag = 4) const; private: - const Function & fFunc; - double fUp; + const Function & fFunc; + double fUp; }; } // end namespace Minuit2 diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/FCNBase.h b/ThirdParty/RootMinimizers/inc/Minuit2/FCNBase.h index 83d8d5d8eb2188c616bf3e228949a3f1df74ce2b..f59ab5c81fef14a7fee271806f80c66738f83c3e 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/FCNBase.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/FCNBase.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -25,13 +25,13 @@ namespace ROOT { @defgroup Minuit Minuit2 Minimization Library - Object-oriented implementation of the MINUIT minimization package. - More information is available at the home page of the \ref Minuit2 package. + Object-oriented implementation of the MINUIT minimization package. + More information is available at the home page of the \ref Minuit2 package. */ //______________________________________________________________________________ -/** +/** Interface (abstract class) defining the function to be minimized, which has to be implemented by the user. @@ -53,14 +53,14 @@ public: /** - The meaning of the vector of parameters is of course defined by the user, - who uses the values of those parameters to calculate his function Value. - The order and the position of these parameters is strictly the one specified - by the user when supplying the starting values for minimization. The starting - values must be specified by the user, either via an std::vector<double> or the - MnUserParameters supplied as input to the MINUIT minimizers such as - VariableMetricMinimizer or MnMigrad. Later values are determined by MINUIT - as it searches for the Minimum or performs whatever analysis is requested by + The meaning of the vector of parameters is of course defined by the user, + who uses the values of those parameters to calculate their function Value. + The order and the position of these parameters is strictly the one specified + by the user when supplying the starting values for minimization. The starting + values must be specified by the user, either via an std::vector<double> or the + MnUserParameters supplied as input to the MINUIT minimizers such as + VariableMetricMinimizer or MnMigrad. Later values are determined by MINUIT + as it searches for the Minimum or performs whatever analysis is requested by the user. @param par function parameters as defined by the user. @@ -68,7 +68,7 @@ public: @return the Value of the function. @see MnUserParameters - @see VariableMetricMinimizer + @see VariableMetricMinimizer @see MnMigrad */ @@ -78,12 +78,12 @@ public: /** - Error definition of the function. MINUIT defines Parameter errors as the - change in Parameter Value required to change the function Value by up. Normally, + Error definition of the function. MINUIT defines Parameter errors as the + change in Parameter Value required to change the function Value by up. Normally, for chisquared fits it is 1, and for negative log likelihood, its Value is 0.5. - If the user wants instead the 2-sigma errors for chisquared fits, it becomes 4, + If the user wants instead the 2-sigma errors for chisquared fits, it becomes 4, as Chi2(x+n*sigma) = Chi2(x) + n*n. - + Comment a little bit better with links!!!!!!!!!!!!!!!!! */ @@ -93,23 +93,23 @@ public: /** - Error definition of the function. MINUIT defines Parameter errors as the - change in Parameter Value required to change the function Value by up. Normally, + Error definition of the function. MINUIT defines Parameter errors as the + change in Parameter Value required to change the function Value by up. Normally, for chisquared fits it is 1, and for negative log likelihood, its Value is 0.5. - If the user wants instead the 2-sigma errors for chisquared fits, it becomes 4, + If the user wants instead the 2-sigma errors for chisquared fits, it becomes 4, as Chi2(x+n*sigma) = Chi2(x) + n*n. - + \todo Comment a little bit better with links!!!!!!!!!!!!!!!!! Idem for ErrorDef() */ virtual double Up() const = 0; - /** - add interface to set dynamically a new error definition - Re-implement this function if needed. - */ - virtual void SetErrorDef(double ) {}; + /** + add interface to set dynamically a new error definition + Re-implement this function if needed. + */ + virtual void SetErrorDef(double ) {}; }; diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/FCNGradAdapter.h b/ThirdParty/RootMinimizers/inc/Minuit2/FCNGradAdapter.h index 4c8b2888919f916188e2d178ee3b2c66c296366b..cc743a3f34c110c583014164d8f323189400545e 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/FCNGradAdapter.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/FCNGradAdapter.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Author: L. Moneta 10/2006 +// Author: L. Moneta 10/2006 /********************************************************************** * * @@ -16,14 +16,14 @@ //#define DEBUG #ifdef DEBUG -#include <iostream> +#include <iostream> #endif namespace ROOT { namespace Minuit2 { -/** +/** template wrapped class for adapting to FCNBase signature a IGradFunction @@ -34,49 +34,49 @@ template wrapped class for adapting to FCNBase signature a IGradFunction */ -template< class Function> +template< class Function> class FCNGradAdapter : public FCNGradientBase { public: - FCNGradAdapter(const Function & f, double up = 1.) : - fFunc(f) , - fUp (up) , - fGrad(std::vector<double>(fFunc.NDim() ) ) + FCNGradAdapter(const Function & f, double up = 1.) : + fFunc(f) , + fUp (up) , + fGrad(std::vector<double>(fFunc.NDim() ) ) {} ~FCNGradAdapter() {} - - double operator()(const std::vector<double>& v) const { - return fFunc.operator()(&v[0]); + + double operator()(const std::vector<double>& v) const { + return fFunc.operator()(&v[0]); } - double operator()(const double * v) const { - return fFunc.operator()(v); + double operator()(const double * v) const { + return fFunc.operator()(v); } double Up() const {return fUp;} - - std::vector<double> Gradient(const std::vector<double>& v) const { + + std::vector<double> Gradient(const std::vector<double>& v) const { fFunc.Gradient(&v[0], &fGrad[0]); #ifdef DEBUG std::cout << " gradient in FCNAdapter = { " ; - for (unsigned int i = 0; i < fGrad.size(); ++i) + for (unsigned int i = 0; i < fGrad.size(); ++i) std::cout << fGrad[i] << "\t"; std::cout << "}" << std::endl; #endif - return fGrad; + return fGrad; } // forward interface //virtual double operator()(int npar, double* params,int iflag = 4) const; - bool CheckGradient() const { return false; } + bool CheckGradient() const { return false; } private: - const Function & fFunc; - double fUp; - mutable std::vector<double> fGrad; + const Function & fFunc; + double fUp; + mutable std::vector<double> fGrad; }; } // end namespace Minuit2 diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/FCNGradientBase.h b/ThirdParty/RootMinimizers/inc/Minuit2/FCNGradientBase.h index c3ed98654e71cd4f4dbecc1903e6b99ad6f4ff3b..ba9a7fe6232ea5ac548ce19675d79856d171e045 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/FCNGradientBase.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/FCNGradientBase.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -17,15 +17,15 @@ namespace ROOT { namespace Minuit2 { //________________________________________________________________________ -/** Extension of the FCNBase for providing the analytical Gradient of the - function. The user-Gradient is checked at the beginning of the - minimization against the Minuit internal numerical Gradient in order to - spot problems in the analytical Gradient calculation. This can be turned +/** Extension of the FCNBase for providing the analytical Gradient of the + function. The user-Gradient is checked at the beginning of the + minimization against the Minuit internal numerical Gradient in order to + spot problems in the analytical Gradient calculation. This can be turned off by overriding CheckGradient() to make it return "false". - The size of the output Gradient vector must be equal to the size of the + The size of the output Gradient vector must be equal to the size of the input Parameter vector. - Minuit does a check of the user Gradient at the beginning, if this is not - wanted the method "CheckGradient()" has to be overridden to return + Minuit does a check of the user Gradient at the beginning, if this is not + wanted the method "CheckGradient()" has to be overridden to return "false". */ @@ -34,11 +34,11 @@ class FCNGradientBase : public FCNBase { public: virtual ~FCNGradientBase() {} - + virtual std::vector<double> Gradient(const std::vector<double>&) const = 0; - + virtual bool CheckGradient() const {return true;} - + }; } // namespace Minuit2 diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/FumiliBuilder.h b/ThirdParty/RootMinimizers/inc/Minuit2/FumiliBuilder.h index f170b36ee4049cb5c92676a85ad957b35d15ffba..990a7bcfaff00a0656facfde4b891e9bfcfded2c 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/FumiliBuilder.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/FumiliBuilder.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -41,7 +41,7 @@ class FumiliBuilder : public MinimumBuilder { public: - FumiliBuilder() : fEstimator(VariableMetricEDMEstimator()), + FumiliBuilder() : fEstimator(VariableMetricEDMEstimator()), fErrorUpdator(FumiliErrorUpdator()) {} ~FumiliBuilder() {} @@ -58,10 +58,10 @@ public: @param fMinimumSeed the seed generator. - @param fMnStrategy the strategy describing the number of function calls + @param fMnStrategy the strategy describing the number of function calls allowed for Gradient calculations. - @param maxfcn maximum number of function calls after which the calculation + @param maxfcn maximum number of function calls after which the calculation will be stopped even if it has not yet converged. @param edmval expected vertical distance to the Minimum. @@ -69,7 +69,7 @@ public: @return Returns the function Minimum found. - \todo Complete the documentation by understanding what is the reason to + \todo Complete the documentation by understanding what is the reason to have two Minimum methods. */ @@ -87,9 +87,9 @@ public: @param fMinimumSeed the seed generator. - @param states vector containing the state result of each iteration + @param states vector containing the state result of each iteration - @param maxfcn maximum number of function calls after which the calculation + @param maxfcn maximum number of function calls after which the calculation will be stopped even if it has not yet converged. @param edmval expected vertical distance to the Minimum @@ -104,7 +104,7 @@ public: */ FunctionMinimum Minimum(const MnFcn& fMnFcn, const GradientCalculator& fGradienCalculator, const MinimumSeed& fMinimumSeed, std::vector<MinimumState> & states, unsigned int maxfcn, double edmval) const; - + /** @@ -115,7 +115,7 @@ public: \todo Maybe a little explanation concerning EDM in all relevant classes. */ - + const VariableMetricEDMEstimator& Estimator() const {return fEstimator;} diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/FumiliChi2FCN.h b/ThirdParty/RootMinimizers/inc/Minuit2/FumiliChi2FCN.h index dfce9b0462b0542a3b67a11ffff4993c18b6d997..e9819b2e2b904231527d344a5fd874959b21d94b 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/FumiliChi2FCN.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/FumiliChi2FCN.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -20,15 +20,15 @@ namespace ROOT { -/** +/** -Extension of the FCNBase for the Fumili method. Fumili applies only to -minimization problems used for fitting. The method is based on a -linearization of the model function negleting second derivatives. +Extension of the FCNBase for the Fumili method. Fumili applies only to +minimization problems used for fitting. The method is based on a +linearization of the model function negleting second derivatives. User needs to provide the model function. The figure-of-merit describing the difference between the model function and the actual measurements in the case of chi-square is the sum of the squares of the figures-of-merit -calculated for each measurement point, which is implemented by the +calculated for each measurement point, which is implemented by the operator() member function. The user still has to implement the calculation of the individual figures-of-merit (which in the majority of the cases will be the (measured Value - the Value predicted by the model)/standard deviation @@ -84,15 +84,15 @@ public: /** - - Evaluates the model function for the different measurement points and + + Evaluates the model function for the different measurement points and the Parameter values supplied, calculates a figure-of-merit for each measurement and returns a vector containing the result of this evaluation. @param par vector of Parameter values to feed to the model function. - @return A vector containing the figures-of-merit for the model function evaluated + @return A vector containing the figures-of-merit for the model function evaluated for each set of measurements. */ @@ -102,9 +102,9 @@ public: /** - + Accessor to the parameters of a given measurement. For example in the - case of a chi-square fit with a one-dimensional Gaussian, the Parameter + case of a chi-square fit with a one-dimensional Gaussian, the Parameter characterizing the measurement will be the position. It is the Parameter that is feeded to the model function. @@ -118,7 +118,7 @@ public: /** - Accessor to the number of measurements used for calculating the + Accessor to the number of measurements used for calculating the present figure of merit. @return the number of measurements @@ -130,48 +130,48 @@ public: /** - - Calculates the sum of Elements squared, ie the chi-square. The user must + + Calculates the sum of Elements squared, ie the chi-square. The user must implement in a class which inherits from FumiliChi2FCN the member function Elements() which will supply the Elements for the sum. @param par vector containing the Parameter values for the model function - + @return The sum of Elements squared @see FumiliFCNBase#elements */ - + double operator()(const std::vector<double>& par) const { - double chiSquare = 0.0; + double chiSquare = 0.0; std::vector<double> vecElements = Elements(par); unsigned int vecElementsSize = vecElements.size(); - for (unsigned int i = 0; i < vecElementsSize; ++i) - chiSquare += vecElements[i]*vecElements[i]; + for (unsigned int i = 0; i < vecElementsSize; ++i) + chiSquare += vecElements[i]*vecElements[i]; - return chiSquare; + return chiSquare; } - + /** - + !!!!!!!!!!!! to be commented */ - virtual double Up() const { return 1.0; } + virtual double Up() const { return 1.0; } - private: + private: // A pointer to the model function which describes the data const ParametricFunction *fModelFunction; - + }; diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/FumiliErrorUpdator.h b/ThirdParty/RootMinimizers/inc/Minuit2/FumiliErrorUpdator.h index 1ac1e4797350cc08414b082afbc552899f6c4899..3eb5da9c3602f68260de6b795c15af4c9ca93d67 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/FumiliErrorUpdator.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/FumiliErrorUpdator.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -17,17 +17,17 @@ namespace ROOT { namespace Minuit2 { -class MinimumState; -class MinimumParameters; -class GradientCalculator; -class FumiliFCNBase; -class FunctionGradient; +class MinimumState; +class MinimumParameters; +class GradientCalculator; +class FumiliFCNBase; +class FunctionGradient; /** In the case of the Fumili algorithm the Error matrix (or the Hessian matrix containing the (approximate) second derivatives) is calculated -using a linearization of the model function negleting second +using a linearization of the model function negleting second derivatives. (In some sense the Name Updator is a little bit misleading as the Error matrix is not calculated by iteratively updating, like in Davidon's or other similar variable metric methods, but by @@ -49,15 +49,15 @@ class FumiliErrorUpdator : public MinimumErrorUpdator { public: FumiliErrorUpdator() {} - + ~FumiliErrorUpdator() { } /** - + Member function that calculates the Error matrix (or the Hessian - matrix containing the (approximate) second derivatives) using a + matrix containing the (approximate) second derivatives) using a linearization of the model function negleting second derivatives. @param fMinimumState used to calculate the change in the covariance @@ -68,13 +68,13 @@ public: @param fGradientCalculator the Gradient calculator used to retrieved the Parameter transformation @param fFumiliFCNBase the function calculating the figure of merit. - + \todo Some nice latex mathematical formuli... */ - virtual MinimumError Update(const MinimumState& fMinimumState, + virtual MinimumError Update(const MinimumState& fMinimumState, const MinimumParameters& fMinimumParameters, const GradientCalculator& fGradientCalculator, double lambda) const; @@ -85,7 +85,7 @@ public: Member function which is only present due to the design already in place of the software. As all classes calculating the Error matrix are supposed - inherit from the MinimumErrorUpdator they must inherit this method. In some + inherit from the MinimumErrorUpdator they must inherit this method. In some methods calculating the aforementioned matrix some of these parameters are not needed and other parameters are necessary... Hopefully, a more elegant solution will be found in the future. diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/FumiliFCNAdapter.h b/ThirdParty/RootMinimizers/inc/Minuit2/FumiliFCNAdapter.h index 2d04727371796fefa9575b3fd74628cd9eb6028a..3c27dd4aeba065c8a42babfe8e19b692c3f4d3ce 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/FumiliFCNAdapter.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/FumiliFCNAdapter.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Author: L. Moneta 10/2006 +// Author: L. Moneta 10/2006 /********************************************************************** * * @@ -32,7 +32,7 @@ namespace ROOT { namespace Minuit2 { -/** +/** template wrapped class for adapting to FumiliFCNBase signature @@ -43,33 +43,33 @@ template wrapped class for adapting to FumiliFCNBase signature */ -template< class Function> +template< class Function> class FumiliFCNAdapter : public FumiliFCNBase { public: -// typedef ROOT::Math::FitMethodFunction Function; - typedef typename Function::Type_t Type_t; +// typedef ROOT::Math::FitMethodFunction Function; + typedef typename Function::Type_t Type_t; - FumiliFCNAdapter(const Function & f, unsigned int ndim, double up = 1.) : + FumiliFCNAdapter(const Function & f, unsigned int ndim, double up = 1.) : FumiliFCNBase( ndim ), - fFunc(f) , + fFunc(f) , fUp (up) {} ~FumiliFCNAdapter() {} - - double operator()(const std::vector<double>& v) const { - return fFunc.operator()(&v[0]); + + double operator()(const std::vector<double>& v) const { + return fFunc.operator()(&v[0]); } - double operator()(const double * v) const { - return fFunc.operator()(v); + double operator()(const double * v) const { + return fFunc.operator()(v); } double Up() const {return fUp;} - void SetErrorDef(double up) { fUp = up; } - + void SetErrorDef(double up) { fUp = up; } + //virtual std::vector<double> Gradient(const std::vector<double>&) const; // forward interface @@ -77,24 +77,24 @@ public: /** - evaluate gradient hessian and function value needed by fumili + evaluate gradient hessian and function value needed by fumili */ void EvaluateAll( const std::vector<double> & v); private: - + //data member - const Function & fFunc; - double fUp; + const Function & fFunc; + double fUp; }; template<class Function> -void FumiliFCNAdapter<Function>::EvaluateAll( const std::vector<double> & v) { +void FumiliFCNAdapter<Function>::EvaluateAll( const std::vector<double> & v) { - //typedef FumiliFCNAdapter::Function Function; + //typedef FumiliFCNAdapter::Function Function; //evaluate all elements unsigned int npar = Dimension(); @@ -102,66 +102,66 @@ void FumiliFCNAdapter<Function>::EvaluateAll( const std::vector<double> & v) { assert(npar == v.size()); //must distinguish case of likelihood or LS - std::vector<double> & grad = Gradient(); - std::vector<double> & hess = Hessian(); - // reset + std::vector<double> & grad = Gradient(); + std::vector<double> & hess = Hessian(); + // reset assert(grad.size() == npar); - grad.assign( npar, 0.0); + grad.assign( npar, 0.0); hess.assign( hess.size(), 0.0); - - double sum = 0; + + double sum = 0; unsigned int ndata = fFunc.NPoints(); - std::vector<double> gf(npar); - + std::vector<double> gf(npar); + //loop on the data points - + // assume for now least-square - if (fFunc.Type() == Function::kLeastSquare) { + if (fFunc.Type() == Function::kLeastSquare) { - for (unsigned int i = 0; i < ndata; ++i) { - // calculate data element and gradient + for (unsigned int i = 0; i < ndata; ++i) { + // calculate data element and gradient double fval = fFunc.DataElement(&v.front(), i, &gf[0]); // t.b.d should protect for bad values of fval sum += fval*fval; - for (unsigned int j = 0; j < npar; ++j) { + for (unsigned int j = 0; j < npar; ++j) { grad[j] += 2. * fval * gf[j]; - for (unsigned int k = j; k < npar; ++ k) { - int idx = j + k*(k+1)/2; - hess[idx] += 2.0 * gf[j] * gf[k]; + for (unsigned int k = j; k < npar; ++ k) { + int idx = j + k*(k+1)/2; + hess[idx] += 2.0 * gf[j] * gf[k]; } } } } - else if (fFunc.Type() == Function::kLogLikelihood) { + else if (fFunc.Type() == Function::kLogLikelihood) { - for (unsigned int i = 0; i < ndata; ++i) { + for (unsigned int i = 0; i < ndata; ++i) { - // calculate data element and gradient + // calculate data element and gradient // return value is log of pdf and derivative of the log(Pdf) double fval = fFunc.DataElement(&v.front(), i, &gf[0]); sum -= fval; - - for (unsigned int j = 0; j < npar; ++j) { - double gfj = gf[j] ; + + for (unsigned int j = 0; j < npar; ++j) { + double gfj = gf[j] ; grad[j] -= gfj; - for (unsigned int k = j; k < npar; ++ k) { - int idx = j + k*(k+1)/2; - hess[idx] += gfj * gf[k] ; + for (unsigned int k = j; k < npar; ++ k) { + int idx = j + k*(k+1)/2; + hess[idx] += gfj * gf[k] ; } } } } - else { + else { MN_ERROR_MSG("FumiliFCNAdapter: type of fit method is not supported, it must be chi2 or log-likelihood"); } } - + } // end namespace Minuit2 diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/FumiliFCNBase.h b/ThirdParty/RootMinimizers/inc/Minuit2/FumiliFCNBase.h index b76d70e1490ceb800e38f872c1403e8fc8e7f65c..0ffc17fbf912574195079db56363225250347094 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/FumiliFCNBase.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/FumiliFCNBase.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -19,11 +19,11 @@ namespace ROOT { //____________________________________________________________________________________________ -/** - -Extension of the FCNBase for the Fumili method. Fumili applies only to -minimization problems used for fitting. The method is based on a -linearization of the model function negleting second derivatives. +/** + +Extension of the FCNBase for the Fumili method. Fumili applies only to +minimization problems used for fitting. The method is based on a +linearization of the model function negleting second derivatives. User needs to provide the model function. The figure-of-merit describing the difference between the model function and the actual measurements has to be implemented by the user in a subclass of FumiliFCNBase. @@ -52,8 +52,8 @@ public: Default Constructor. Need in this case to create when implementing EvaluateAll the Gradient and Hessian vectors with the right size */ - FumiliFCNBase() : - fNumberOfParameters(0), + FumiliFCNBase() : + fNumberOfParameters(0), fValue(0) {} @@ -62,16 +62,16 @@ public: Constructor which initializes the class with the function provided by the user for modeling the data. - @param npar the number of parameters + @param npar the number of parameters */ - FumiliFCNBase(unsigned int npar) : + FumiliFCNBase(unsigned int npar) : fNumberOfParameters(npar), fValue(0), - fGradient(std::vector<double>(npar)), - fHessian(std::vector<double>(static_cast<int>( 0.5*npar*(npar+1) )) ) + fGradient(std::vector<double>(npar)), + fHessian(std::vector<double>(static_cast<int>( 0.5*npar*(npar+1) )) ) {} @@ -86,16 +86,16 @@ public: /** - + Evaluate function Value, Gradient and Hessian using Fumili approximation, for values of parameters p - The resul is cached inside and is return from the FumiliFCNBase::Value , FumiliFCNBase::Gradient and - FumiliFCNBase::Hessian methods + The resul is cached inside and is return from the FumiliFCNBase::Value , FumiliFCNBase::Gradient and + FumiliFCNBase::Hessian methods @param par vector of parameters **/ - virtual void EvaluateAll( const std::vector<double> & par ) = 0; + virtual void EvaluateAll( const std::vector<double> & par ) = 0; /** @@ -103,7 +103,7 @@ public: **/ - virtual double Value() const { return fValue; } + virtual double Value() const { return fValue; } /** Return cached Value of function Gradient estimated previously using the FumiliFCNBase::EvaluateAll method @@ -117,12 +117,12 @@ public: @param col col Index of the matrix **/ - virtual double Hessian(unsigned int row, unsigned int col) const { - assert( row < fGradient.size() && col < fGradient.size() ); - if(row > col) + virtual double Hessian(unsigned int row, unsigned int col) const { + assert( row < fGradient.size() && col < fGradient.size() ); + if(row > col) return fHessian[col+row*(row+1)/2]; else - return fHessian[row+col*(col+1)/2]; + return fHessian[row+col*(col+1)/2]; } /** @@ -131,7 +131,7 @@ public: virtual unsigned int Dimension() { return fNumberOfParameters; } -protected : +protected : /** initialize and reset values of gradien and Hessian @@ -139,11 +139,11 @@ protected : virtual void InitAndReset(unsigned int npar) { fNumberOfParameters = npar; - fGradient = std::vector<double>(npar); - fHessian = std::vector<double>(static_cast<int>( 0.5*npar*(npar+1) )); + fGradient = std::vector<double>(npar); + fHessian = std::vector<double>(static_cast<int>( 0.5*npar*(npar+1) )); } - // methods to be used by the derived classes to set the values + // methods to be used by the derived classes to set the values void SetFCNValue(double value) { fValue = value; } std::vector<double> & Gradient() { return fGradient; } @@ -153,11 +153,11 @@ protected : -private: +private: - unsigned int fNumberOfParameters; - double fValue; - std::vector<double> fGradient; + unsigned int fNumberOfParameters; + double fValue; + std::vector<double> fGradient; std::vector<double> fHessian; diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/FumiliGradientCalculator.h b/ThirdParty/RootMinimizers/inc/Minuit2/FumiliGradientCalculator.h index 603d6918ba34e2f5b0548e19aaeebfa2cadfb679..fa696f3b1a459afeb39d2d7b989e1c26c4d59a3a 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/FumiliGradientCalculator.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/FumiliGradientCalculator.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -26,10 +26,10 @@ class FumiliGradientCalculator : public GradientCalculator { public: - FumiliGradientCalculator(const FumiliFCNBase& fcn, const MnUserTransformation& state, int n) : - fFcn(fcn), - fTransformation(state), - fHessian(MnAlgebraicSymMatrix(n) ) + FumiliGradientCalculator(const FumiliFCNBase& fcn, const MnUserTransformation& state, int n) : + fFcn(fcn), + fTransformation(state), + fHessian(MnAlgebraicSymMatrix(n) ) {} ~FumiliGradientCalculator() {} @@ -39,7 +39,7 @@ public: FunctionGradient operator()(const MinimumParameters&, const FunctionGradient&) const; - const MnUserTransformation& Trafo() const {return fTransformation;} + const MnUserTransformation& Trafo() const {return fTransformation;} const MnAlgebraicSymMatrix & Hessian() const { return fHessian; } diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/FumiliMaximumLikelihoodFCN.h b/ThirdParty/RootMinimizers/inc/Minuit2/FumiliMaximumLikelihoodFCN.h index 508667d99d04776453633ba813ec710cbb0706e1..c6725ae350e68a991ef43de710ac99ac59601932 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/FumiliMaximumLikelihoodFCN.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/FumiliMaximumLikelihoodFCN.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -15,6 +15,7 @@ #include <cmath> #include <float.h> #include "Minuit2/ParametricFunction.h" +#include "Math/Util.h" namespace ROOT { @@ -23,11 +24,11 @@ namespace ROOT { //#include <iostream> -/** +/** -Extension of the FCNBase for the Fumili method. Fumili applies only to -minimization problems used for fitting. The method is based on a -linearization of the model function negleting second derivatives. +Extension of the FCNBase for the Fumili method. Fumili applies only to +minimization problems used for fitting. The method is based on a +linearization of the model function negleting second derivatives. User needs to provide the model function. In this cased the function to be minimized is the sum of the logarithms of the model function for the different measurements times -1. @@ -81,15 +82,15 @@ public: /** - - Evaluates the model function for the different measurement points and + + Evaluates the model function for the different measurement points and the Parameter values supplied, calculates a figure-of-merit for each measurement and returns a vector containing the result of this evaluation. @param par vector of Parameter values to feed to the model function. - @return A vector containing the figures-of-merit for the model function evaluated + @return A vector containing the figures-of-merit for the model function evaluated for each set of measurements. */ @@ -99,9 +100,9 @@ public: /** - + Accessor to the parameters of a given measurement. For example in the - case of a chi-square fit with a one-dimensional Gaussian, the Parameter + case of a chi-square fit with a one-dimensional Gaussian, the Parameter characterizing the measurement will be the position. It is the Parameter that is feeded to the model function. @@ -115,7 +116,7 @@ public: /** - Accessor to the number of measurements used for calculating the + Accessor to the number of measurements used for calculating the present figure of merit. @return the number of measurements @@ -126,50 +127,49 @@ public: /** - - Calculates the function for the maximum likelihood method. The user must + + Calculates the function for the maximum likelihood method. The user must implement in a class which inherits from FumiliChi2FCN the member function Elements() which will supply the Elements for the sum. @param par vector containing the Parameter values for the model function - + @return The sum of the natural logarithm of the Elements multiplied by -1 @see FumiliFCNBase#elements */ - + double operator()(const std::vector<double>& par) const { double sumoflogs = 0.0; std::vector<double> vecElements = Elements(par); unsigned int vecElementsSize = vecElements.size(); - + for (unsigned int i = 0; i < vecElementsSize; ++i) { double tmp = vecElements[i]; //for max likelihood probability have to be positive assert(tmp >= 0); - if ( tmp < FLT_MIN*5 ) - tmp = FLT_MIN*5; - - sumoflogs -= std::log(tmp); + sumoflogs -= ROOT::Math::Util::EvalLog(tmp); //std::cout << " i " << tmp << " lik " << sumoflogs << std::endl; } + + return sumoflogs; } - + /** - + !!!!!!!!!!!! to be commented */ - virtual double Up() const { return 0.5; } - - private: + virtual double Up() const { return 0.5; } + + private: // A pointer to the model function which describes the data const ParametricFunction *fModelFunction; diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/FumiliMinimizer.h b/ThirdParty/RootMinimizers/inc/Minuit2/FumiliMinimizer.h index c909f4efb9fb0ab882128cc2cb2d9fe40d743d15..e74043c4fbadcbeb514c59ff59b82b215f2305b4 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/FumiliMinimizer.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/FumiliMinimizer.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -24,7 +24,7 @@ class MinimumSeedGenerator; class MinimumBuilder; class MinimumSeed; class MnFcn; -class FumiliFcnBase; +class FumiliFcnBase; class GradientCalculator; class MnUserParameterState; class MnUserParameters; @@ -34,10 +34,10 @@ class MnStrategy; //______________________________________________________________ -/** +/** Instantiates the seed generator and Minimum builder for the -Fumili minimization method. Produces the Minimum via the +Fumili minimization method. Produces the Minimum via the Minimize methods inherited from ModularFunctionMinimizer. @author Andras Zsenei and Lorenzo Moneta, Creation date: 28 Sep 2004 @@ -54,18 +54,18 @@ public: /** - Constructor initializing the FumiliMinimizer by instantiatiating + Constructor initializing the FumiliMinimizer by instantiatiating the SeedGenerator and MinimumBuilder for the Fumili minimization method. @see MnSeedGenerator - + @see FumiliBuilder */ FumiliMinimizer() : fMinSeedGen(MnSeedGenerator()), fMinBuilder(FumiliBuilder()) {} - + ~FumiliMinimizer() {} @@ -100,43 +100,43 @@ public: // need to re-implement all function in ModularFuncitionMinimizer otherwise they will be hided - virtual FunctionMinimum Minimize(const FCNBase& fcn, const std::vector<double>& par, const std::vector<double>& err, unsigned int stra = 1, unsigned int maxfcn = 0, double toler = 0.1) const { + virtual FunctionMinimum Minimize(const FCNBase& fcn, const std::vector<double>& par, const std::vector<double>& err, unsigned int stra = 1, unsigned int maxfcn = 0, double toler = 0.1) const { return ModularFunctionMinimizer::Minimize(fcn, par, err, stra, maxfcn,toler); - } + } - virtual FunctionMinimum Minimize(const FCNGradientBase&fcn, const std::vector<double>&par, const std::vector<double>&err, unsigned int stra=1, unsigned int maxfcn = 0, double toler = 0.1) const { - return ModularFunctionMinimizer::Minimize(fcn,par,err,stra,maxfcn,toler); + virtual FunctionMinimum Minimize(const FCNGradientBase&fcn, const std::vector<double>&par, const std::vector<double>&err, unsigned int stra=1, unsigned int maxfcn = 0, double toler = 0.1) const { + return ModularFunctionMinimizer::Minimize(fcn,par,err,stra,maxfcn,toler); } - virtual FunctionMinimum Minimize(const FCNBase& fcn, const std::vector<double>&par, unsigned int nrow, const std::vector<double>&cov, unsigned int stra=1, unsigned int maxfcn = 0, double toler = 0.1) const { - return ModularFunctionMinimizer::Minimize(fcn,par,nrow,cov,stra,maxfcn,toler); - } + virtual FunctionMinimum Minimize(const FCNBase& fcn, const std::vector<double>&par, unsigned int nrow, const std::vector<double>&cov, unsigned int stra=1, unsigned int maxfcn = 0, double toler = 0.1) const { + return ModularFunctionMinimizer::Minimize(fcn,par,nrow,cov,stra,maxfcn,toler); + } + + virtual FunctionMinimum Minimize(const FCNGradientBase& fcn, const std::vector<double>&par, unsigned int nrow, const std::vector<double>&cov, unsigned int stra=1, unsigned int maxfcn = 0, double toler = 0.1) const { + return ModularFunctionMinimizer::Minimize(fcn,par,nrow,cov,stra,maxfcn,toler); + } - virtual FunctionMinimum Minimize(const FCNGradientBase& fcn, const std::vector<double>&par, unsigned int nrow, const std::vector<double>&cov, unsigned int stra=1, unsigned int maxfcn = 0, double toler = 0.1) const { - return ModularFunctionMinimizer::Minimize(fcn,par,nrow,cov,stra,maxfcn,toler); - } - - virtual FunctionMinimum Minimize(const FCNBase& fcn, const MnUserParameters& par, const MnStrategy& stra, unsigned int maxfcn = 0, double toler = 0.1) const { - return ModularFunctionMinimizer::Minimize(fcn,par,stra,maxfcn,toler); + virtual FunctionMinimum Minimize(const FCNBase& fcn, const MnUserParameters& par, const MnStrategy& stra, unsigned int maxfcn = 0, double toler = 0.1) const { + return ModularFunctionMinimizer::Minimize(fcn,par,stra,maxfcn,toler); } - virtual FunctionMinimum Minimize(const FCNGradientBase& fcn, const MnUserParameters& par, const MnStrategy& stra, unsigned int maxfcn = 0, double toler = 0.1) const { - return ModularFunctionMinimizer::Minimize(fcn,par,stra,maxfcn,toler); + virtual FunctionMinimum Minimize(const FCNGradientBase& fcn, const MnUserParameters& par, const MnStrategy& stra, unsigned int maxfcn = 0, double toler = 0.1) const { + return ModularFunctionMinimizer::Minimize(fcn,par,stra,maxfcn,toler); } - virtual FunctionMinimum Minimize(const FCNBase& fcn, const MnUserParameters& par, const MnUserCovariance& cov, const MnStrategy& stra, unsigned int maxfcn = 0, double toler = 0.1) const { - return ModularFunctionMinimizer::Minimize(fcn,par,cov,stra,maxfcn,toler); + virtual FunctionMinimum Minimize(const FCNBase& fcn, const MnUserParameters& par, const MnUserCovariance& cov, const MnStrategy& stra, unsigned int maxfcn = 0, double toler = 0.1) const { + return ModularFunctionMinimizer::Minimize(fcn,par,cov,stra,maxfcn,toler); } - virtual FunctionMinimum Minimize(const FCNGradientBase& fcn, const MnUserParameters& par, const MnUserCovariance& cov, const MnStrategy& stra, unsigned int maxfcn = 0, double toler = 0.1) const { - return ModularFunctionMinimizer::Minimize(fcn,par,cov,stra,maxfcn,toler); + virtual FunctionMinimum Minimize(const FCNGradientBase& fcn, const MnUserParameters& par, const MnUserCovariance& cov, const MnStrategy& stra, unsigned int maxfcn = 0, double toler = 0.1) const { + return ModularFunctionMinimizer::Minimize(fcn,par,cov,stra,maxfcn,toler); } - virtual FunctionMinimum Minimize(const MnFcn& mfcn, const GradientCalculator& gc, const MinimumSeed& seed, const MnStrategy& stra, unsigned int maxfcn, double toler) const { - return ModularFunctionMinimizer::Minimize(mfcn, gc, seed, stra, maxfcn, toler); + virtual FunctionMinimum Minimize(const MnFcn& mfcn, const GradientCalculator& gc, const MinimumSeed& seed, const MnStrategy& stra, unsigned int maxfcn, double toler) const { + return ModularFunctionMinimizer::Minimize(mfcn, gc, seed, stra, maxfcn, toler); } diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/FumiliStandardChi2FCN.h b/ThirdParty/RootMinimizers/inc/Minuit2/FumiliStandardChi2FCN.h index a647c856a96e75a684570e16f4c5d580beaf870e..90cf2dc613fe87158e77da005c91394b11333d70 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/FumiliStandardChi2FCN.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/FumiliStandardChi2FCN.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -10,7 +10,7 @@ #ifndef ROOT_Minuit2_FumiliStandardChi2FCN #define ROOT_Minuit2_FumiliStandardChi2FCN - + #include "Minuit2/FumiliChi2FCN.h" #include "Minuit2/ParametricFunction.h" #include <assert.h> @@ -26,8 +26,8 @@ namespace ROOT { /** Class implementing the standard chi square function, which -is the sum of the squares of the figures-of-merit calculated for each measurement -point, the individual figures-of-merit being: (the Value predicted by the +is the sum of the squares of the figures-of-merit calculated for each measurement +point, the individual figures-of-merit being: (the Value predicted by the model-measured Value)/standard deviation. @author Andras Zsenei and Lorenzo Moneta, Creation date: 31 Aug 2004 @@ -46,9 +46,9 @@ public: /** - + Constructor which initializes chi square function for one-dimensional model function - + @param modelFCN the model function used for describing the data. @param meas vector containing the measured values. @@ -56,43 +56,44 @@ public: @param pos vector containing the x values corresponding to the measurements - @param mvar vector containing the variances corresponding to each + @param mvar vector containing the variances corresponding to each measurement (where the variance equals the standard deviation squared). If the variances are zero, a Value of 1 is used (as it is done in ROOT/PAW) */ - FumiliStandardChi2FCN(const ParametricFunction& modelFCN, const std::vector<double>& meas, - const std::vector<double>& pos, - const std::vector<double>& mvar) - { //this->fModelFCN = &modelFunction; - this->SetModelFunction(modelFCN); - - assert(meas.size() == pos.size()); - assert(meas.size() == mvar.size()); - fMeasurements = meas; - std::vector<double> x(1); - unsigned int n = mvar.size(); - fPositions.reserve( n); - // correct for variance == 0 - fInvErrors.resize(n); - for (unsigned int i = 0; i < n; ++i) - { - x[0] = pos[i]; - fPositions.push_back(x); - // PAW/ROOT hack : use 1 for 0 entries bins - if (mvar[i] == 0) - fInvErrors[i] = 1; - else - fInvErrors[i] = 1.0/std::sqrt(mvar[i]); - } + FumiliStandardChi2FCN(const ParametricFunction& modelFCN, const std::vector<double>& meas, + const std::vector<double>& pos, + const std::vector<double>& mvar) + { //this->fModelFCN = &modelFunction; + this->SetModelFunction(modelFCN); + + assert(meas.size() == pos.size()); + assert(meas.size() == mvar.size()); + fMeasurements = meas; + std::vector<double> x(1); + unsigned int n = mvar.size(); + fPositions.reserve( n); + // correct for variance == 0 + fInvErrors.resize(n); + for (unsigned int i = 0; i < n; ++i) + { + x[0] = pos[i]; + fPositions.push_back(x); + // PAW/ROOT hack : use 1 for 0 entries bins + if (mvar[i] == 0) + fInvErrors[i] = 1; + else + fInvErrors[i] = 1.0/std::sqrt(mvar[i]); + } + } /** - + Constructor which initializes the multi-dimensional model function. - + @param modelFCN the model function used for describing the data. @param meas vector containing the measured values. @@ -100,7 +101,7 @@ public: @param pos vector containing the x values corresponding to the measurements - @param mvar vector containing the variances corresponding to each + @param mvar vector containing the variances corresponding to each measurement (where the variance equals the standard deviation squared). If the variances are zero, a Value of 1 is used (as it is done in ROOT/PAW) @@ -111,7 +112,7 @@ public: const std::vector<double>& mvar) { //this->fModelFCN = &modelFunction; this->SetModelFunction(modelFCN); - + assert(meas.size() == pos.size()); assert(meas.size() == mvar.size()); fMeasurements = meas; @@ -123,9 +124,9 @@ public: { // PAW/ROOT hack : use 1 for 0 entries bins if (mvar[i] == 0) - fInvErrors[i] = 1; + fInvErrors[i] = 1; else - fInvErrors[i] = 1.0/std::sqrt(mvar[i]); + fInvErrors[i] = 1.0/std::sqrt(mvar[i]); } } @@ -141,16 +142,16 @@ public: /** - Evaluates the model function for the different measurement points and + Evaluates the model function for the different measurement points and the Parameter values supplied, calculates a figure-of-merit for each measurement and returns a vector containing the result of this - evaluation. The figure-of-merit is (Value predicted by the model + evaluation. The figure-of-merit is (Value predicted by the model function-measured Value)/standard deviation. @param par vector of Parameter values to feed to the model function. - @return A vector containing the figures-of-merit for the model function evaluated - for each set of measurements. + @return A vector containing the figures-of-merit for the model function evaluated + for each set of measurements. \todo What to do when the variances are 0???!! (right now just pushes back 0...) @@ -175,7 +176,7 @@ public: /** - Accessor to the number of measurements used for calculating + Accessor to the number of measurements used for calculating the chi-square. @return the number of measurements. @@ -186,16 +187,16 @@ public: /** - + Evaluate function Value, Gradient and Hessian using Fumili approximation, for values of parameters p - The resul is cached inside and is return from the FumiliFCNBase::Value , FumiliFCNBase::Gradient and - FumiliFCNBase::Hessian methods + The resul is cached inside and is return from the FumiliFCNBase::Value , FumiliFCNBase::Gradient and + FumiliFCNBase::Hessian methods @param par vector of parameters **/ - virtual void EvaluateAll( const std::vector<double> & par ); + virtual void EvaluateAll( const std::vector<double> & par ); private: diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/FumiliStandardMaximumLikelihoodFCN.h b/ThirdParty/RootMinimizers/inc/Minuit2/FumiliStandardMaximumLikelihoodFCN.h index dc2e6565d5813a4d9eb4d8a84c36a122b21a1fea..ad9737304b5f821418e74971489f715d4353521d 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/FumiliStandardMaximumLikelihoodFCN.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/FumiliStandardMaximumLikelihoodFCN.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -24,7 +24,7 @@ namespace ROOT { /** -Class implementing the Elements member function for the standard +Class implementing the Elements member function for the standard maximum likelihood method. @author Andras Zsenei and Lorenzo Moneta, Creation date: 4 Sep 2004 @@ -41,9 +41,9 @@ public: /** - + Constructor which initializes the measurement points for the one dimensional model function. - + @param modelFCN the model function used for describing the data. @param pos vector containing the x values corresponding to the @@ -51,25 +51,25 @@ public: */ - FumiliStandardMaximumLikelihoodFCN(const ParametricFunction& modelFCN, - const std::vector<double>& pos) + FumiliStandardMaximumLikelihoodFCN(const ParametricFunction& modelFCN, + const std::vector<double>& pos) { - this->SetModelFunction(modelFCN); - unsigned int n = pos.size(); + this->SetModelFunction(modelFCN); + unsigned int n = pos.size(); fPositions.reserve( n ); std::vector<double> x(1); - for (unsigned int i = 0; i < n; ++i) { + for (unsigned int i = 0; i < n; ++i) { x[0] = pos[i]; - fPositions.push_back(x); + fPositions.push_back(x); } } /** - + Constructor which initializes the measurement points for the multi dimensional model function. - + @param modelFCN the model function used for describing the data. @param pos vector containing the x values corresponding to the @@ -77,10 +77,9 @@ public: */ - FumiliStandardMaximumLikelihoodFCN(const ParametricFunction& modelFCN, - const std::vector<std::vector<double> >& pos) - { - this->SetModelFunction(modelFCN); + FumiliStandardMaximumLikelihoodFCN(const ParametricFunction& modelFCN, + const std::vector<std::vector<double> >& pos) { + this->SetModelFunction(modelFCN); fPositions = pos; } @@ -95,13 +94,13 @@ public: /** - Evaluates the model function for the different measurement points and + Evaluates the model function for the different measurement points and the Parameter values supplied. @param par vector of Parameter values to feed to the model function. - @return A vector containing the model function evaluated - for each measurement point. + @return A vector containing the model function evaluated + for each measurement point. */ @@ -125,7 +124,7 @@ public: /** - Accessor to the number of measurements used for calculating + Accessor to the number of measurements used for calculating the maximum likelihood. @return the number of measurements. @@ -135,10 +134,10 @@ public: virtual int GetNumberOfMeasurements() const; /** - + Evaluate function Value, Gradient and Hessian using Fumili approximation, for values of parameters p - The resul is cached inside and is return from the FumiliFCNBase::Value , FumiliFCNBase::Gradient and - FumiliFCNBase::Hessian methods + The resul is cached inside and is return from the FumiliFCNBase::Value , FumiliFCNBase::Gradient and + FumiliFCNBase::Hessian methods @param par vector of parameters diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/FunctionGradient.h b/ThirdParty/RootMinimizers/inc/Minuit2/FunctionGradient.h index c284f5fbcacabf785f2078aae274348c0a11b2bb..68eb31ba7e440307759e8371ad592f68ad1ca53f 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/FunctionGradient.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/FunctionGradient.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -23,19 +23,19 @@ class FunctionGradient { private: public: - - explicit FunctionGradient(unsigned int n) : + + explicit FunctionGradient(unsigned int n) : fData(MnRefCountedPointer<BasicFunctionGradient>(new BasicFunctionGradient(n))) {} - - explicit FunctionGradient(const MnAlgebraicVector& grd) : + + explicit FunctionGradient(const MnAlgebraicVector& grd) : fData(MnRefCountedPointer<BasicFunctionGradient>(new BasicFunctionGradient(grd))) {} FunctionGradient(const MnAlgebraicVector& grd, const MnAlgebraicVector& g2, const MnAlgebraicVector& gstep) : fData(MnRefCountedPointer<BasicFunctionGradient>(new BasicFunctionGradient(grd, g2, gstep))) {} - + ~FunctionGradient() {} - + FunctionGradient(const FunctionGradient& grad) : fData(grad.fData) {} FunctionGradient& operator=(const FunctionGradient& grad) { diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/FunctionMinimizer.h b/ThirdParty/RootMinimizers/inc/Minuit2/FunctionMinimizer.h index 602e0fe17bdc3f68557df02b438080bd5a1f4c59..f7b93cafc34e4a97c1bfe1eb645f8bc0b1c74288 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/FunctionMinimizer.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/FunctionMinimizer.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -26,30 +26,30 @@ class FunctionMinimum; //_____________________________________________________________________________________ /** base class for function minimizers; user may give FCN or FCN with Gradient, Parameter starting values and initial Error guess (sigma) (or "step size"), - or Parameter starting values and initial covariance matrix; - covariance matrix is stored in Upper triangular packed storage format, - e.g. the Elements in the array are arranged like + or Parameter starting values and initial covariance matrix; + covariance matrix is stored in Upper triangular packed storage format, + e.g. the Elements in the array are arranged like {a(0,0), a(0,1), a(1,1), a(0,2), a(1,2), a(2,2), ...}, - the size is nrow*(nrow+1)/2 (see also MnUserCovariance.h); + the size is nrow*(nrow+1)/2 (see also MnUserCovariance.h); */ class FunctionMinimizer { public: - + virtual ~FunctionMinimizer() {} //starting values for parameters and errors - virtual FunctionMinimum Minimize(const FCNBase&, const std::vector<double>& par, const std::vector<double>& err, unsigned int strategy, unsigned int maxfcn, double toler) const = 0; + virtual FunctionMinimum Minimize(const FCNBase&, const std::vector<double>& par, const std::vector<double>& err, unsigned int strategy, unsigned int maxfcn, double toler) const = 0; //starting values for parameters and errors and FCN with Gradient - virtual FunctionMinimum Minimize(const FCNGradientBase&, const std::vector<double>& par, const std::vector<double>& err, unsigned int strategy, unsigned int maxfcn, double toler) const = 0; + virtual FunctionMinimum Minimize(const FCNGradientBase&, const std::vector<double>& par, const std::vector<double>& err, unsigned int strategy, unsigned int maxfcn, double toler) const = 0; //starting values for parameters and covariance matrix - virtual FunctionMinimum Minimize(const FCNBase&, const std::vector<double>& par, unsigned int nrow, const std::vector<double>& cov, unsigned int strategy, unsigned int maxfcn, double toler) const = 0; + virtual FunctionMinimum Minimize(const FCNBase&, const std::vector<double>& par, unsigned int nrow, const std::vector<double>& cov, unsigned int strategy, unsigned int maxfcn, double toler) const = 0; //starting values for parameters and covariance matrix and FCN with Gradient - virtual FunctionMinimum Minimize(const FCNGradientBase&, const std::vector<double>& par, unsigned int nrow, const std::vector<double>& cov, unsigned int strategy, unsigned int maxfcn, double toler) const = 0; + virtual FunctionMinimum Minimize(const FCNGradientBase&, const std::vector<double>& par, unsigned int nrow, const std::vector<double>& cov, unsigned int strategy, unsigned int maxfcn, double toler) const = 0; }; diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/FunctionMinimum.h b/ThirdParty/RootMinimizers/inc/Minuit2/FunctionMinimum.h index 4ca895d7487f268528ae9413a927bd3b9f9918ff..552e43743df6f9ace7d4fc7a5b3f3f98c8d6a7fe 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/FunctionMinimum.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/FunctionMinimum.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -13,7 +13,7 @@ #include "Minuit2/BasicFunctionMinimum.h" #ifdef G__DICTIONARY -typedef ROOT::Minuit2::MinimumState MinimumState; +typedef ROOT::Minuit2::MinimumState MinimumState; #endif namespace ROOT { @@ -21,8 +21,8 @@ namespace ROOT { namespace Minuit2 { //______________________________________________________________________________________________ -/** - class holding the full result of the minimization; +/** + class holding the full result of the minimization; both internal and external (MnUserParameterState) representation available for the parameters at the Minimum */ @@ -35,30 +35,30 @@ public: class MnAboveMaxEdm {}; public: - - /// constructor from only MinimumSeed. Minimum is only from seed result not full minimization + + /// constructor from only MinimumSeed. Minimum is only from seed result not full minimization FunctionMinimum(const MinimumSeed& seed, double up) : fData(MnRefCountedPointer<BasicFunctionMinimum>(new BasicFunctionMinimum(seed, up))) {} - - /// constructor at the end of a successfull minimization from seed and vector of states + + /// constructor at the end of a successfull minimization from seed and vector of states FunctionMinimum(const MinimumSeed& seed, const std::vector<MinimumState>& states, double up) : fData(MnRefCountedPointer<BasicFunctionMinimum>(new BasicFunctionMinimum(seed, states, up))) {} - - /// constructor at the end of a failed minimization due to exceeding function call limit + + /// constructor at the end of a failed minimization due to exceeding function call limit FunctionMinimum(const MinimumSeed& seed, const std::vector<MinimumState>& states, double up, MnReachedCallLimit) : fData(MnRefCountedPointer<BasicFunctionMinimum>(new BasicFunctionMinimum(seed, states, up, BasicFunctionMinimum::MnReachedCallLimit()))) {} - + /// constructor at the end of a failed minimization due to edm above maximum value FunctionMinimum(const MinimumSeed& seed, const std::vector<MinimumState>& states, double up, MnAboveMaxEdm) : fData(MnRefCountedPointer<BasicFunctionMinimum>(new BasicFunctionMinimum(seed, states, up, BasicFunctionMinimum::MnAboveMaxEdm()))) {} /// copy constructo FunctionMinimum(const FunctionMinimum& min) : fData(min.fData) {} - + FunctionMinimum& operator=(const FunctionMinimum& min) { fData = min.fData; return *this; } - + ~FunctionMinimum() {} - + // add new state void Add(const MinimumState& state) {fData->Add(state);} @@ -86,8 +86,8 @@ public: const FunctionGradient& Grad() const {return fData->Grad();} double Fval() const {return fData->Fval();} double Edm() const {return fData->Edm();} - int NFcn() const {return fData->NFcn();} - + int NFcn() const {return fData->NFcn();} + double Up() const {return fData->Up();} bool IsValid() const {return fData->IsValid();} bool HasValidParameters() const {return fData->HasValidParameters();} diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/GenericFunction.h b/ThirdParty/RootMinimizers/inc/Minuit2/GenericFunction.h index cd0a0661420df08e53e9797595c900e3805f3a85..2ab29406f63eb2c98860cd172e82d8ba526ef4e6 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/GenericFunction.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/GenericFunction.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -20,7 +20,7 @@ namespace ROOT { //_____________________________________________________________________ -/** +/** Class from which all the other classes, representing functions, inherit. That is why it defines only one method, the operator(), @@ -43,7 +43,7 @@ public: Evaluates the function using the vector containing the input values. - @param x vector of the coordinates (for example the x coordinate for a + @param x vector of the coordinates (for example the x coordinate for a one-dimensional Gaussian) @return the result of the evaluation of the function. diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/GradientCalculator.h b/ThirdParty/RootMinimizers/inc/Minuit2/GradientCalculator.h index b6903311bf759cc4b6e2d951ecc9ab67ad3a0b71..0ca963a9a6aaac012d743e31140c947b7fce5caa 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/GradientCalculator.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/GradientCalculator.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -25,7 +25,7 @@ class FunctionGradient; class GradientCalculator { public: - + virtual ~GradientCalculator() {} virtual FunctionGradient operator()(const MinimumParameters&) const = 0; diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/HessianGradientCalculator.h b/ThirdParty/RootMinimizers/inc/Minuit2/HessianGradientCalculator.h index 2d02665f4333e589a7bb74bcdb0e9554d7d348c2..20ce15bff1e3cb2f94888d994a370c1adfe6509e 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/HessianGradientCalculator.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/HessianGradientCalculator.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -30,13 +30,13 @@ class MnStrategy; */ class HessianGradientCalculator : public GradientCalculator { - + public: - + HessianGradientCalculator(const MnFcn& fcn, const MnUserTransformation& par, const MnStrategy& stra) : fFcn(fcn), fTransformation(par), fStrategy(stra) {} - + virtual ~HessianGradientCalculator() {} virtual FunctionGradient operator()(const MinimumParameters&) const; @@ -47,10 +47,10 @@ public: std::pair<FunctionGradient, MnAlgebraicVector> DeltaGradient(const MinimumParameters&, const FunctionGradient&) const; const MnFcn& Fcn() const {return fFcn;} - const MnUserTransformation& Trafo() const {return fTransformation;} + const MnUserTransformation& Trafo() const {return fTransformation;} const MnMachinePrecision& Precision() const; const MnStrategy& Strategy() const {return fStrategy;} - + unsigned int Ncycle() const; double StepTolerance() const; double GradTolerance() const; @@ -58,7 +58,7 @@ public: private: const MnFcn& fFcn; - const MnUserTransformation& fTransformation; + const MnUserTransformation& fTransformation; const MnStrategy& fStrategy; }; diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/InitialGradientCalculator.h b/ThirdParty/RootMinimizers/inc/Minuit2/InitialGradientCalculator.h index 89f1c25a9368011245304fbe5e054921987ba0c9..f4d129fa04280d065e01fc85090cfa92de32a540 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/InitialGradientCalculator.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/InitialGradientCalculator.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -26,13 +26,13 @@ class MnStrategy; Class to calculate an initial estimate of the gradient */ class InitialGradientCalculator : public GradientCalculator { - + public: - + InitialGradientCalculator(const MnFcn& fcn, const MnUserTransformation& par, const MnStrategy& stra) : fFcn(fcn), fTransformation(par), fStrategy(stra) {}; - + virtual ~InitialGradientCalculator() {} virtual FunctionGradient operator()(const MinimumParameters&) const; @@ -41,7 +41,7 @@ public: const FunctionGradient&) const; const MnFcn& Fcn() const {return fFcn;} - const MnUserTransformation& Trafo() const {return fTransformation;} + const MnUserTransformation& Trafo() const {return fTransformation;} const MnMachinePrecision& Precision() const; const MnStrategy& Strategy() const {return fStrategy;} @@ -52,7 +52,7 @@ public: private: const MnFcn& fFcn; - const MnUserTransformation& fTransformation; + const MnUserTransformation& fTransformation; const MnStrategy& fStrategy; }; diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/LASymMatrix.h b/ThirdParty/RootMinimizers/inc/Minuit2/LASymMatrix.h index 72b724fb9cf4e77b6543c0e3531d0b01e32a4584..73c74fea369446fac41cb76a56f0e44ad2b86bcc 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/LASymMatrix.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/LASymMatrix.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -40,12 +40,12 @@ class LAVector; int Invert ( LASymMatrix & ); /** - Class describing a symmetric matrix of size n. - The size is specified as a run-time argument passed in the - constructor. - The class uses expression templates for the operations and functions. + Class describing a symmetric matrix of size n. + The size is specified as a run-time argument passed in the + constructor. + The class uses expression templates for the operations and functions. Only the independent data are kept in the fdata array of size n*(n+1)/2 - containing the lower triangular data + containing the lower triangular data */ class LASymMatrix { @@ -72,7 +72,7 @@ public: if(fData) StackAllocatorHolder::Get().Deallocate(fData); } - LASymMatrix(const LASymMatrix& v) : + LASymMatrix(const LASymMatrix& v) : fSize(v.size()), fNRow(v.Nrow()), fData((double*)StackAllocatorHolder::Get().Allocate(sizeof(double)*v.size())) { // std::cout<<"LASymMatrix(const LASymMatrix& v)"<<std::endl; memcpy(fData, v.Data(), fSize*sizeof(double)); @@ -88,14 +88,14 @@ public: } template<class T> - LASymMatrix(const ABObj<sym, LASymMatrix, T>& v) : + LASymMatrix(const ABObj<sym, LASymMatrix, T>& v) : fSize(v.Obj().size()), fNRow(v.Obj().Nrow()), fData((double*)StackAllocatorHolder::Get().Allocate(sizeof(double)*v.Obj().size())) { // std::cout<<"LASymMatrix(const ABObj<sym, LASymMatrix, T>& v)"<<std::endl; - //std::cout<<"allocate "<<fSize<<std::endl; + //std::cout<<"allocate "<<fSize<<std::endl; memcpy(fData, v.Obj().Data(), fSize*sizeof(double)); Mndscal(fSize, double(v.f()), fData, 1); //std::cout<<"fData= "<<fData[0]<<" "<<fData[1]<<std::endl; - } + } template<class A, class B, class T> LASymMatrix(const ABObj<sym, ABSum<ABObj<sym, A, T>, ABObj<sym, B, T> >,T>& sum) : fSize(0), fNRow(0), fData(0) { @@ -114,7 +114,7 @@ public: //std::cout<<"(*this)=sum.Obj().B();"<<std::endl; (*this)=sum.Obj().B(); //std::cout<<"(*this)+=sum.Obj().A();"<<std::endl; - (*this)+=sum.Obj().A(); + (*this)+=sum.Obj().A(); //std::cout<<"leaving template<class A, class T> LASymMatrix(const ABObj<sym, ABSum<ABObj<sym, LASymMatrix,.."<<std::endl; } @@ -140,7 +140,7 @@ public: // recursive construction (*this)=sum.Obj().B(); - (*this)+=sum.Obj().A(); + (*this)+=sum.Obj().A(); //std::cout<<"leaving template<class A, class T> LASymMatrix(const ABObj<sym, ABSum<ABObj<sym, LASymMatrix,.."<<std::endl; } @@ -152,7 +152,7 @@ public: // recursive construction (*this)=sum.Obj().B(); - (*this)+=sum.Obj().A(); + (*this)+=sum.Obj().A(); //std::cout<<"leaving template<class A, class T> LASymMatrix(const ABObj<sym, ABSum<ABObj<sym, LASymMatrix,.."<<std::endl; } @@ -208,7 +208,7 @@ public: Outer_prod(*this, m.Obj().Obj().Obj(), m.f()*m.Obj().Obj().f()*m.Obj().Obj().f()); return *this; } - + LASymMatrix& operator*=(double scal) { Mndscal(fSize, scal, fData, 1); return *this; @@ -216,7 +216,7 @@ public: double operator()(unsigned int row, unsigned int col) const { assert(row<fNRow && col < fNRow); - if(row > col) + if(row > col) return fData[col+row*(row+1)/2]; else return fData[row+col*(col+1)/2]; @@ -224,24 +224,24 @@ public: double& operator()(unsigned int row, unsigned int col) { assert(row<fNRow && col < fNRow); - if(row > col) + if(row > col) return fData[col+row*(row+1)/2]; else return fData[row+col*(col+1)/2]; } - + const double* Data() const {return fData;} double* Data() {return fData;} - + unsigned int size() const {return fSize;} unsigned int Nrow() const {return fNRow;} - + unsigned int Ncol() const {return Nrow();} private: - + unsigned int fSize; unsigned int fNRow; double* fData; @@ -274,7 +274,7 @@ public: LASymMatrix tmp(something.Obj()); tmp *= something.f(); assert(fSize == tmp.size()); - memcpy(fData, tmp.Data(), fSize*sizeof(double)); + memcpy(fData, tmp.Data(), fSize*sizeof(double)); } //std::cout<<"template<class A, class T> LASymMatrix& operator=(const ABObj<sym, ABObj<sym, A, T>, T>& something)"<<std::endl; return *this; @@ -301,7 +301,7 @@ public: template<class A, class T> LASymMatrix& operator=(const ABObj<sym, ABSum<ABObj<sym, LASymMatrix, T>, ABObj<sym, A, T> >,T>& sum) { //std::cout<<"template<class A, class T> LASymMatrix& operator=(const ABObj<sym, ABSum<ABObj<sym, LASymMatrix, T>, ABObj<sym, A, T> >,T>& sum)"<<std::endl; - + if(fSize == 0 && fData == 0) { //std::cout<<"fSize == 0 && fData == 0"<<std::endl; (*this) = sum.Obj().B(); diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/LAVector.h b/ThirdParty/RootMinimizers/inc/Minuit2/LAVector.h index 4c0759230e907ee23b9669b09ca831c32cf9b1d8..74c55004c743cf36cbc63329c2847e8d580234a8 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/LAVector.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/LAVector.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -56,7 +56,7 @@ public: if(fData) StackAllocatorHolder::Get().Deallocate(fData); } - LAVector(const LAVector& v) : + LAVector(const LAVector& v) : fSize(v.size()), fData((double*)StackAllocatorHolder::Get().Allocate(sizeof(double)*v.size())) { // std::cout<<"LAVector(const LAVector& v)"<<std::endl; memcpy(fData, v.Data(), fSize*sizeof(double)); @@ -72,14 +72,14 @@ public: } template<class T> - LAVector(const ABObj<vec, LAVector, T>& v) : + LAVector(const ABObj<vec, LAVector, T>& v) : fSize(v.Obj().size()), fData((double*)StackAllocatorHolder::Get().Allocate(sizeof(double)*v.Obj().size())) { // std::cout<<"LAVector(const ABObj<LAVector, T>& v)"<<std::endl; -// std::cout<<"allocate "<<fSize<<std::endl; +// std::cout<<"allocate "<<fSize<<std::endl; memcpy(fData, v.Obj().Data(), fSize*sizeof(T)); (*this) *= T(v.f()); // std::cout<<"fData= "<<fData[0]<<" "<<fData[1]<<std::endl; - } + } template<class A, class B, class T> LAVector(const ABObj<vec, ABSum<ABObj<vec, A, T>, ABObj<vec, B, T> >,T>& sum) : fSize(0), fData(0) { @@ -97,7 +97,7 @@ public: // std::cout<<"(*this)=sum.Obj().B();"<<std::endl; (*this) = sum.Obj().B(); // std::cout<<"(*this)+=sum.Obj().A();"<<std::endl; - (*this) += sum.Obj().A(); + (*this) += sum.Obj().A(); (*this) *= double(sum.f()); // std::cout<<"leaving template<class A, class T> LAVector(const ABObj<ABSum<ABObj<LAVector,.."<<std::endl; } @@ -108,7 +108,7 @@ public: (*this) = something.Obj(); (*this) *= something.f(); } - + // template<class T> LAVector(const ABObj<vec, ABProd<ABObj<sym, LASymMatrix, T>, ABObj<vec, LAVector, T> >, T>& prod) : fSize(prod.Obj().B().Obj().size()), fData((double*)StackAllocatorHolder::Get().Allocate(sizeof(double)*prod.Obj().B().Obj().size())) { @@ -122,7 +122,7 @@ public: LAVector(const ABObj<vec, ABSum<ABObj<vec, ABProd<ABObj<sym, LASymMatrix, T>, ABObj<vec, LAVector, T> >, T>, ABObj<vec, LAVector, T> >, T>& prod) : fSize(0), fData(0) { (*this) = prod.Obj().B(); (*this) += prod.Obj().A(); - (*this) *= double(prod.f()); + (*this) *= double(prod.f()); } // @@ -165,7 +165,7 @@ public: Mndspmv("U", fSize, prod.f()*prod.Obj().A().f()*prod.Obj().B().f(), prod.Obj().A().Obj().Data(), prod.Obj().B().Data(), 1, 1., fData, 1); return *this; } - + LAVector& operator*=(double scal) { Mndscal(fSize, scal, fData, 1); return *this; @@ -190,15 +190,15 @@ public: assert(i<fSize); return fData[i]; } - + const double* Data() const {return fData;} double* Data() {return fData;} - + unsigned int size() const {return fSize;} - + private: - + unsigned int fSize; double* fData; @@ -226,7 +226,7 @@ public: } else { LAVector tmp(something.Obj()); assert(fSize == tmp.size()); - memcpy(fData, tmp.Data(), fSize*sizeof(double)); + memcpy(fData, tmp.Data(), fSize*sizeof(double)); } (*this) *= something.f(); return *this; @@ -268,12 +268,12 @@ public: if(fSize == 0 && fData == 0) { fSize = prod.Obj().B().Obj().size(); fData = (double*)StackAllocatorHolder::Get().Allocate(sizeof(double)*fSize); - Mndspmv("U", fSize, double(prod.f()*prod.Obj().A().f()*prod.Obj().B().f()), prod.Obj().A().Obj().Data(), prod.Obj().B().Obj().Data(), 1, 0., fData, 1); + Mndspmv("U", fSize, double(prod.f()*prod.Obj().A().f()*prod.Obj().B().f()), prod.Obj().A().Obj().Data(), prod.Obj().B().Obj().Data(), 1, 0., fData, 1); } else { LAVector tmp(prod.Obj().B()); assert(fSize == tmp.size()); Mndspmv("U", fSize, double(prod.f()*prod.Obj().A().f()), prod.Obj().A().Obj().Data(), tmp.Data(), 1, 0., fData, 1); - } + } return *this; } diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/LaInverse.h b/ThirdParty/RootMinimizers/inc/Minuit2/LaInverse.h index 2c2c4d3a3062332236972ee5ded607f5216cbb49..0911e00f7102bcc290b48de913ef72e961ae50a5 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/LaInverse.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/LaInverse.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -11,7 +11,7 @@ #define ROOT_Minuit2_LaInverse /** LAPACK Algebra - specialize the Invert function for LASymMatrix + specialize the Invert function for LASymMatrix */ #include "Minuit2/MatrixInverse.h" diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/LaOuterProduct.h b/ThirdParty/RootMinimizers/inc/Minuit2/LaOuterProduct.h index e4bdfb210aa63c400b8d25f3e3912188cd364822..8d5468ed6f948a410c50ff54ba58bc3763c7eaff 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/LaOuterProduct.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/LaOuterProduct.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -42,7 +42,7 @@ inline ABObj<sym, VectorOuterProduct<ABObj<vec, LAVector, T>, T>, T> operator/(c // std::cout<<"ABObj<sym, VectorOuterProduct<ABObj<vec, LAVector, T>, T>, T> operator/(const ABObj<sym, VectorOuterProduct<ABObj<vec, LAVector, T>, T>, T>& obj, T f)"<<std::endl; return ABObj<sym, VectorOuterProduct<ABObj<vec, LAVector, T>, T>, T>(obj.Obj(), obj.f()/f); } - + // -outer template<class T> inline ABObj<sym, VectorOuterProduct<ABObj<vec, LAVector, T>, T>, T> operator-(const ABObj<sym, VectorOuterProduct<ABObj<vec, LAVector, T>, T>, T>& obj) { diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/LaProd.h b/ThirdParty/RootMinimizers/inc/Minuit2/LaProd.h index aa8faba889ad19141fa196eb86169d0abd28c75d..a64d2f7c90b2cc36b11923c61149b1adbbadd806 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/LaProd.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/LaProd.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/LaSum.h b/ThirdParty/RootMinimizers/inc/Minuit2/LaSum.h index 095bb9a800dc40e26c356dae8836be0dacd24655..70dd4991b92e57e3a71db1e234ba3572c9ff31f7 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/LaSum.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/LaSum.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MPIProcess.h b/ThirdParty/RootMinimizers/inc/Minuit2/MPIProcess.h index 8ec5053e629c3fe8c7b334bfd69f522b0bac76c2..7d7960b49e9a5de6ab90dfbadf4511e7aab956ea 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MPIProcess.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MPIProcess.h @@ -27,7 +27,7 @@ namespace Minuit2 { class MPITerminate { public: - ~MPITerminate() { + ~MPITerminate() { #ifdef MPIPROC if (MPI::Is_initialized() && !(MPI::Is_finalized())) { std::cout << "Info --> MPITerminate:: End MPI on #" @@ -53,7 +53,7 @@ namespace Minuit2 { inline unsigned int NumElements4Job(unsigned int rank) const { return NumElements4JobIn()+((rank<NumElements4JobOut()) ? 1 : 0); } - inline unsigned int StartElementIndex() const + inline unsigned int StartElementIndex() const { return ((fRank<NumElements4JobOut()) ? (fRank*NumElements4Job(fRank)) : (fNelements-(fSize-fRank)*NumElements4Job(fRank))); } @@ -63,16 +63,16 @@ namespace Minuit2 { inline unsigned int GetMPISize() const { return fSize; } inline unsigned int GetMPIRank() const { return fRank; } - bool SyncVector(ROOT::Minuit2::MnAlgebraicVector &mnvector); - bool SyncSymMatrixOffDiagonal(ROOT::Minuit2::MnAlgebraicSymMatrix &mnmatrix); + bool SyncVector(ROOT::Minuit2::MnAlgebraicVector &mnvector); + bool SyncSymMatrixOffDiagonal(ROOT::Minuit2::MnAlgebraicSymMatrix &mnmatrix); static unsigned int GetMPIGlobalRank() { StartMPI(); return fgGlobalRank; } static unsigned int GetMPIGlobalSize() { StartMPI(); return fgGlobalSize; } static inline void StartMPI() { -#ifdef MPIPROC - if (!(MPI::Is_initialized())) { - MPI::Init(); - std::cout << "Info --> MPIProcess::StartMPI: Start MPI on #" +#ifdef MPIPROC + if (!(MPI::Is_initialized())) { + MPI::Init(); + std::cout << "Info --> MPIProcess::StartMPI: Start MPI on #" << MPI::COMM_WORLD.Get_rank() << " processor" << std::endl; } @@ -81,13 +81,13 @@ namespace Minuit2 { #endif } - static void TerminateMPI() { + static void TerminateMPI() { #ifdef MPIPROC if (fgCommunicators[0]!=0 && fgCommunicators[1]!=0) { delete fgCommunicators[0]; fgCommunicators[0] = 0; fgIndecesComm[0] = 0; delete fgCommunicators[1]; fgCommunicators[1] = 0; fgIndecesComm[1] = 0; } - + MPITerminate(); #endif @@ -115,10 +115,10 @@ namespace Minuit2 { private: unsigned int fNelements; unsigned int fSize; - unsigned int fRank; + unsigned int fRank; static unsigned int fgGlobalSize; - static unsigned int fgGlobalRank; + static unsigned int fgGlobalRank; static unsigned int fgCartSizeX; static unsigned int fgCartSizeY; diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MatrixInverse.h b/ThirdParty/RootMinimizers/inc/Minuit2/MatrixInverse.h index ad357400650195aadfd3a281e97f46abb2dedd1b..ae306fd47eee23ba7a0eb0759ce7f5d1f1c5e774 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MatrixInverse.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MatrixInverse.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MinimumBuilder.h b/ThirdParty/RootMinimizers/inc/Minuit2/MinimumBuilder.h index bbdaaccdbb2d71b7f769d5625a35451d803bcc66..6c9b477ccb4dde4e510a7774d5724c5f376b8f09 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MinimumBuilder.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MinimumBuilder.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -29,7 +29,7 @@ class MnStrategy; class MinimumBuilder { public: - + MinimumBuilder(); virtual ~MinimumBuilder() {} @@ -51,12 +51,12 @@ public: } void TraceIteration(int iter, const MinimumState & state) const { - if (fTracer) (*fTracer)(iter, state); + if (fTracer) (*fTracer)(iter, state); } -private: +private: - int fPrintLevel; + int fPrintLevel; int fStorageLevel; MnTraceObject * fTracer; //! tracer object (it is managed by user) diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MinimumError.h b/ThirdParty/RootMinimizers/inc/Minuit2/MinimumError.h index af81b25d4f742e369d195d1f5e43a3d7a11f5810..71ea65e486630fdcf4c12d1f841ef27648376bbd 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MinimumError.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MinimumError.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -17,8 +17,8 @@ namespace ROOT { namespace Minuit2 { - -/** MinimumError keeps the inv. 2nd derivative (inv. Hessian) used for + +/** MinimumError keeps the inv. 2nd derivative (inv. Hessian) used for calculating the Parameter step size (-V*g) and for the covariance Update (ErrorUpdator). The covariance matrix is equal to twice the inv. Hessian. */ @@ -33,11 +33,11 @@ public: class MnInvertFailed {}; public: - + MinimumError(unsigned int n) : fData(MnRefCountedPointer<BasicMinimumError>(new BasicMinimumError(n))) {} - + MinimumError(const MnAlgebraicSymMatrix& mat, double dcov) : fData(MnRefCountedPointer<BasicMinimumError>(new BasicMinimumError(mat, dcov))) {} - + MinimumError(const MnAlgebraicSymMatrix& mat, MnHesseFailed) : fData(MnRefCountedPointer<BasicMinimumError>(new BasicMinimumError(mat, BasicMinimumError::MnHesseFailed()))) {} MinimumError(const MnAlgebraicSymMatrix& mat, MnMadePosDef) : fData(MnRefCountedPointer<BasicMinimumError>(new BasicMinimumError(mat, BasicMinimumError::MnMadePosDef()))) {} diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MinimumErrorUpdator.h b/ThirdParty/RootMinimizers/inc/Minuit2/MinimumErrorUpdator.h index f97cd78d197db87c7b3ac61ef58db0817be6be27..8951525ccc3c5b19142c4a2d62f33b1027aafb45 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MinimumErrorUpdator.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MinimumErrorUpdator.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MinimumParameters.h b/ThirdParty/RootMinimizers/inc/Minuit2/MinimumParameters.h index 6d82b36a140066d72e7eb6ce20805d957bfe913c..c795612d01e3b8bffd0f875f7224dc7c6255c194 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MinimumParameters.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MinimumParameters.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -22,16 +22,16 @@ class MinimumParameters { public: - MinimumParameters(unsigned int n) : + MinimumParameters(unsigned int n) : fData(MnRefCountedPointer<BasicMinimumParameters>(new BasicMinimumParameters(n))) {} /** takes the Parameter vector */ - MinimumParameters(const MnAlgebraicVector& avec, double fval) : + MinimumParameters(const MnAlgebraicVector& avec, double fval) : fData(MnRefCountedPointer<BasicMinimumParameters>(new BasicMinimumParameters(avec, fval))) {} - + /** takes the Parameter vector plus step size x1 - x0 = dirin */ MinimumParameters(const MnAlgebraicVector& avec, const MnAlgebraicVector& dirin, double fval) : fData(MnRefCountedPointer<BasicMinimumParameters>(new BasicMinimumParameters(avec, dirin, fval))) {} - + ~MinimumParameters() {} MinimumParameters(const MinimumParameters& par) : fData(par.fData) {} diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MinimumSeed.h b/ThirdParty/RootMinimizers/inc/Minuit2/MinimumSeed.h index 617e540148bb2e314c57b588c87a4286317701aa..481c9a6016c47c1061bca1a73eebee528e64b671 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MinimumSeed.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MinimumSeed.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -24,20 +24,20 @@ class MinimumError; class FunctionGradient; class MnUserTransformation; -/** MinimumSeed contains the starting values for the minimization produced +/** MinimumSeed contains the starting values for the minimization produced by the SeedGenerator. */ class MinimumSeed { public: - + MinimumSeed(const MinimumState& st, const MnUserTransformation& trafo) : fData(MnRefCountedPointer<BasicMinimumSeed>(new BasicMinimumSeed(st, trafo))) {} - + ~MinimumSeed() {} MinimumSeed(const MinimumSeed& seed) : fData(seed.fData) {} - + MinimumSeed& operator=(const MinimumSeed& seed) { fData = seed.fData; return *this; diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MinimumSeedGenerator.h b/ThirdParty/RootMinimizers/inc/Minuit2/MinimumSeedGenerator.h index 9031d319bfdd5299e9566118048124ead0856ebf..ec78dc38ec0df2ee9551e69ddd3df68e4f4405a7 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MinimumSeedGenerator.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MinimumSeedGenerator.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -22,7 +22,7 @@ class MnUserParameterState; class MnStrategy; class AnalyticalGradientCalculator; -/** base class for seed generators (starting values); the seed generator +/** base class for seed generators (starting values); the seed generator prepares initial starting values from the input (MnUserParameterState) for the minimization; */ diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MinimumState.h b/ThirdParty/RootMinimizers/inc/Minuit2/MinimumState.h index 0730d1ea8c19b02017e54d7e92937bcf88c1d657..fa528ce05abb77a0849810df549265536a47798d 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MinimumState.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MinimumState.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -22,29 +22,29 @@ class MinimumParameters; class MinimumError; class FunctionGradient; -/** MinimumState keeps the information (position, Gradient, 2nd deriv, etc) +/** MinimumState keeps the information (position, Gradient, 2nd deriv, etc) after one minimization step (usually in MinimumBuilder). */ class MinimumState { - + public: - + /** invalid state */ - MinimumState(unsigned int n) : + MinimumState(unsigned int n) : fData(MnRefCountedPointer<BasicMinimumState>(new BasicMinimumState(n))) {} /** state with parameters only (from stepping methods like Simplex, Scan) */ - MinimumState(const MinimumParameters& states, double edm, int nfcn) : + MinimumState(const MinimumParameters& states, double edm, int nfcn) : fData(MnRefCountedPointer<BasicMinimumState>(new BasicMinimumState(states, edm, nfcn))) {} - - /** state with parameters, Gradient and covariance (from Gradient methods + + /** state with parameters, Gradient and covariance (from Gradient methods such as Migrad) */ - MinimumState(const MinimumParameters& states, const MinimumError& err, + MinimumState(const MinimumParameters& states, const MinimumError& err, const FunctionGradient& grad, double edm, int nfcn) : fData(MnRefCountedPointer<BasicMinimumState>(new BasicMinimumState(states, err, grad, edm, nfcn))) {} - + ~MinimumState() {} - + MinimumState(const MinimumState& state) : fData(state.fData) {} MinimumState& operator=(const MinimumState& state) { @@ -63,12 +63,12 @@ public: int NFcn() const {return fData->NFcn();} bool IsValid() const {return fData->IsValid();} - + bool HasParameters() const {return fData->HasParameters();} bool HasCovariance() const {return fData->HasCovariance();} private: - + MnRefCountedPointer<BasicMinimumState> fData; }; diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MinosError.h b/ThirdParty/RootMinimizers/inc/Minuit2/MinosError.h index 0c11312223b6b7ce9970636643dff4e9fcd446c7..2b695ad5fe66d672e460295c10e993079d305c87 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MinosError.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MinosError.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -19,7 +19,7 @@ namespace ROOT { //____________________________________________________________________________________ /** - Class holding the result of Minos (lower and upper values) for a specific parameter + Class holding the result of Minos (lower and upper values) for a specific parameter */ class MinosError { @@ -27,7 +27,7 @@ class MinosError { public: MinosError() : fParameter(0), fMinValue(0.), fUpper(MnCross()), fLower(MnCross()) {} - + MinosError(unsigned int par, double min, const MnCross& low, const MnCross& up) : fParameter(par), fMinValue(min), fUpper(up), fLower(low) {} ~MinosError() {} @@ -50,7 +50,7 @@ public: return -1.*LowerState().Error(Parameter())*(1. + fLower.Value()); } double Upper() const { - if ( AtUpperLimit() ) return UpperState().Parameter( Parameter() ).UpperLimit() - fMinValue; + if ( AtUpperLimit() ) return UpperState().Parameter( Parameter() ).UpperLimit() - fMinValue; return UpperState().Error(Parameter())*(1. + fUpper.Value()); } unsigned int Parameter() const {return fParameter;} @@ -69,7 +69,7 @@ public: double Min() const {return fMinValue;} private: - + unsigned int fParameter; double fMinValue; MnCross fUpper; diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/Minuit2Minimizer.h b/ThirdParty/RootMinimizers/inc/Minuit2/Minuit2Minimizer.h index 6951689afe124c034427cd684af3ec8f8b3f0fa0..629751a1d3f896799e3228fc6097688deb5c834a 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/Minuit2Minimizer.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/Minuit2Minimizer.h @@ -27,107 +27,107 @@ -namespace ROOT { +namespace ROOT { - namespace Minuit2 { + namespace Minuit2 { - class ModularFunctionMinimizer; - class FCNBase; + class ModularFunctionMinimizer; + class FCNBase; class FunctionMinimum; class MnTraceObject; // enumeration specifying the type of Minuit2 minimizers - enum EMinimizerType { - kMigrad, - kSimplex, - kCombined, + enum EMinimizerType { + kMigrad, + kSimplex, + kCombined, kScan, kFumili }; } - namespace Minuit2 { + namespace Minuit2 { //_____________________________________________________________________________________________________ -/** - Minuit2Minimizer class implementing the ROOT::Math::Minimizer interface for - Minuit2 minimization algorithm. +/** + Minuit2Minimizer class implementing the ROOT::Math::Minimizer interface for + Minuit2 minimization algorithm. In ROOT it can be instantiated using the plug-in manager (plug-in "Minuit2") - Using a string (used by the plugin manager) or via an enumeration - an one can set all the possible minimization algorithms (Migrad, Simplex, Combined, Scan and Fumili). -*/ + Using a string (used by the plugin manager) or via an enumeration + an one can set all the possible minimization algorithms (Migrad, Simplex, Combined, Scan and Fumili). +*/ class Minuit2Minimizer : public ROOT::Math::Minimizer { -public: +public: - /** + /** Default constructor - */ - Minuit2Minimizer (ROOT::Minuit2::EMinimizerType type = ROOT::Minuit2::kMigrad); + */ + Minuit2Minimizer (ROOT::Minuit2::EMinimizerType type = ROOT::Minuit2::kMigrad); - /** - Constructor with a char (used by PM) - */ - Minuit2Minimizer (const char * type); + /** + Constructor with a char (used by PM) + */ + Minuit2Minimizer (const char * type); - /** + /** Destructor (no operations) - */ - virtual ~Minuit2Minimizer (); + */ + virtual ~Minuit2Minimizer (); private: // usually copying is non trivial, so we make this unaccessible - /** + /** Copy constructor - */ - Minuit2Minimizer(const Minuit2Minimizer &); + */ + Minuit2Minimizer(const Minuit2Minimizer &); - /** + /** Assignment operator - */ - Minuit2Minimizer & operator = (const Minuit2Minimizer & rhs); + */ + Minuit2Minimizer & operator = (const Minuit2Minimizer & rhs); -public: +public: // clear resources (parameters) for consecutives minimizations virtual void Clear(); /// set the function to minimize - virtual void SetFunction(const ROOT::Math::IMultiGenFunction & func); + virtual void SetFunction(const ROOT::Math::IMultiGenFunction & func); /// set gradient the function to minimize - virtual void SetFunction(const ROOT::Math::IMultiGradFunction & func); + virtual void SetFunction(const ROOT::Math::IMultiGradFunction & func); - /// set free variable - virtual bool SetVariable(unsigned int ivar, const std::string & name, double val, double step); + /// set free variable + virtual bool SetVariable(unsigned int ivar, const std::string & name, double val, double step); /// set lower limit variable (override if minimizer supports them ) virtual bool SetLowerLimitedVariable(unsigned int ivar , const std::string & name , double val , double step , double lower ); /// set upper limit variable (override if minimizer supports them ) - virtual bool SetUpperLimitedVariable(unsigned int ivar , const std::string & name , double val , double step , double upper ); + virtual bool SetUpperLimitedVariable(unsigned int ivar , const std::string & name , double val , double step , double upper ); /// set upper/lower limited variable (override if minimizer supports them ) - virtual bool SetLimitedVariable(unsigned int ivar , const std::string & name , double val , double step , double /* lower */, double /* upper */); + virtual bool SetLimitedVariable(unsigned int ivar , const std::string & name , double val , double step , double /* lower */, double /* upper */); /// set fixed variable (override if minimizer supports them ) - virtual bool SetFixedVariable(unsigned int /* ivar */, const std::string & /* name */, double /* val */); + virtual bool SetFixedVariable(unsigned int /* ivar */, const std::string & /* name */, double /* val */); /// set variable virtual bool SetVariableValue(unsigned int ivar, double val); // set variable values virtual bool SetVariableValues(const double * val); /// set the step size of an already existing variable virtual bool SetVariableStepSize(unsigned int ivar, double step ); - /// set the lower-limit of an already existing variable + /// set the lower-limit of an already existing variable virtual bool SetVariableLowerLimit(unsigned int ivar, double lower); - /// set the upper-limit of an already existing variable + /// set the upper-limit of an already existing variable virtual bool SetVariableUpperLimit(unsigned int ivar, double upper); - /// set the limits of an already existing variable - virtual bool SetVariableLimits(unsigned int ivar, double lower, double upper); + /// set the limits of an already existing variable + virtual bool SetVariableLimits(unsigned int ivar, double lower, double upper); /// fix an existing variable virtual bool FixVariable(unsigned int ivar); /// release an existing variable virtual bool ReleaseVariable(unsigned int ivar); /// query if an existing variable is fixed (i.e. considered constant in the minimization) - /// note that by default all variables are not fixed + /// note that by default all variables are not fixed virtual bool IsFixedVariable(unsigned int ivar) const; /// get variable settings in a variable object (like ROOT::Fit::ParamsSettings) virtual bool GetVariableSettings(unsigned int ivar, ROOT::Fit::ParameterSettings & varObj) const; @@ -137,86 +137,86 @@ public: /// return -1 if variable is not found virtual int VariableIndex(const std::string & name) const; - /** - method to perform the minimization. - Return false in case the minimization did not converge. In this case a - status code different than zero is set - (retrieved by the derived method Minimizer::Status() )" - + /** + method to perform the minimization. + Return false in case the minimization did not converge. In this case a + status code different than zero is set + (retrieved by the derived method Minimizer::Status() )" + status = 1 : Covariance was made pos defined status = 2 : Hesse is invalid - status = 3 : Edm is above max + status = 3 : Edm is above max status = 4 : Reached call limit - status = 5 : Any other failure + status = 5 : Any other failure */ - virtual bool Minimize(); + virtual bool Minimize(); /// return minimum function value - virtual double MinValue() const { return fState.Fval(); } + virtual double MinValue() const { return fState.Fval(); } /// return expected distance reached from the minimum virtual double Edm() const { return fState.Edm(); } - /// return pointer to X values at the minimum - virtual const double * X() const; - - /// return pointer to gradient values at the minimum - virtual const double * MinGradient() const { return 0; } // not available in Minuit2 + /// return pointer to X values at the minimum + virtual const double * X() const; - /// number of function calls to reach the minimum - virtual unsigned int NCalls() const { return fState.NFcn(); } + /// return pointer to gradient values at the minimum + virtual const double * MinGradient() const { return 0; } // not available in Minuit2 - /// this is <= Function().NDim() which is the total - /// number of variables (free+ constrained ones) - virtual unsigned int NDim() const { return fDim; } + /// number of function calls to reach the minimum + virtual unsigned int NCalls() const { return fState.NFcn(); } - /// number of free variables (real dimension of the problem) - /// this is <= Function().NDim() which is the total - virtual unsigned int NFree() const { return fState.VariableParameters(); } + /// this is <= Function().NDim() which is the total + /// number of variables (free+ constrained ones) + virtual unsigned int NDim() const { return fDim; } + + /// number of free variables (real dimension of the problem) + /// this is <= Function().NDim() which is the total + virtual unsigned int NFree() const { return fState.VariableParameters(); } /// minimizer provides error and error matrix - virtual bool ProvidesError() const { return true; } + virtual bool ProvidesError() const { return true; } - /// return errors at the minimum - virtual const double * Errors() const; + /// return errors at the minimum + virtual const double * Errors() const; - /** - return covariance matrix elements + /** + return covariance matrix elements if the variable is fixed or const the value is zero - The ordering of the variables is the same as in errors and parameter value. - This is different from the direct interface of Minuit2 or TMinuit where the + The ordering of the variables is the same as in errors and parameter value. + This is different from the direct interface of Minuit2 or TMinuit where the values were obtained only to variable parameters - */ - virtual double CovMatrix(unsigned int i, unsigned int j) const; + */ + virtual double CovMatrix(unsigned int i, unsigned int j) const; - /** - Fill the passed array with the covariance matrix elements - if the variable is fixed or const the value is zero. + /** + Fill the passed array with the covariance matrix elements + if the variable is fixed or const the value is zero. The array will be filled as cov[i *ndim + j] - The ordering of the variables is the same as in errors and parameter value. - This is different from the direct interface of Minuit2 or TMinuit where the + The ordering of the variables is the same as in errors and parameter value. + This is different from the direct interface of Minuit2 or TMinuit where the values were obtained only to variable parameters - */ - virtual bool GetCovMatrix(double * cov) const; + */ + virtual bool GetCovMatrix(double * cov) const; - /** - Fill the passed array with the Hessian matrix elements - The Hessian matrix is the matrix of the second derivatives + /** + Fill the passed array with the Hessian matrix elements + The Hessian matrix is the matrix of the second derivatives and is the inverse of the covariance matrix - If the variable is fixed or const the values for that variables are zero. + If the variable is fixed or const the values for that variables are zero. The array will be filled as h[i *ndim + j] - */ - virtual bool GetHessianMatrix(double * h) const; + */ + virtual bool GetHessianMatrix(double * h) const; /** - return the status of the covariance matrix - status = -1 : not available (inversion failed or Hesse failed) + return the status of the covariance matrix + status = -1 : not available (inversion failed or Hesse failed) status = 0 : available but not positive defined status = 1 : covariance only approximate - status = 2 : full matrix but forced pos def - status = 3 : full accurate matrix + status = 2 : full matrix but forced pos def + status = 3 : full accurate matrix */ virtual int CovMatrixStatus() const; @@ -224,11 +224,11 @@ public: return correlation coefficient between variable i and j. If the variable is fixed or const the return value is zero */ - virtual double Correlation(unsigned int i, unsigned int j ) const; + virtual double Correlation(unsigned int i, unsigned int j ) const; /** - get global correlation coefficient for the variable i. This is a number between zero and one which gives - the correlation between the i-th variable and that linear combination of all other variables which + get global correlation coefficient for the variable i. This is a number between zero and one which gives + the correlation between the i-th variable and that linear combination of all other variables which is most strongly correlated with i. If the variable is fixed or const the return value is zero */ @@ -237,48 +237,48 @@ public: /** get the minos error for parameter i, return false if Minos failed A minimizaiton must be performed befre, return false if no minimization has been done - In case of Minos failed the status error is updated as following + In case of Minos failed the status error is updated as following status += 10 * minosStatus where the minos status is: status = 1 : maximum number of function calls exceeded when running for lower error status = 2 : maximum number of function calls exceeded when running for upper error status = 3 : new minimum found when running for lower error status = 4 : new minimum found when running for upper error - status = 5 : any other failure + status = 5 : any other failure */ - virtual bool GetMinosError(unsigned int i, double & errLow, double & errUp, int = 0); + virtual bool GetMinosError(unsigned int i, double & errLow, double & errUp, int = 0); /** - scan a parameter i around the minimum. A minimization must have been done before, + scan a parameter i around the minimum. A minimization must have been done before, return false if it is not the case */ - virtual bool Scan(unsigned int i, unsigned int & nstep, double * x, double * y, double xmin = 0, double xmax = 0); + virtual bool Scan(unsigned int i, unsigned int & nstep, double * x, double * y, double xmin = 0, double xmax = 0); /** find the contour points (xi,xj) of the function for parameter i and j around the minimum The contour will be find for value of the function = Min + ErrorUp(); */ - virtual bool Contour(unsigned int i, unsigned int j, unsigned int & npoints, double *xi, double *xj); + virtual bool Contour(unsigned int i, unsigned int j, unsigned int & npoints, double *xi, double *xj); + - /** perform a full calculation of the Hessian matrix for error calculation - If a valid minimum exists the calculation is done on the minimum point otherwise is performed + If a valid minimum exists the calculation is done on the minimum point otherwise is performed in the current set values of parameters Status code of minimizer is updated according to the following convention (in case Hesse failed) - status += 100*hesseStatus where hesse status is: + status += 100*hesseStatus where hesse status is: status = 1 : hesse failed status = 2 : matrix inversion failed - status = 3 : matrix is not pos defined + status = 3 : matrix is not pos defined */ virtual bool Hesse(); /// return reference to the objective function - ///virtual const ROOT::Math::IGenFunction & Function() const; + ///virtual const ROOT::Math::IGenFunction & Function() const; /// print result of minimization - virtual void PrintResults(); + virtual void PrintResults(); /// set an object to trace operation for each iteration /// The object muust implement operator() (unsigned int, MinimumState & state) @@ -286,30 +286,30 @@ public: /// set storage level = 1 : store all iteration states (default) /// = 0 : store only first and last state to save memory - void SetStorageLevel(int level); - + void SetStorageLevel(int level); + /// return the minimizer state (containing values, step size , etc..) const ROOT::Minuit2::MnUserParameterState & State() { return fState; } -protected: - +protected: + // protected function for accessing the internal Minuit2 object. Needed for derived classes - virtual const ROOT::Minuit2::ModularFunctionMinimizer * GetMinimizer() const { return fMinimizer; } + virtual const ROOT::Minuit2::ModularFunctionMinimizer * GetMinimizer() const { return fMinimizer; } - virtual void SetMinimizer( ROOT::Minuit2::ModularFunctionMinimizer * m) { fMinimizer = m; } + virtual void SetMinimizer( ROOT::Minuit2::ModularFunctionMinimizer * m) { fMinimizer = m; } void SetMinimizerType( ROOT::Minuit2::EMinimizerType type); - virtual const ROOT::Minuit2::FCNBase * GetFCN() const { return fMinuitFCN; } + virtual const ROOT::Minuit2::FCNBase * GetFCN() const { return fMinuitFCN; } + + /// examine the minimum result + bool ExamineMinimum(const ROOT::Minuit2::FunctionMinimum & min); - /// examine the minimum result - bool ExamineMinimum(const ROOT::Minuit2::FunctionMinimum & min); +private: -private: - - unsigned int fDim; // dimension of the function to be minimized - bool fUseFumili; + unsigned int fDim; // dimension of the function to be minimized + bool fUseFumili; ROOT::Minuit2::MnUserParameterState fState; // std::vector<ROOT::Minuit2::MinosError> fMinosErrors; @@ -319,7 +319,7 @@ private: mutable std::vector<double> fValues; mutable std::vector<double> fErrors; -}; +}; } // end namespace Fit diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MinuitParameter.h b/ThirdParty/RootMinimizers/inc/Minuit2/MinuitParameter.h index 486b4bf91eaefac0bec9d99c6a3fc1c91d595fd2..b5d09c8496a138525e79dbf2b91d3c765e12a1c2 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MinuitParameter.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MinuitParameter.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -13,21 +13,21 @@ #include <algorithm> #include <memory> #include <cassert> -#include <string> +#include <string> namespace ROOT { namespace Minuit2 { //____________________________________________________________________________ -/** - class for the individual Minuit Parameter with Name and number; +/** + class for the individual Minuit Parameter with Name and number; contains the input numbers for the minimization or the output result from minimization; - possible interactions: Fix/release, set/remove limits, set Value/error; + possible interactions: Fix/release, set/remove limits, set Value/error; - From version 5.20: use string to store the name to avoid limitation of - name length of 20 characters + From version 5.20: use string to store the name to avoid limitation of + name length of 20 characters */ class MinuitParameter { @@ -35,32 +35,32 @@ class MinuitParameter { public: //default constructor standard with value/error = 0 - MinuitParameter() : - fNum(0), fValue(0), fError(0.), fConst(false), fFix(false), + MinuitParameter() : + fNum(0), fValue(0), fError(0.), fConst(false), fFix(false), fLoLimit(0.), fUpLimit(0.), fLoLimValid(false), fUpLimValid(false), fName("") {} - + //constructor for constant Parameter - MinuitParameter(unsigned int num, const std::string & name, double val) : - fNum(num), fValue(val), fError(0.), fConst(true), fFix(false), + MinuitParameter(unsigned int num, const std::string & name, double val) : + fNum(num), fValue(val), fError(0.), fConst(true), fFix(false), fLoLimit(0.), fUpLimit(0.), fLoLimValid(false), fUpLimValid(false), fName(name) {} - + //constructor for standard Parameter MinuitParameter(unsigned int num, const std::string & name, double val, double err) : - fNum(num), fValue(val), fError(err), fConst(false), fFix(false), + fNum(num), fValue(val), fError(err), fConst(false), fFix(false), fLoLimit(0.), fUpLimit(0.), fLoLimValid(false), fUpLimValid(false), fName(name) {} - + //constructor for limited Parameter - MinuitParameter(unsigned int num, const std::string & name, double val, double err, - double min, double max) : - fNum(num),fValue(val), fError(err), fConst(false), fFix(false), - fLoLimit(min), fUpLimit(max), fLoLimValid(true), fUpLimValid(true), - fName(name) + MinuitParameter(unsigned int num, const std::string & name, double val, double err, + double min, double max) : + fNum(num),fValue(val), fError(err), fConst(false), fFix(false), + fLoLimit(min), fUpLimit(max), fLoLimValid(true), fUpLimValid(true), + fName(name) { assert(min != max); if(min > max) { @@ -71,14 +71,14 @@ public: ~MinuitParameter() {} - MinuitParameter(const MinuitParameter& par) : + MinuitParameter(const MinuitParameter& par) : fNum(par.fNum), fValue(par.fValue), fError(par.fError), - fConst(par.fConst), fFix(par.fFix), fLoLimit(par.fLoLimit), - fUpLimit(par.fUpLimit), fLoLimValid(par.fLoLimValid), - fUpLimValid(par.fUpLimValid), - fName(par.fName ) + fConst(par.fConst), fFix(par.fFix), fLoLimit(par.fLoLimit), + fUpLimit(par.fUpLimit), fLoLimValid(par.fLoLimValid), + fUpLimValid(par.fUpLimValid), + fName(par.fName ) {} - + MinuitParameter& operator=(const MinuitParameter& par) { if(this != &par) { fNum = par.fNum; @@ -87,9 +87,9 @@ public: fError = par.fError; fConst = par.fConst; fFix = par.fFix; - fLoLimit = par.fLoLimit; + fLoLimit = par.fLoLimit; fUpLimit = par.fUpLimit; - fLoLimValid = par.fLoLimValid; + fLoLimValid = par.fLoLimValid; fUpLimValid = par.fUpLimValid; } return *this; @@ -97,11 +97,11 @@ public: //access methods unsigned int Number() const {return fNum;} - // new API returning a string + // new API returning a string const std::string & GetName() const { return fName; } // return const char * for mantaining backward compatibility const char * Name() const {return fName.c_str();} - + double Value() const {return fValue;} double Error() const {return fError;} @@ -112,40 +112,40 @@ public: void SetError(double err) {fError = err;} void SetLimits(double low, double up) { assert(low != up); - fLoLimit = low; + fLoLimit = low; fUpLimit = up; - fLoLimValid = true; + fLoLimValid = true; fUpLimValid = true; if(low > up) { - fLoLimit = up; + fLoLimit = up; fUpLimit = low; } } void SetUpperLimit(double up) { - fLoLimit = 0.; + fLoLimit = 0.; fUpLimit = up; - fLoLimValid = false; + fLoLimValid = false; fUpLimValid = true; } void SetLowerLimit(double low) { - fLoLimit = low; + fLoLimit = low; fUpLimit = 0.; - fLoLimValid = true; + fLoLimValid = true; fUpLimValid = false; } void RemoveLimits() { - fLoLimit = 0.; + fLoLimit = 0.; fUpLimit = 0.; - fLoLimValid = false; + fLoLimValid = false; fUpLimValid = false; } void Fix() {fFix = true;} void Release() {fFix = false;} - + //state of Parameter (fixed/const/limited) bool IsConst() const {return fConst;} bool IsFixed() const {return fFix;} @@ -163,9 +163,9 @@ private: double fError; bool fConst; bool fFix; - double fLoLimit; + double fLoLimit; double fUpLimit; - bool fLoLimValid; + bool fLoLimValid; bool fUpLimValid; std::string fName; diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MnApplication.h b/ThirdParty/RootMinimizers/inc/Minuit2/MnApplication.h index 9e431c5891cc5eeecba92c55fba345b154f0c184..b4b8d1f4e1ca36b14265bdbf56d603314180a034 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MnApplication.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MnApplication.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -27,10 +27,10 @@ class FCNBase; class FCNGradientBase; //___________________________________________________________________________ -/** - application interface class for minimizers (migrad, simplex, Minimize, +/** + application interface class for minimizers (migrad, simplex, Minimize, Scan) - User normally instantiates the derived class like ROOT::Minuit2::MnMigrad + User normally instantiates the derived class like ROOT::Minuit2::MnMigrad for using Migrad for minimization */ @@ -49,15 +49,15 @@ public: /** Minimize the function - @param maxfcn : max number of function calls (if = 0) default is used which is set to + @param maxfcn : max number of function calls (if = 0) default is used which is set to 200 + 100 * npar + 5 * npar**2 - @param tolerance : value used for terminating iteration procedure. - For example, MIGRAD will stop iterating when edm (expected distance from minimum) will be: + @param tolerance : value used for terminating iteration procedure. + For example, MIGRAD will stop iterating when edm (expected distance from minimum) will be: edm < tolerance * 10**-3 Default value of tolerance used is 0.1 */ virtual FunctionMinimum operator()(unsigned int maxfcn = 0, double tolerance = 0.1); - + virtual const ModularFunctionMinimizer& Minimizer() const = 0; const MnMachinePrecision& Precision() const {return fState.Precision();} @@ -76,14 +76,14 @@ protected: unsigned int fNumCall; bool fUseGrad; -public: +public: // facade: forward interface of MnUserParameters and MnUserTransformation // via MnUserParameterState //access to parameters (row-wise) const std::vector<ROOT::Minuit2::MinuitParameter>& MinuitParameters() const; - //access to parameters and errors in column-wise representation + //access to parameters and errors in column-wise representation std::vector<double> Params() const; std::vector<double> Errors() const; @@ -107,7 +107,7 @@ public: double Value(unsigned int) const; double Error(unsigned int) const; - + //interaction via Name of Parameter void Fix(const char*); void Release(const char*); @@ -119,7 +119,7 @@ public: double Value(const char*) const; double Error(const char*) const; - + //convert Name into external number of Parameter unsigned int Index(const char*) const; //convert external number into Name of Parameter diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MnConfig.h b/ThirdParty/RootMinimizers/inc/Minuit2/MnConfig.h index dd2af0932721b6f3f6fd18f3784d2eafe08da1ac..518d116343ede025880f752c253ffee212e569a9 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MnConfig.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MnConfig.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -10,20 +10,11 @@ #ifndef ROOT_Minuit2_MnConfig #define ROOT_Minuit2_MnConfig -// for alpha streams -#if defined(__alpha) && !defined(linux) -# include <standards.h> -# ifndef __USE_STD_IOSTREAM -# define __USE_STD_IOSTREAM -# endif -#endif - - #ifdef _MSC_VER # pragma warning(disable:4244) // conversion from __w64 to int #endif -#if defined(__sun) && !defined(linux) +#if defined(__sun) && !defined(linux) #include <stdlib.h> #endif diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MnContours.h b/ThirdParty/RootMinimizers/inc/Minuit2/MnContours.h index 3b20c89e5bacf02307e5ddf25738055735f51135..7f226f90139c79cfeb2c6283bb8ec87056f65486 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MnContours.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MnContours.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -39,13 +39,13 @@ class MnContours { public: /// construct from FCN + Minimum - MnContours(const FCNBase& fcn, const FunctionMinimum& min) : fFCN(fcn), fMinimum(min), fStrategy(MnStrategy(1)) {} + MnContours(const FCNBase& fcn, const FunctionMinimum& min) : fFCN(fcn), fMinimum(min), fStrategy(MnStrategy(1)) {} /// construct from FCN + Minimum + strategy - MnContours(const FCNBase& fcn, const FunctionMinimum& min, unsigned int stra) : fFCN(fcn), fMinimum(min), fStrategy(MnStrategy(stra)) {} + MnContours(const FCNBase& fcn, const FunctionMinimum& min, unsigned int stra) : fFCN(fcn), fMinimum(min), fStrategy(MnStrategy(stra)) {} /// construct from FCN + Minimum + strategy - MnContours(const FCNBase& fcn, const FunctionMinimum& min, const MnStrategy& stra) : fFCN(fcn), fMinimum(min), fStrategy(stra) {} + MnContours(const FCNBase& fcn, const FunctionMinimum& min, const MnStrategy& stra) : fFCN(fcn), fMinimum(min), fStrategy(stra) {} ~MnContours() {} diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MnCovarianceSqueeze.h b/ThirdParty/RootMinimizers/inc/Minuit2/MnCovarianceSqueeze.h index b1fa157fe6e13e80ede2ba7c1077ee8819b676a6..4c8197c6f4e511f9870a66d8a1ed08574a32b242 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MnCovarianceSqueeze.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MnCovarianceSqueeze.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -21,7 +21,7 @@ class MnUserCovariance; class MinimumError; /** - class to reduce the covariance matrix when a parameter is fixed by + class to reduce the covariance matrix when a parameter is fixed by removing the corresponding row and index */ class MnCovarianceSqueeze { diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MnCross.h b/ThirdParty/RootMinimizers/inc/Minuit2/MnCross.h index 2e573bf343339180b9666ec34620811aa9ae8315..61bd3dcf1fdea73a8e7063a0bdcb4d000cacbb53 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MnCross.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MnCross.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -20,21 +20,21 @@ namespace ROOT { class MnCross { public: - + class CrossParLimit {}; class CrossFcnLimit {}; class CrossNewMin {}; public: - - MnCross() : fValue(0.), fState(MnUserParameterState()), fNFcn(0), fValid(false), fLimset(false), fMaxFcn(false), fNewMin(false) {} - - MnCross(unsigned int nfcn) : fValue(0.), fState(MnUserParameterState() ), fNFcn(nfcn), fValid(false), fLimset(false), fMaxFcn(false), fNewMin(false) {} - MnCross(const MnUserParameterState& state, unsigned int nfcn) : fValue(0.), fState(state), fNFcn(nfcn), fValid(false), fLimset(false), fMaxFcn(false), fNewMin(false) {} - + MnCross() : fValue(0.), fState(MnUserParameterState()), fNFcn(0), fValid(false), fLimset(false), fMaxFcn(false), fNewMin(false) {} + + MnCross(unsigned int nfcn) : fValue(0.), fState(MnUserParameterState() ), fNFcn(nfcn), fValid(false), fLimset(false), fMaxFcn(false), fNewMin(false) {} + + MnCross(const MnUserParameterState& state, unsigned int nfcn) : fValue(0.), fState(state), fNFcn(nfcn), fValid(false), fLimset(false), fMaxFcn(false), fNewMin(false) {} + MnCross(double value, const MnUserParameterState& state, unsigned int nfcn) : fValue(value), fState(state), fNFcn(nfcn), fValid(true), fLimset(false), fMaxFcn(false), fNewMin(false) {} - + MnCross(const MnUserParameterState& state, unsigned int nfcn, CrossParLimit) : fValue(0.), fState(state), fNFcn(nfcn), fValid(true), fLimset(true), fMaxFcn(false), fNewMin(false) {} MnCross(const MnUserParameterState& state, unsigned int nfcn, CrossFcnLimit) : fValue(0.), fState(state), fNFcn(nfcn), fValid(false), fLimset(false), fMaxFcn(true), fNewMin(false) {} @@ -56,7 +56,7 @@ public: return *this; } - double Value() const {return fValue;} + double Value() const {return fValue;} const MnUserParameterState& State() const {return fState;} bool IsValid() const {return fValid;} bool AtLimit() const {return fLimset;} diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MnEigen.h b/ThirdParty/RootMinimizers/inc/Minuit2/MnEigen.h index ed9f9d1a7efb4ff5fd68d68b077e0116cd27430a..9fa3403faceec92168199795553f08314c5fc80c 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MnEigen.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MnEigen.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MnFcn.h b/ThirdParty/RootMinimizers/inc/Minuit2/MnFcn.h index 7b1c2b70c8dfb400a30cf1d873684e7d55d28e45..1f60d94e1528c42ad9e1cde9ea8f4399e01f88d4 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MnFcn.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MnFcn.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -23,18 +23,18 @@ namespace ROOT { class FCNBase; /** Wrapper class to FCNBase interface used internally by Minuit. - Apply conversion from calling the function from a Minuit Vector (MnAlgebraicVector) to a std::vector for - the function coordinates. + Apply conversion from calling the function from a Minuit Vector (MnAlgebraicVector) to a std::vector for + the function coordinates. The class counts also the number of function calls. By default counter strart from zero, but a different value might be given if the class is instantiated later on, for example for a set of different minimizaitons - Normally the derived class MnUserFCN should be instantiated with performs in addition the transformatiopn - internal-> external parameters + Normally the derived class MnUserFCN should be instantiated with performs in addition the transformatiopn + internal-> external parameters */ class MnFcn { public: - /// constructor of + /// constructor of explicit MnFcn(const FCNBase& fcn, int ncall = 0) : fFCN(fcn), fNumCall(ncall) {} virtual ~MnFcn(); diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MnFumiliMinimize.h b/ThirdParty/RootMinimizers/inc/Minuit2/MnFumiliMinimize.h index a43a7b2084389f2d619b06344d3ecfee22ee97b6..c8848f64e8c422fe0d977124f1a8de84ac66bbaf 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MnFumiliMinimize.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MnFumiliMinimize.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -23,13 +23,13 @@ namespace ROOT { // class FCNBase; -//___________________________________________________________________________ -/** +//___________________________________________________________________________ +/** API class for minimization using Fumili technology; allows for user interaction: set/change parameters, do minimization, -change parameters, re-do minimization etc.; +change parameters, re-do minimization etc.; also used by MnMinos and MnContours; @@ -57,7 +57,7 @@ public: /// construct from FumiliFCNBase + MnUserParameterState + MnStrategy MnFumiliMinimize(const FumiliFCNBase& fcn, const MnUserParameterState& par, const MnStrategy& str) : MnApplication(fcn, MnUserParameterState(par), str), fMinimizer(FumiliMinimizer()), fFCN(fcn) {} - MnFumiliMinimize(const MnFumiliMinimize& migr) : MnApplication(migr.Fcnbase(), migr.State(), migr.Strategy(), migr.NumOfCalls()), fMinimizer(migr.fMinimizer), fFCN(migr.Fcnbase()) {} + MnFumiliMinimize(const MnFumiliMinimize& migr) : MnApplication(migr.Fcnbase(), migr.State(), migr.Strategy(), migr.NumOfCalls()), fMinimizer(migr.fMinimizer), fFCN(migr.Fcnbase()) {} virtual ~MnFumiliMinimize() { } diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MnFunctionCross.h b/ThirdParty/RootMinimizers/inc/Minuit2/MnFunctionCross.h index 8c535b996e765ce165d7a00fc1070a4679826e9c..38a1bbc2db092ecbbdefdbf470345b3754c59194 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MnFunctionCross.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MnFunctionCross.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -25,17 +25,17 @@ class MnStrategy; class MnCross; /** - MnFunctionCross + MnFunctionCross */ class MnFunctionCross { public: - - MnFunctionCross(const FCNBase& fcn, const MnUserParameterState& state, double fval, const MnStrategy& stra) : fFCN(fcn), fState(state), fFval(fval), fStrategy(stra) {} - + + MnFunctionCross(const FCNBase& fcn, const MnUserParameterState& state, double fval, const MnStrategy& stra) : fFCN(fcn), fState(state), fFval(fval), fStrategy(stra) {} + ~MnFunctionCross() {} - + MnCross operator()(const std::vector<unsigned int>&, const std::vector<double>&, const std::vector<double>&, double, unsigned int) const; private: diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MnGlobalCorrelationCoeff.h b/ThirdParty/RootMinimizers/inc/Minuit2/MnGlobalCorrelationCoeff.h index 657022a0994863fa0ee6736ae69aac8ef6884236..fcdfb3de08fc1ef98fef84cd3a21f41201b81b67 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MnGlobalCorrelationCoeff.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MnGlobalCorrelationCoeff.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -27,7 +27,7 @@ class MnGlobalCorrelationCoeff { public: - MnGlobalCorrelationCoeff() : + MnGlobalCorrelationCoeff() : fGlobalCC(std::vector<double>()), fValid(false) {} MnGlobalCorrelationCoeff(const MnAlgebraicSymMatrix&); diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MnHesse.h b/ThirdParty/RootMinimizers/inc/Minuit2/MnHesse.h index c406584dde56e78e2d18c3d4bec6a7e7a109e5a7..e7a386daa3de7dba59e780e2fce34e9f651c490c 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MnHesse.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MnHesse.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -28,12 +28,12 @@ class MnUserTransformation; class MinimumState; class MnMachinePrecision; class MnFcn; -class FunctionMinimum; +class FunctionMinimum; //_______________________________________________________________________ -/** - API class for calculating the numerical covariance matrix - (== 2x Inverse Hessian == 2x Inverse 2nd derivative); can be used by the +/** + API class for calculating the numerical covariance matrix + (== 2x Inverse Hessian == 2x Inverse 2nd derivative); can be used by the user or Minuit itself */ @@ -70,13 +70,13 @@ public: MnUserParameterState operator()(const FCNBase&, const MnUserParameters&, const MnUserCovariance&, unsigned int maxcalls=0) const; /// FCN + MnUserParameterState MnUserParameterState operator()(const FCNBase&, const MnUserParameterState&, unsigned int maxcalls=0) const; - /// - /// API to use MnHesse after minimization when function mimimum is avalilable, otherwise information on the last state will be - /// lost. (It would be needed to re-call the gradient and spend extra useless function calls) + /// + /// API to use MnHesse after minimization when function mimimum is avalilable, otherwise information on the last state will be + /// lost. (It would be needed to re-call the gradient and spend extra useless function calls) /// The Function Minimum is updated (modified) by adding the Hesse results as last state of minimization /// void operator()(const FCNBase&, FunctionMinimum&, unsigned int maxcalls=0) const; - + /// internal interface /// diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MnLineSearch.h b/ThirdParty/RootMinimizers/inc/Minuit2/MnLineSearch.h index 28196e62ffeda7732e5165f2462f6665d5d83516..8869a7908090cc55bc7fa435914def1d7bb3fe72 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MnLineSearch.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MnLineSearch.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -25,11 +25,11 @@ class MnParabolaPoint; -/** +/** -Implements a 1-dimensional minimization along a given direction -(i.e. quadratic interpolation) It is independent of the algorithm -that generates the direction vector. It brackets the 1-dimensional +Implements a 1-dimensional minimization along a given direction +(i.e. quadratic interpolation) It is independent of the algorithm +that generates the direction vector. It brackets the 1-dimensional Minimum and iterates to approach the real Minimum of the n-dimensional function. diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MnMachinePrecision.h b/ThirdParty/RootMinimizers/inc/Minuit2/MnMachinePrecision.h index e2312af70a692315532f484326c89ce60247c687..36fe5d163896ab2064af915a8b73a68ebda79595 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MnMachinePrecision.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MnMachinePrecision.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -17,10 +17,10 @@ namespace ROOT { namespace Minuit2 { -/** - determines the relative floating point arithmetic precision. The - SetPrecision() method can be used to override Minuit's own determination, - when the user knows that the {FCN} function Value is not calculated to +/** + determines the relative floating point arithmetic precision. The + SetPrecision() method can be used to override Minuit's own determination, + when the user knows that the {FCN} function Value is not calculated to the nominal machine accuracy. */ diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MnMatrix.h b/ThirdParty/RootMinimizers/inc/Minuit2/MnMatrix.h index ed4112422fd78cf588dfc5f8d6046341b2b9dec3..3cfe9eca9ad8115e46815548d894f2924679d71e 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MnMatrix.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MnMatrix.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -10,7 +10,7 @@ #ifndef ROOT_Minuit2_MnMatrix #define ROOT_Minuit2_MnMatrix -//add MnConfig file to define before everything compiler +//add MnConfig file to define before everything compiler // dependent macros #include "Minuit2/MnConfig.h" diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MnMigrad.h b/ThirdParty/RootMinimizers/inc/Minuit2/MnMigrad.h index 2d309c1d067523b86aa84da2287ff54a31bafc54..7a79fc6a5e0dc26db0cdcec6a7096aec317e4668 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MnMigrad.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MnMigrad.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -24,7 +24,7 @@ class FCNBase; /** API class for minimization using Variable Metric technology ("MIGRAD"); allows for user interaction: set/change parameters, do minimization, - change parameters, re-do minimization etc.; + change parameters, re-do minimization etc.; also used by MnMinos and MnContours; */ @@ -70,7 +70,7 @@ public: /// construct from FCNGradientBase + MnUserParameterState + MnStrategy MnMigrad(const FCNGradientBase& fcn, const MnUserParameterState& par, const MnStrategy& str) : MnApplication(fcn, MnUserParameterState(par), str), fMinimizer(VariableMetricMinimizer()) {} - MnMigrad(const MnMigrad& migr) : MnApplication(migr.Fcnbase(), migr.State(), migr.Strategy(), migr.NumOfCalls()), fMinimizer(migr.fMinimizer) {} + MnMigrad(const MnMigrad& migr) : MnApplication(migr.Fcnbase(), migr.State(), migr.Strategy(), migr.NumOfCalls()), fMinimizer(migr.fMinimizer) {} ~MnMigrad() {} diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MnMinimize.h b/ThirdParty/RootMinimizers/inc/Minuit2/MnMinimize.h index ad28f1080c1b2d06d0b0d45bc8d10ad57a556738..6dec8e8de67e527d250fb895c9b724b62516d91c 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MnMinimize.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MnMinimize.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -22,7 +22,7 @@ class FCNBase; /** API class for minimization using Variable Metric technology ("MIGRAD"); allows for user interaction: set/change parameters, do minimization, - change parameters, re-do minimization etc.; + change parameters, re-do minimization etc.; also used by MnMinos and MnContours; */ @@ -69,7 +69,7 @@ public: MnMinimize(const FCNGradientBase& fcn, const MnUserParameterState& par, const MnStrategy& str) : MnApplication(fcn, MnUserParameterState(par), str), fMinimizer(CombinedMinimizer()) {} - MnMinimize(const MnMinimize& migr) : MnApplication(migr.Fcnbase(), migr.State(), migr.Strategy(), migr.NumOfCalls()), fMinimizer(migr.fMinimizer) {} + MnMinimize(const MnMinimize& migr) : MnApplication(migr.Fcnbase(), migr.State(), migr.Strategy(), migr.NumOfCalls()), fMinimizer(migr.fMinimizer) {} ~MnMinimize() {} diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MnMinos.h b/ThirdParty/RootMinimizers/inc/Minuit2/MnMinos.h index 8fa7e95bc38568803b6624d3bcd287c74993400e..2dc3ca9564d3de55677660acd5da3b302870b272 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MnMinos.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MnMinos.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -25,7 +25,7 @@ class MinosError; class MnCross; //__________________________________________________________________ -/** +/** API class for Minos Error analysis (asymmetric errors); minimization has to be done before and Minimum must be valid; possibility to ask only for one side of the Minos Error; @@ -37,14 +37,14 @@ public: /// construct from FCN + Minimum + strategy - MnMinos(const FCNBase& fcn, const FunctionMinimum& min, unsigned int stra = 1); + MnMinos(const FCNBase& fcn, const FunctionMinimum& min, unsigned int stra = 1); /// construct from FCN + Minimum + strategy - MnMinos(const FCNBase& fcn, const FunctionMinimum& min, const MnStrategy& stra); + MnMinos(const FCNBase& fcn, const FunctionMinimum& min, const MnStrategy& stra); ~MnMinos() {} - - /// returns the negative (pair.first) and the positive (pair.second) + + /// returns the negative (pair.first) and the positive (pair.second) /// Minos Error of the Parameter std::pair<double,double> operator()(unsigned int, unsigned int maxcalls = 0, double toler = 0.1) const; @@ -57,16 +57,16 @@ public: MnCross Upval(unsigned int, unsigned int maxcalls = 0, double toler = 0.1) const; /// ask for MinosError (Lower + Upper) - /// can be printed via std::cout + /// can be printed via std::cout MinosError Minos(unsigned int, unsigned int maxcalls = 0, double toler = 0.1) const; -protected: - +protected: + /// internal method to get crossing value via MnFunctionCross MnCross FindCrossValue(int dir , unsigned int, unsigned int maxcalls, double toler) const; - + private: - + const FCNBase& fFCN; const FunctionMinimum& fMinimum; MnStrategy fStrategy; diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MnParabola.h b/ThirdParty/RootMinimizers/inc/Minuit2/MnParabola.h index d59fee6f2ebafe2a0f0ae5f4748a1a790456e014..7c0b763b96a352261c9156570676242bf40c9d49 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MnParabola.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MnParabola.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -17,7 +17,7 @@ namespace ROOT { namespace Minuit2 { -/** +/** This class defines a parabola of the form a*x*x + b*x + c @@ -64,7 +64,7 @@ public: /** - Calculates the bigger of the two x values corresponding to the + Calculates the bigger of the two x values corresponding to the given y Value. <p> @@ -73,12 +73,12 @@ public: crash?? what is sqrt (-1.0) ? @param y the y Value for which the x Value is to be calculated. - + @return the bigger one of the two corresponding values. */ - // ok, at first glance it does not look like the formula for the quadratic + // ok, at first glance it does not look like the formula for the quadratic // equation, but it is! ;-) double X_pos(double y) const {return (sqrt(y/fA + Min()*Min() - fC/fA) + Min());} // maybe it is worth to check the performance improvement with the below formula?? @@ -88,7 +88,7 @@ public: /** - Calculates the smaller of the two x values corresponding to the + Calculates the smaller of the two x values corresponding to the given y Value. <p> @@ -97,7 +97,7 @@ public: crash?? what is sqrt (-1.0) ? @param y the y Value for which the x Value is to be calculated. - + @return the smaller one of the two corresponding values. */ @@ -129,8 +129,8 @@ public: /** - Accessor to the coefficient of the quadratic term. - + Accessor to the coefficient of the quadratic term. + @return the coefficient of the quadratic term. */ @@ -140,9 +140,9 @@ public: /** - Accessor to the coefficient of the linear term. + Accessor to the coefficient of the linear term. - @return the coefficient of the linear term. + @return the coefficient of the linear term. */ @@ -151,7 +151,7 @@ public: /** - Accessor to the coefficient of the constant term. + Accessor to the coefficient of the constant term. @return the coefficient of the constant term. diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MnParabolaFactory.h b/ThirdParty/RootMinimizers/inc/Minuit2/MnParabolaFactory.h index 70c9b75da79347304fe654172656084085256825..f18707954afaacb042a7d5225588b86cce1cf8d7 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MnParabolaFactory.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MnParabolaFactory.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -26,14 +26,14 @@ public: ~MnParabolaFactory() {} - MnParabola operator()(const MnParabolaPoint&, const MnParabolaPoint&, + MnParabola operator()(const MnParabolaPoint&, const MnParabolaPoint&, const MnParabolaPoint&) const; - MnParabola operator()(const MnParabolaPoint&, double, + MnParabola operator()(const MnParabolaPoint&, double, const MnParabolaPoint&) const; -private: - +private: + }; } // namespace Minuit2 diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MnParabolaPoint.h b/ThirdParty/RootMinimizers/inc/Minuit2/MnParabolaPoint.h index 694e41340179ec74c746f81f6e1de585b6140e32..71076f6d8325f8f8fc305e3c7bf29b16689f2990 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MnParabolaPoint.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MnParabolaPoint.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -16,7 +16,7 @@ namespace ROOT { -/** +/** A point of a parabola. @@ -42,11 +42,11 @@ public: /** - + Initializes the point with its coordinates. @param x the x (first) coordinate of the point. - @param y the y (second) coordinate of the point. + @param y the y (second) coordinate of the point. */ diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MnParameterScan.h b/ThirdParty/RootMinimizers/inc/Minuit2/MnParameterScan.h index 3f41960925bd12ffed23a21fcef7d3393b3ddb07..62530a4b0484117fb809782b1e458630619f6773 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MnParameterScan.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MnParameterScan.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -23,7 +23,7 @@ namespace ROOT { class FCNBase; -/** Scans the values of FCN as a function of one Parameter and retains the +/** Scans the values of FCN as a function of one Parameter and retains the best function and Parameter values found. */ diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MnPlot.h b/ThirdParty/RootMinimizers/inc/Minuit2/MnPlot.h index f5c02571b99d827e3a58463d0d719b0eadebacba..7bd8e288639df78471bad9057d0e45ae31667633 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MnPlot.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MnPlot.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -19,14 +19,14 @@ namespace ROOT { namespace Minuit2 { -/** MnPlot produces a text-screen graphical output of (x,y) points, e.g. +/** MnPlot produces a text-screen graphical output of (x,y) points, e.g. from Scan or Contours. */ class MnPlot { public: - + MnPlot() : fPageWidth(80), fPageLength(30) {} MnPlot(unsigned int width, unsigned int length) : fPageWidth(width), fPageLength(length) { diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MnPosDef.h b/ThirdParty/RootMinimizers/inc/Minuit2/MnPosDef.h index 0b12d60f849b1a652db7e0701c2196fec09f1acf..c5b0d92f7778cb1b1f495eb87f0ad1f638cfdfba 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MnPosDef.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MnPosDef.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -26,11 +26,11 @@ class MnMachinePrecision; class MnPosDef { public: - + MnPosDef() {} - + ~MnPosDef() {} - + MinimumState operator()(const MinimumState&, const MnMachinePrecision&) const; MinimumError operator()(const MinimumError&, const MnMachinePrecision&) const; private: diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MnPrint.h b/ThirdParty/RootMinimizers/inc/Minuit2/MnPrint.h index 4d040d62486e6f1c7bcf1bcb1ba49b4b8bd479f2..3d7d29e2277b96b1ea4fbbdbf844db2269d1a68a 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MnPrint.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MnPrint.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -32,7 +32,7 @@ namespace ROOT { /** - define ostream operators for output + define std::ostream operators for output */ class FunctionMinimum; @@ -68,27 +68,26 @@ std::ostream& operator<<(std::ostream&, const MinosError&); class ContoursError; std::ostream& operator<<(std::ostream&, const ContoursError&); - -// class define static print level values -class MnPrint { +// class define static print level values + +class MnPrint { public: // set print level and return the previous one static int SetLevel(int level); - + // return current level - static int Level(); - - // print current minimization state + static int Level(); + + // print current minimization state static void PrintState(std::ostream & os, const MinimumState & state, const char * msg, int iter = -1); - // print current minimization state + // print current minimization state static void PrintState(std::ostream & os, double fcn, double edm, int ncalls, const char * msg, int iter = -1); // print FCN value with right precision adding optionally end line static void PrintFcn(std::ostream & os, double value, bool endline = true); - }; @@ -104,7 +103,7 @@ public: #ifndef MNLOG #define MN_OS std::cerr -#else +#else #define MN_OS MNLOG #endif @@ -115,9 +114,9 @@ public: if (MnPrint::Level() >= 0) MN_OS << "Error: " << str \ << std::endl; # define MN_INFO_VAL(x) \ - if (MnPrint::Level() > 0) MN_OS << "Info: " << #x << " = " << (x) << std::endl; + if (MnPrint::Level() > 0) MN_OS << "Info: " << #x << " = " << (x) << std::endl; # define MN_ERROR_VAL(x) \ - if (MnPrint::Level() >= 0) MN_OS << "Error: " << #x << " = " << (x) << std::endl; + if (MnPrint::Level() >= 0) MN_OS << "Error: " << #x << " = " << (x) << std::endl; // same giving a location @@ -131,16 +130,16 @@ public: # define MN_INFO_VAL2(loc,x) \ if (MnPrint::Level() > 0) MN_OS << "Info in " << loc << " : " << #x << " = " << (x) << std::endl; # define MN_ERROR_VAL2(loc,x) \ - if (MnPrint::Level() >= 0) MN_OS << "Error in " << loc << " : " << #x << " = " << (x) << std::endl; + if (MnPrint::Level() >= 0) MN_OS << "Error in " << loc << " : " << #x << " = " << (x) << std::endl; #else -// use ROOT error reporting system +// use ROOT error reporting system #include "TError.h" #include "Math/Util.h" -// this first two should be used only with string literals to +// this first two should be used only with string literals to // avoid warning produced by the format in TError #define MN_INFO_MSG(str) \ ::Info("Minuit2",str); @@ -148,24 +147,24 @@ public: ::Error("Minuit2",str); # define MN_INFO_VAL(x) \ {std::string str = std::string(#x) + std::string(" = ") + ROOT::Math::Util::ToString(x); \ - ::Info("Minuit2","%s",str.c_str() );} + ::Info("Minuit2","%s",str.c_str() );} # define MN_ERROR_VAL(x) \ {std::string str = std::string(#x) + std::string(" = ") + ROOT::Math::Util::ToString(x); \ - ::Error("Minuit2","%s",str.c_str() );} + ::Error("Minuit2","%s",str.c_str() );} # define MN_INFO_MSG2(loc,txt) \ {std::string str = std::string(loc) + std::string(" : ") + std::string(txt); \ - ::Info("Minuit2","%s",str.c_str() );} + ::Info("Minuit2","%s",str.c_str() );} # define MN_ERROR_MSG2(loc,txt) \ {std::string str = std::string(loc) + std::string(" : ") + std::string(txt); \ - ::Error("Minuit2","%s",str.c_str() );} + ::Error("Minuit2","%s",str.c_str() );} # define MN_INFO_VAL2(loc,x) \ {std::string str = std::string(loc) + std::string(" : ") + std::string(#x) + std::string(" = ") + ROOT::Math::Util::ToString(x); \ - ::Info("Minuit2","%s",str.c_str() );} + ::Info("Minuit2","%s",str.c_str() );} # define MN_ERROR_VAL2(loc,x) \ {std::string str = std::string(loc) + std::string(" : ") + std::string(#x) + std::string(" = ") + ROOT::Math::Util::ToString(x); \ - ::Error("Minuit2","%s",str.c_str() );} + ::Error("Minuit2","%s",str.c_str() );} diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MnRefCountedPointer.h b/ThirdParty/RootMinimizers/inc/Minuit2/MnRefCountedPointer.h index ea349f26c2ccc2b36d85a6577d1f81c8377878c8..fe1934844bccdb79fe2ce0f8df25c02a14105070 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MnRefCountedPointer.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MnRefCountedPointer.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -23,26 +23,26 @@ public: // Default constructor needed for use inside array, vector, etc. MnRefCountedPointer() : fPtr(0), fCounter(0) {} - - MnRefCountedPointer(T* pt) : + + MnRefCountedPointer(T* pt) : fPtr(pt), fCounter(new MnReferenceCounter()) {AddReference();} - MnRefCountedPointer(const MnRefCountedPointer<T>& other) : + MnRefCountedPointer(const MnRefCountedPointer<T>& other) : fPtr(other.fPtr), fCounter(other.fCounter) {AddReference();} ~MnRefCountedPointer() { /* if(References() == 0) { - if(fPtr) delete fPtr; + if(fPtr) delete fPtr; if(fCounter) delete fCounter; } else RemoveReference(); */ if(References() != 0) RemoveReference(); } - + bool IsValid() const {return fPtr != 0;} - + MnRefCountedPointer& operator=(const MnRefCountedPointer<T>& other) { if(this != &other && fPtr != other.fPtr) { RemoveReference(); @@ -64,13 +64,13 @@ public: T* Get() const {return fPtr;} T* operator->() const {DoCheck(); return fPtr;} - + T& operator*() const {DoCheck(); return *fPtr;} - + bool operator==(const T* otherP) const {return fPtr == otherP;} - + bool operator<(const T* otherP) const {return fPtr < otherP;} - + unsigned int References() const {return fCounter->References();} void AddReference() const {fCounter->AddReference();} @@ -78,19 +78,19 @@ public: void RemoveReference() { fCounter->RemoveReference(); if(References() == 0) { - delete fPtr; fPtr=0; + delete fPtr; fPtr=0; delete fCounter; fCounter=0; } } - + private: - - T* fPtr; + + T* fPtr; MnReferenceCounter* fCounter; - + private: - void DoCheck() const {assert(IsValid());} + void DoCheck() const {assert(IsValid());} }; } // namespace Minuit2 diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MnReferenceCounter.h b/ThirdParty/RootMinimizers/inc/Minuit2/MnReferenceCounter.h index e3febddcf03578acc791d987d643bc0ab6cea9be..f2938c68969bc6614e728768b6eb9a0b3b092074 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MnReferenceCounter.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MnReferenceCounter.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -27,20 +27,20 @@ public: MnReferenceCounter() : fReferences(0) {} - MnReferenceCounter(const MnReferenceCounter& other) : + MnReferenceCounter(const MnReferenceCounter& other) : fReferences(other.fReferences) {} MnReferenceCounter& operator=(const MnReferenceCounter& other) { fReferences = other.fReferences; return *this; } - + ~MnReferenceCounter() {assert(fReferences == 0);} - + void* operator new(size_t nbytes) { return StackAllocatorHolder::Get().Allocate(nbytes); } - + void operator delete(void* p, size_t /*nbytes */) { StackAllocatorHolder::Get().Deallocate(p); } @@ -50,9 +50,9 @@ public: void AddReference() const {fReferences++;} void RemoveReference() const {fReferences--;} - + private: - + mutable unsigned int fReferences; }; diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MnScan.h b/ThirdParty/RootMinimizers/inc/Minuit2/MnScan.h index a6ce635c9635b06155fdb3a37f094d76e0b5241e..d224f011144e579dc0a63b1a9eb36cd7804c62e9 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MnScan.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MnScan.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -21,11 +21,11 @@ namespace ROOT { class FCNBase; //_______________________________________________________________________ -/** +/** API class for minimization using a scan method to find the minimum; allows for user interaction: set/change parameters, do minimization, - change parameters, re-do minimization etc.; - + change parameters, re-do minimization etc.; + */ class MnScan : public MnApplication { @@ -50,7 +50,7 @@ public: /// construct from FCNBase + MnUserParameterState + MnStrategy MnScan(const FCNBase& fcn, const MnUserParameterState& par, const MnStrategy& str) : MnApplication(fcn, MnUserParameterState(par), str), fMinimizer(ScanMinimizer()) {} - MnScan(const MnScan& migr) : MnApplication(migr.Fcnbase(), migr.State(), migr.Strategy(), migr.NumOfCalls()), fMinimizer(migr.fMinimizer) {} + MnScan(const MnScan& migr) : MnApplication(migr.Fcnbase(), migr.State(), migr.Strategy(), migr.NumOfCalls()), fMinimizer(migr.fMinimizer) {} ~MnScan() {} diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MnSeedGenerator.h b/ThirdParty/RootMinimizers/inc/Minuit2/MnSeedGenerator.h index c57ea39250420e0c1d904777ab6bde9255acf371..116bf1e29474b016b1f3757d4dd8c247b5aa5bc1 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MnSeedGenerator.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MnSeedGenerator.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MnSimplex.h b/ThirdParty/RootMinimizers/inc/Minuit2/MnSimplex.h index dcce2024b335d39e488017ba3e9374acbc5428c2..0d7f52fa6f2d816dfd919b3d3a2a264e29cf1693 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MnSimplex.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MnSimplex.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -21,14 +21,14 @@ namespace ROOT { class FCNBase; //_________________________________________________________________________ -/** - API class for minimization using the Simplex method, which does not need and use - the derivatives of the function, but only function values. - More information on the minimization method is available +/** + API class for minimization using the Simplex method, which does not need and use + the derivatives of the function, but only function values. + More information on the minimization method is available <A HREF="http://seal.web.cern.ch/mathlibs/documents/minuit/mntutorial.pdf">here</A>. - + It allows for user interaction: set/change parameters, do minimization, - change parameters, re-do minimization etc.; + change parameters, re-do minimization etc.; */ class MnSimplex : public MnApplication { @@ -53,7 +53,7 @@ public: /// construct from FCNBase + MnUserParameterState + MnStrategy MnSimplex(const FCNBase& fcn, const MnUserParameterState& par, const MnStrategy& str) : MnApplication(fcn, MnUserParameterState(par), str), fMinimizer(SimplexMinimizer()) {} - MnSimplex(const MnSimplex& migr) : MnApplication(migr.Fcnbase(), migr.State(), migr.Strategy(), migr.NumOfCalls()), fMinimizer(migr.fMinimizer) {} + MnSimplex(const MnSimplex& migr) : MnApplication(migr.Fcnbase(), migr.State(), migr.Strategy(), migr.NumOfCalls()), fMinimizer(migr.fMinimizer) {} ~MnSimplex() {} diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MnStrategy.h b/ThirdParty/RootMinimizers/inc/Minuit2/MnStrategy.h index 72c86bfe53130b5f887ded6cf2a2eb023e502eda..e89532cc11de48a3f01ee887aae4bab4f1b126ce 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MnStrategy.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MnStrategy.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -15,11 +15,11 @@ namespace ROOT { namespace Minuit2 { //_________________________________________________________________________ -/** - API class for defining three levels of strategies: low (0), medium (1), +/** + API class for defining three levels of strategies: low (0), medium (1), high (>=2); - acts on: Migrad (behavioural), - Minos (lowers strategy by 1 for Minos-own minimization), + acts on: Migrad (behavioural), + Minos (lowers strategy by 1 for Minos-own minimization), Hesse (iterations), Numerical2PDerivative (iterations) */ @@ -48,7 +48,7 @@ public: unsigned int HessianGradientNCycles() const {return fHessGradNCyc;} int StorageLevel() const { return fStoreLevel; } - + bool IsLow() const {return fStrategy == 0;} bool IsMedium() const {return fStrategy == 1;} bool IsHigh() const {return fStrategy >= 2;} @@ -56,7 +56,7 @@ public: void SetLowStrategy(); void SetMediumStrategy(); void SetHighStrategy(); - + void SetGradientNCycles(unsigned int n) {fGradNCyc = n;} void SetGradientStepTolerance(double stp) {fGradTlrStp = stp;} void SetGradientTolerance(double toler) {fGradTlr = toler;} @@ -65,8 +65,8 @@ public: void SetHessianStepTolerance(double stp) {fHessTlrStp = stp;} void SetHessianG2Tolerance(double toler) {fHessTlrG2 = toler;} void SetHessianGradientNCycles(unsigned int n) {fHessGradNCyc = n;} - - // set storage level of iteration quantities + + // set storage level of iteration quantities // 0 = store only last iterations 1 = full storage (default) void SetStorageLevel(unsigned int level) { fStoreLevel = level; } private: @@ -80,7 +80,7 @@ private: double fHessTlrStp; double fHessTlrG2; unsigned int fHessGradNCyc; - int fStoreLevel; + int fStoreLevel; }; } // namespace Minuit2 diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MnTiny.h b/ThirdParty/RootMinimizers/inc/Minuit2/MnTiny.h index 0e5cebd5f2b93d6adf8866333a2a00f24ebe8abd..5590b0db074953276e2f1994c7f25d5c6f17439f 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MnTiny.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MnTiny.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -16,19 +16,19 @@ namespace ROOT { class MnTiny { - + public: - + MnTiny() : fOne(1.) {} - + ~MnTiny() {} - + double One() const; - - double operator()(double epsp1) const; - + + double operator()(volatile double epsp1) const; + private: - + double fOne; }; diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MnTraceObject.h b/ThirdParty/RootMinimizers/inc/Minuit2/MnTraceObject.h index ae931367df1685f264bb8dd13cedd286df8fdbe2..78edd5879219d5f50250a6ad75dc0b59a60128f6 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MnTraceObject.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MnTraceObject.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Author: L. Moneta 2012 +// Author: L. Moneta 2012 /********************************************************************** * * @@ -15,11 +15,11 @@ namespace ROOT { namespace Minuit2 { class MinimumState; - class MnUserParameterState; + class MnUserParameterState; - class MnTraceObject { + class MnTraceObject { - public: + public: MnTraceObject(int parNumber = -1) : fUserState(0), @@ -29,7 +29,7 @@ namespace ROOT { virtual void Init(const MnUserParameterState & state) { fUserState = &state; } - virtual void operator() (int i, const MinimumState & state); + virtual void operator() (int i, const MinimumState & state); const MnUserParameterState & UserState() const { return *fUserState; } @@ -37,10 +37,10 @@ namespace ROOT { int ParNumber() const { return fParNumber; } - private: + private: - const MnUserParameterState * fUserState; - int fParNumber; + const MnUserParameterState * fUserState; + int fParNumber; }; } // namespace Minuit2 diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MnUserCovariance.h b/ThirdParty/RootMinimizers/inc/Minuit2/MnUserCovariance.h index 95b988892a6f5b9badda332a11ac9749fd5f16e9..c513d90d3f74ce7ede9db966f5bd3d2398fa23ae 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MnUserCovariance.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MnUserCovariance.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -22,7 +22,7 @@ namespace ROOT { /** - Class containing the covariance matrix data represented as a vector of + Class containing the covariance matrix data represented as a vector of size n*(n+1)/2 Used to hide internal matrix representation to user */ @@ -40,11 +40,11 @@ public: // unsafe constructor using just a pointer MnUserCovariance(const double * data, unsigned int nrow) : - fData(std::vector<double>(data,data+nrow*(nrow+1)/2)), + fData(std::vector<double>(data,data+nrow*(nrow+1)/2)), fNRow(nrow) { } - MnUserCovariance(unsigned int n) : + MnUserCovariance(unsigned int n) : fData(std::vector<double>(n*(n+1)/2, 0.)), fNRow(n) {} ~MnUserCovariance() {} @@ -61,7 +61,7 @@ public: double operator()(unsigned int row, unsigned int col) const { assert(row < fNRow && col < fNRow); - if(row > col) + if(row > col) return fData[col+row*(row+1)/2]; else return fData[row+col*(col+1)/2]; @@ -69,7 +69,7 @@ public: double& operator()(unsigned int row, unsigned int col) { assert(row < fNRow && col < fNRow); - if(row > col) + if(row > col) return fData[col+row*(row+1)/2]; else return fData[row+col*(col+1)/2]; @@ -84,7 +84,7 @@ public: unsigned int Nrow() const {return fNRow;} // VC 7.1 warning: conversion from size_t to unsigned int - unsigned int size() const + unsigned int size() const { return static_cast < unsigned int > ( fData.size() ); } diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MnUserFcn.h b/ThirdParty/RootMinimizers/inc/Minuit2/MnUserFcn.h index 581e6d2a302d91c6cc710d60962590471c13011d..51e50fc7d4c21f4834d8a664d7010e2f218489a9 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MnUserFcn.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MnUserFcn.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -20,7 +20,7 @@ namespace ROOT { class MnUserTransformation; /** - Wrapper used by Minuit of FCN interface + Wrapper used by Minuit of FCN interface containing a reference to the transformation object */ class MnUserFcn : public MnFcn { diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MnUserParameterState.h b/ThirdParty/RootMinimizers/inc/Minuit2/MnUserParameterState.h index 8c7bdf631009cf17f4f80ddad9118a365e968907..83d7f8561ddbc94ec9e0d10233403e5446fa2df7 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MnUserParameterState.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MnUserParameterState.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -22,10 +22,10 @@ namespace ROOT { class MinimumState; //_____________________________________________________________________________ -/** - class which holds the external user and/or internal Minuit representation - of the parameters and errors; - transformation internal <-> external on demand; +/** + class which holds the external user and/or internal Minuit representation + of the parameters and errors; + transformation internal <-> external on demand; */ class MnUserParameterState { @@ -33,9 +33,9 @@ class MnUserParameterState { public: /// default constructor (invalid state) - MnUserParameterState() : fValid(false), fCovarianceValid(false), fGCCValid(false), fCovStatus(-1), fFVal(0), fEDM(0), fNFcn(0), - fParameters(MnUserParameters()), fCovariance(MnUserCovariance()), - fIntParameters(std::vector<double>()), fIntCovariance(MnUserCovariance()) {} + MnUserParameterState() : fValid(false), fCovarianceValid(false), fGCCValid(false), fCovStatus(-1), fFVal(0), fEDM(0), fNFcn(0), + fParameters(MnUserParameters()), fCovariance(MnUserCovariance()), + fIntParameters(std::vector<double>()), fIntCovariance(MnUserCovariance()) {} /// construct from user parameters (before minimization) MnUserParameterState(const std::vector<double>&, const std::vector<double>&); @@ -55,10 +55,10 @@ public: ~MnUserParameterState() {} MnUserParameterState(const MnUserParameterState& state) : fValid(state.fValid), - fCovarianceValid(state.fCovarianceValid), fGCCValid(state.fGCCValid), fCovStatus(state.fCovStatus), + fCovarianceValid(state.fCovarianceValid), fGCCValid(state.fGCCValid), fCovStatus(state.fCovStatus), fFVal(state.fFVal), fEDM(state.fEDM), fNFcn(state.fNFcn), fParameters(state.fParameters), - fCovariance(state.fCovariance), + fCovariance(state.fCovariance), fGlobalCC(state.fGlobalCC), fIntParameters(state.fIntParameters), fIntCovariance(state.fIntCovariance) {} MnUserParameterState& operator=(const MnUserParameterState& state) { @@ -75,7 +75,7 @@ public: fGlobalCC = state.fGlobalCC; fIntParameters = state.fIntParameters; fIntCovariance = state.fIntCovariance; - } + } return *this; } @@ -92,7 +92,7 @@ public: const MnUserCovariance& IntCovariance() const {return fIntCovariance;} // covariance matrix status (0 = not valid, 1 approximate, 2, full but made pos def, 3 accurate and not pos def - int CovarianceStatus() const { return fCovStatus; } + int CovarianceStatus() const { return fCovStatus; } //transformation internal <-> external const MnUserTransformation& Trafo() const {return fParameters.Trafo();} @@ -103,7 +103,7 @@ public: double Fval() const {return fFVal;} double Edm() const {return fEDM;} - unsigned int NFcn() const {return fNFcn;} + unsigned int NFcn() const {return fNFcn;} public: @@ -112,7 +112,7 @@ public: //access to parameters (row-wise) const std::vector<ROOT::Minuit2::MinuitParameter>& MinuitParameters() const; - //access to parameters and errors in column-wise representation + //access to parameters and errors in column-wise representation std::vector<double> Params() const; std::vector<double> Errors() const; @@ -139,7 +139,7 @@ public: double Value(unsigned int) const; double Error(unsigned int) const; - + //interaction via Name of Parameter void Fix(const std::string &); void Release(const std::string &); @@ -152,11 +152,11 @@ public: double Value(const std::string &) const; double Error(const std::string &) const; - + //convert Name into external number of Parameter unsigned int Index(const std::string &) const; //convert external number into Name of Parameter - const std::string & GetName(unsigned int) const; + const std::string & GetName(unsigned int) const; // mantain interface with const char * for backward compatibility const char* Name(unsigned int) const; @@ -171,11 +171,11 @@ public: private: - + bool fValid; bool fCovarianceValid; bool fGCCValid; - int fCovStatus; // covariance matrix status + int fCovStatus; // covariance matrix status double fFVal; double fEDM; unsigned int fNFcn; diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MnUserParameters.h b/ThirdParty/RootMinimizers/inc/Minuit2/MnUserParameters.h index 59949ed849d48506baafb9cb06e66ea6250fe071..e2f6b1878257ff69ec23808f34bbb54ae78e04bc 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MnUserParameters.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MnUserParameters.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -25,12 +25,12 @@ class MnMachinePrecision; /** API class for the user interaction with the parameters; serves as input to the minimizer as well as output from it; users can interact: Fix/release parameters, set values and errors, etc.; - parameters can be accessed via their Parameter number (determined - internally by Minuit and followed the order how the parameters are created) - or via their user-specified Name (10 character string). + parameters can be accessed via their Parameter number (determined + internally by Minuit and followed the order how the parameters are created) + or via their user-specified Name (10 character string). Minuit has also an internal parameter number which is used during the minimization - (the fix parameter are skipped). The parameter number used in this class is the external - one. The class ROOT::Minuit2::MnUserTransformation is used to keep the + (the fix parameter are skipped). The parameter number used in this class is the external + one. The class ROOT::Minuit2::MnUserTransformation is used to keep the internal <-> external transformation */ @@ -44,7 +44,7 @@ public: ~MnUserParameters() {} - MnUserParameters(const MnUserParameters& par) : + MnUserParameters(const MnUserParameters& par) : fTransformation(par.fTransformation) {} MnUserParameters& operator=(const MnUserParameters& par) { @@ -61,7 +61,7 @@ public: /// access to parameters (row-wise) const std::vector<ROOT::Minuit2::MinuitParameter>& Parameters() const; - /// access to parameters and errors in column-wise representation + /// access to parameters and errors in column-wise representation std::vector<double> Params() const; std::vector<double> Errors() const; @@ -88,7 +88,7 @@ public: double Value(unsigned int) const; double Error(unsigned int) const; - + /// interaction via Name of Parameter void Fix(const std::string &); void Release(const std::string &); @@ -101,7 +101,7 @@ public: double Value(const std::string &) const; double Error(const std::string &) const; - + //convert Name into external number of Parameter unsigned int Index(const std::string &) const; //convert external number into Name of Parameter diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MnUserTransformation.h b/ThirdParty/RootMinimizers/inc/Minuit2/MnUserTransformation.h index f5b96823d09dfd44d5b6e8933769e6ace7727267..dfdc99820ae98e9321f1d4962fd398669d9c937a 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MnUserTransformation.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MnUserTransformation.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -44,7 +44,7 @@ class MnUserCovariance; // class MnMachinePrecision; -/** +/** class dealing with the transformation between user specified parameters (external) and internal parameters used for minimization */ @@ -65,13 +65,13 @@ public: ~MnUserTransformation() {} - MnUserTransformation(const MnUserTransformation& trafo) : + MnUserTransformation(const MnUserTransformation& trafo) : fPrecision(trafo.fPrecision), - fParameters(trafo.fParameters),fExtOfInt(trafo.fExtOfInt), - fDoubleLimTrafo(trafo.fDoubleLimTrafo), - fUpperLimTrafo(trafo.fUpperLimTrafo), + fParameters(trafo.fParameters),fExtOfInt(trafo.fExtOfInt), + fDoubleLimTrafo(trafo.fDoubleLimTrafo), + fUpperLimTrafo(trafo.fUpperLimTrafo), fLowerLimTrafo(trafo.fLowerLimTrafo), fCache(trafo.fCache) {} - + MnUserTransformation& operator=(const MnUserTransformation& trafo) { if(this != &trafo) { fPrecision = trafo.fPrecision; @@ -85,9 +85,9 @@ public: return *this; } - + //#ifdef MINUIT2_THREAD_SAFE - // thread-safe version (do not use cache) + // thread-safe version (do not use cache) std::vector<double> operator()(const MnAlgebraicVector&) const; //#else // not thread safe // const std::vector<double>& operator()(const MnAlgebraicVector&) const; @@ -114,7 +114,7 @@ public: unsigned int IntOfExt(unsigned int) const; // Index = internal Parameter - unsigned int ExtOfInt(unsigned int internal) const { + unsigned int ExtOfInt(unsigned int internal) const { assert(internal < fExtOfInt.size()); return fExtOfInt[internal]; } @@ -125,9 +125,9 @@ public: unsigned int VariableParameters() const {return static_cast<unsigned int> ( fExtOfInt.size() );} - // return initial parameter values (useful especially to get fixed parameter values) - const std::vector<double> & InitialParValues() const { - return fCache; + // return initial parameter values (useful especially to get fixed parameter values) + const std::vector<double> & InitialParValues() const { + return fCache; } @@ -136,7 +136,7 @@ public: const MnMachinePrecision& Precision() const {return fPrecision;} void SetPrecision(double eps) {fPrecision.SetPrecision(eps);} - /// access to parameters and errors in column-wise representation + /// access to parameters and errors in column-wise representation std::vector<double> Params() const; std::vector<double> Errors() const; @@ -164,7 +164,7 @@ public: double Value(unsigned int) const; double Error(unsigned int) const; - + //interaction via Name of Parameter void Fix(const std::string &); void Release(const std::string &); @@ -177,15 +177,15 @@ public: double Value(const std::string &) const; double Error(const std::string &) const; - + //convert Name into external number of Parameter (will assert if parameter is not found) unsigned int Index(const std::string &) const; - // find parameter index given a name. If it is not found return a -1 + // find parameter index given a name. If it is not found return a -1 int FindIndex(const std::string & ) const; //convert external number into Name of Parameter (will assert if index is out of range) - const std::string & GetName(unsigned int) const; - // mantain interface with const char * for backward compatibility + const std::string & GetName(unsigned int) const; + // mantain interface with const char * for backward compatibility const char* Name(unsigned int) const; private: diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/MnVectorTransform.h b/ThirdParty/RootMinimizers/inc/Minuit2/MnVectorTransform.h index 0895a44ddca7bd046e1549f2e38f5911b1ca78f4..2b872bba94a9ff859fc64c43f03ab5ad55077878 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/MnVectorTransform.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/MnVectorTransform.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -30,10 +30,10 @@ public: std::vector<double> result; result.reserve(avec.size()); for(unsigned int i = 0; i < avec.size(); i++) result.push_back(avec(i)); - + return result; } - + }; } // namespace Minuit2 diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/ModularFunctionMinimizer.h b/ThirdParty/RootMinimizers/inc/Minuit2/ModularFunctionMinimizer.h index a401459e121d291d1ab428aed405e5ee5eb62975..93c9c1357f9d1bd6f384614b59ef9673ec713899 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/ModularFunctionMinimizer.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/ModularFunctionMinimizer.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -41,7 +41,7 @@ class FumiliFCNBase; //_____________________________________________________________ /** Base common class providing the API for all the minimizer - Various Minimize methods are provided varying on the type of + Various Minimize methods are provided varying on the type of FCN function passesd and on the objects used for the parameters */ class ModularFunctionMinimizer : public FunctionMinimizer { @@ -51,13 +51,13 @@ public: virtual ~ModularFunctionMinimizer() {} // inherited interface - virtual FunctionMinimum Minimize(const FCNBase&, const std::vector<double>&, const std::vector<double>&, unsigned int stra=1, unsigned int maxfcn = 0, double toler = 0.1) const; + virtual FunctionMinimum Minimize(const FCNBase&, const std::vector<double>&, const std::vector<double>&, unsigned int stra=1, unsigned int maxfcn = 0, double toler = 0.1) const; - virtual FunctionMinimum Minimize(const FCNGradientBase&, const std::vector<double>&, const std::vector<double>&, unsigned int stra=1, unsigned int maxfcn = 0, double toler = 0.1) const; + virtual FunctionMinimum Minimize(const FCNGradientBase&, const std::vector<double>&, const std::vector<double>&, unsigned int stra=1, unsigned int maxfcn = 0, double toler = 0.1) const; - virtual FunctionMinimum Minimize(const FCNBase&, const std::vector<double>&, unsigned int, const std::vector<double>&, unsigned int stra=1, unsigned int maxfcn = 0, double toler = 0.1) const; + virtual FunctionMinimum Minimize(const FCNBase&, const std::vector<double>&, unsigned int, const std::vector<double>&, unsigned int stra=1, unsigned int maxfcn = 0, double toler = 0.1) const; - virtual FunctionMinimum Minimize(const FCNGradientBase&, const std::vector<double>&, unsigned int, const std::vector<double>&, unsigned int stra=1, unsigned int maxfcn = 0, double toler = 0.1) const; + virtual FunctionMinimum Minimize(const FCNGradientBase&, const std::vector<double>&, unsigned int, const std::vector<double>&, unsigned int stra=1, unsigned int maxfcn = 0, double toler = 0.1) const; // extension virtual FunctionMinimum Minimize(const FCNBase&, const MnUserParameters&, const MnStrategy&, unsigned int maxfcn = 0, double toler = 0.1) const; @@ -74,7 +74,7 @@ public: // for Fumili -// virtual FunctionMinimum Minimize(const FumiliFCNBase&, const std::vector<double>&, const std::vector<double>&, unsigned int stra=1, unsigned int maxfcn = 0, double toler = 0.1) const; +// virtual FunctionMinimum Minimize(const FumiliFCNBase&, const std::vector<double>&, const std::vector<double>&, unsigned int stra=1, unsigned int maxfcn = 0, double toler = 0.1) const; // virtual FunctionMinimum Minimize(const FumiliFCNBase&, const MnUserParameters&, const MnStrategy&, unsigned int maxfcn = 0, double toler = 0.1) const; @@ -89,7 +89,7 @@ public: public: - virtual FunctionMinimum Minimize(const MnFcn&, const GradientCalculator&, const MinimumSeed&, const MnStrategy&, unsigned int, double) const; + virtual FunctionMinimum Minimize(const MnFcn&, const GradientCalculator&, const MinimumSeed&, const MnStrategy&, unsigned int, double) const; }; diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/NegativeG2LineSearch.h b/ThirdParty/RootMinimizers/inc/Minuit2/NegativeG2LineSearch.h index 7e6bf0fc1040c923a2a360e1e8898a13f1a52bff..477a313a9b65fcd9b08d4ba506f98db9d43298b6 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/NegativeG2LineSearch.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/NegativeG2LineSearch.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -21,10 +21,10 @@ class GradientCalculator; class MnMachinePrecision; class FunctionGradient; -/** In case that one of the components of the second derivative g2 calculated - by the numerical Gradient calculator is negative, a 1dim line search in - the direction of that component is done in order to find a better position - where g2 is again positive. +/** In case that one of the components of the second derivative g2 calculated + by the numerical Gradient calculator is negative, a 1dim line search in + the direction of that component is done in order to find a better position + where g2 is again positive. */ class NegativeG2LineSearch { @@ -32,7 +32,7 @@ class NegativeG2LineSearch { public: NegativeG2LineSearch() {} - + ~NegativeG2LineSearch() {} MinimumState operator()(const MnFcn&, const MinimumState&, const GradientCalculator&, const MnMachinePrecision&) const; diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/Numerical2PGradientCalculator.h b/ThirdParty/RootMinimizers/inc/Minuit2/Numerical2PGradientCalculator.h index 7086f3ad5f266ecdf149a3f9b8d9a1b582e0f36e..357e5ca1017d076ef930ac27c626386e007bcb27 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/Numerical2PGradientCalculator.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/Numerical2PGradientCalculator.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -35,14 +35,14 @@ class MnStrategy; */ class Numerical2PGradientCalculator : public GradientCalculator { - + public: - - Numerical2PGradientCalculator(const MnFcn& fcn, + + Numerical2PGradientCalculator(const MnFcn& fcn, const MnUserTransformation& par, const MnStrategy& stra) : fFcn(fcn), fTransformation(par), fStrategy(stra) {} - + virtual ~Numerical2PGradientCalculator() {} virtual FunctionGradient operator()(const MinimumParameters&) const; @@ -59,7 +59,7 @@ public: const FunctionGradient&) const; const MnFcn& Fcn() const {return fFcn;} - const MnUserTransformation& Trafo() const {return fTransformation;} + const MnUserTransformation& Trafo() const {return fTransformation;} const MnMachinePrecision& Precision() const; const MnStrategy& Strategy() const {return fStrategy;} @@ -70,7 +70,7 @@ public: private: const MnFcn& fFcn; - const MnUserTransformation& fTransformation; + const MnUserTransformation& fTransformation; const MnStrategy& fStrategy; }; diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/ParametricFunction.h b/ThirdParty/RootMinimizers/inc/Minuit2/ParametricFunction.h index 6216e68c54a634f487d375e23ab46e9b38c66aca..dbaa8973b1052be8433eb38f65c4ee71373cacfc 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/ParametricFunction.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/ParametricFunction.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -22,20 +22,20 @@ namespace ROOT { -/** +/** Function which has parameters. For example, one could define a one-dimensional Gaussian, by considering x as an input coordinate for the evaluation of the function, and the mean and the square root of the variance as parameters. <p> -AS OF NOW PARAMETRICFUNCTION INHERITS FROM FCNBASE INSTEAD OF +AS OF NOW PARAMETRICFUNCTION INHERITS FROM FCNBASE INSTEAD OF GENERICFUNCTION. THIS IS ONLY BECAUSE NUMERICAL2PGRADIENTCALCULATOR NEEDS AN FCNBASE OBJECT AND WILL BE CHANGED!!!!!!!!!!!!!!!! @ingroup Minuit -\todo ParametricFunction and all the classes that inherit from it +\todo ParametricFunction and all the classes that inherit from it are inheriting also FCNBase so that the Gradient calculation has the Up() member function. That is not really good... @@ -49,13 +49,13 @@ public: /** - Constructor which initializes the ParametricFunction with the + Constructor which initializes the ParametricFunction with the parameters given as input. @param params vector containing the initial Parameter values */ - + ParametricFunction(const std::vector<double>& params) : par(params) {} @@ -179,7 +179,7 @@ public: protected: /** - + The vector containing the parameters of the function It is mutable for "historical reasons" as in the hierarchy methods and classes are const and all the implications of changing @@ -195,5 +195,5 @@ public: } // namespace Minuit2 } // namespace ROOT - + #endif // ROOT_Minuit2_ParametricFunction diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/ScanBuilder.h b/ThirdParty/RootMinimizers/inc/Minuit2/ScanBuilder.h index f9651227ae1934076e41b90a9af302bd26dc890a..dd2d3c216d34254f34aa88336fc560f3d50b7274 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/ScanBuilder.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/ScanBuilder.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/ScanMinimizer.h b/ThirdParty/RootMinimizers/inc/Minuit2/ScanMinimizer.h index cb7f27cd523b47c137ce808b2e0a11ae1e1a29c8..6c279735adecf60f59db34b786c762b5ab846cc0 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/ScanMinimizer.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/ScanMinimizer.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -31,17 +31,17 @@ class ScanMinimizer : public ModularFunctionMinimizer { public: - ScanMinimizer() : fSeedGenerator(SimplexSeedGenerator()), + ScanMinimizer() : fSeedGenerator(SimplexSeedGenerator()), fBuilder(ScanBuilder()) {} - + ~ScanMinimizer() {} - + const MinimumSeedGenerator& SeedGenerator() const {return fSeedGenerator;} const MinimumBuilder& Builder() const {return fBuilder;} MinimumBuilder& Builder() {return fBuilder;} - + private: - + SimplexSeedGenerator fSeedGenerator; ScanBuilder fBuilder; }; diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/SimplexBuilder.h b/ThirdParty/RootMinimizers/inc/Minuit2/SimplexBuilder.h index 28d36c6f219fc684e069d12e2a9cbc94a5ea6b7f..e788aa29b992c929bd9faf61fdd1f6fb3bd75a79 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/SimplexBuilder.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/SimplexBuilder.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/SimplexMinimizer.h b/ThirdParty/RootMinimizers/inc/Minuit2/SimplexMinimizer.h index a083e7342105a223848d3ec8c2269daaa7e34a69..82481576417e3eb79770b3b96cb2419ab3dea7cb 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/SimplexMinimizer.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/SimplexMinimizer.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -31,7 +31,7 @@ class SimplexMinimizer : public ModularFunctionMinimizer { public: - SimplexMinimizer() : fSeedGenerator(SimplexSeedGenerator()), + SimplexMinimizer() : fSeedGenerator(SimplexSeedGenerator()), fBuilder(SimplexBuilder()) {} ~SimplexMinimizer() {} diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/SimplexParameters.h b/ThirdParty/RootMinimizers/inc/Minuit2/SimplexParameters.h index c2172971b4e58a7b3b9db69633b6964be980c178..c5dd94c96e048504128f2f2dece9233488031983 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/SimplexParameters.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/SimplexParameters.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -22,8 +22,8 @@ namespace ROOT { namespace Minuit2 { /** - class describing the simplex set of points (f(x), x ) which evolve during the minimization - iteration process. + class describing the simplex set of points (f(x), x ) which evolve during the minimization + iteration process. */ class SimplexParameters { @@ -34,8 +34,8 @@ public: ~SimplexParameters() {} - void Update(double, const MnAlgebraicVector&); - + void Update(double, const MnAlgebraicVector&); + const std::vector<std::pair<double, MnAlgebraicVector> >& Simplex() const { return fSimplexParameters; } @@ -44,7 +44,7 @@ public: assert(i < fSimplexParameters.size()); return fSimplexParameters[i]; } - + unsigned int Jh() const {return fJHigh;} unsigned int Jl() const {return fJLow;} double Edm() const {return fSimplexParameters[Jh()].first - fSimplexParameters[Jl()].first;} diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/SimplexSeedGenerator.h b/ThirdParty/RootMinimizers/inc/Minuit2/SimplexSeedGenerator.h index 7ea2b719a4410863a887e56f9116c6a084ff269a..2433d4ac70f96c891ec6c78b3b18142de02c5733 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/SimplexSeedGenerator.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/SimplexSeedGenerator.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/SinParameterTransformation.h b/ThirdParty/RootMinimizers/inc/Minuit2/SinParameterTransformation.h index 7b8040befd18831c9c30fe4103aa4b023dcff3ff..a6924dfe1d79de28a539d1408010e0d84047f288 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/SinParameterTransformation.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/SinParameterTransformation.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -19,8 +19,8 @@ class MnMachinePrecision; /** class for the transformation for double-limited parameter - Using a sin function one goes from a double-limited parameter range to - an unlimited one + Using a sin function one goes from a double-limited parameter range to + an unlimited one */ class SinParameterTransformation { @@ -31,7 +31,7 @@ public: ~SinParameterTransformation() {} double Int2ext(double Value, double Upper, double Lower) const; - double Ext2int(double Value, double Upper, double Lower, + double Ext2int(double Value, double Upper, double Lower, const MnMachinePrecision&) const; double DInt2Ext(double Value, double Upper, double Lower) const; diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/SqrtLowParameterTransformation.h b/ThirdParty/RootMinimizers/inc/Minuit2/SqrtLowParameterTransformation.h index 8c8ebfcbdbdb84c7ca06aa6ad39f878f95906ed7..61571d4b3f13b3d5715213f357466bbc6007ebc7 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/SqrtLowParameterTransformation.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/SqrtLowParameterTransformation.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -9,7 +9,7 @@ // Project : LCG // Package : Minuit -// Author : Lorenzo.MONETA@cern.ch +// Author : Lorenzo.MONETA@cern.ch // Created by: moneta at Thu Apr 8 10:26:22 2004 @@ -24,33 +24,33 @@ class MnMachinePrecision; /** - * Transformation from external to internal Parameter based on sqrt(1 + x**2) - * - * This transformation applies for the case of single side Lower Parameter limits + * Transformation from external to internal Parameter based on sqrt(1 + x**2) + * + * This transformation applies for the case of single side Lower Parameter limits */ class SqrtLowParameterTransformation /* : public ParameterTransformation */ { -public: - +public: + SqrtLowParameterTransformation() {} ~SqrtLowParameterTransformation() {} - // transformation from internal to external + // transformation from internal to external double Int2ext(double Value, double Lower) const; - + // transformation from external to internal double Ext2int(double Value, double Lower, const MnMachinePrecision&) const; - // derivative of transformation from internal to external + // derivative of transformation from internal to external double DInt2Ext(double Value, double Lower) const; private: -}; +}; } // namespace Minuit2 } // namespace ROOT -#endif +#endif diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/SqrtUpParameterTransformation.h b/ThirdParty/RootMinimizers/inc/Minuit2/SqrtUpParameterTransformation.h index 89646c0fcc48b30a33940fe27a2abcfe74f98bd4..ff127ffed5e4db92c3a06a2afbd1995188ee56a9 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/SqrtUpParameterTransformation.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/SqrtUpParameterTransformation.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -9,7 +9,7 @@ // Project : LCG // Package : Minuit -// Author : Lorenzo.MONETA@cern.ch +// Author : Lorenzo.MONETA@cern.ch // Created by: moneta at Thu Apr 8 10:26:22 2004 @@ -26,35 +26,35 @@ class MnMachinePrecision; /** - * Transformation from external to internal Parameter based on sqrt(1 + x**2) - * - * This transformation applies for the case of single side Upper Parameter limits + * Transformation from external to internal Parameter based on sqrt(1 + x**2) + * + * This transformation applies for the case of single side Upper Parameter limits */ class SqrtUpParameterTransformation /* : public ParameterTransformation */ { -public: - +public: + // create with user defined precision SqrtUpParameterTransformation() {} - + ~SqrtUpParameterTransformation() {} - - // transformation from internal to external + + // transformation from internal to external double Int2ext(double Value, double Upper) const; - + // transformation from external to internal double Ext2int(double Value, double Upper, const MnMachinePrecision&) const; - // derivative of transformation from internal to external + // derivative of transformation from internal to external double DInt2Ext(double Value, double Upper) const; private: - -}; + +}; } // namespace Minuit2 } // namespace ROOT -#endif +#endif diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/StackAllocator.h b/ThirdParty/RootMinimizers/inc/Minuit2/StackAllocator.h index 5b53d04438639771dc045ed0a132f34e583e2076..8d54ff7dfd6e4bd05d3e3dee59e073a3d97eb544 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/StackAllocator.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/StackAllocator.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -12,10 +12,10 @@ #include "Minuit2/MnConfig.h" -// comment out this line and recompile if you want to gain additional +// comment out this line and recompile if you want to gain additional // performance (the gain is mainly for "simple" functions which are easy // to calculate and vanishes quickly if going to cost-intensive functions) -// the library is no longer thread save however +// the library is no longer thread save however #ifdef MN_USE_STACK_ALLOC #define _MN_NO_THREAD_SAVE_ @@ -35,7 +35,7 @@ namespace ROOT { /// define stack allocator symbol - + class StackOverflow {}; @@ -84,7 +84,7 @@ public: WriteInt( fStackOffset, fStackOffset+nAlloc); // write the start position of the new block at the end of the block WriteInt( fStackOffset + nAlloc - sizeof(int), fStackOffset); - + void* result = fStack + fStackOffset + sizeof(int); fStackOffset += nAlloc; fBlockCount++; @@ -92,7 +92,7 @@ public: #ifdef DEBUG_ALLOCATOR CheckConsistency(); #endif - + #else void* result = malloc(nBytes); if (!result) throw std::bad_alloc(); @@ -100,14 +100,14 @@ public: return result; } - + void Deallocate( void* p) { #ifdef _MN_NO_THREAD_SAVE_ // int previousOffset = ReadInt( fStackOffset - sizeof(int)); int delBlock = ToInt(p); int nextBlock = ReadInt( delBlock); int previousBlock = ReadInt( nextBlock - sizeof(int)); - if ( nextBlock == fStackOffset) { + if ( nextBlock == fStackOffset) { // deallocating last allocated fStackOffset = previousBlock; } @@ -126,21 +126,21 @@ public: #else free(p); #endif - // cout << "Block at " << delBlock - // << " deallocated, fStackOffset = " << fStackOffset << endl; + // std::cout << "Block at " << delBlock + // << " deallocated, fStackOffset = " << fStackOffset << std::endl; } int ReadInt( int offset) { int* ip = (int*)(fStack+offset); - // cout << "read " << *ip << " from offset " << offset << endl; + // std::cout << "read " << *ip << " from offset " << offset << std::endl; return *ip; } void WriteInt( int offset, int Value) { - // cout << "writing " << Value << " to offset " << offset << endl; + // std::cout << "writing " << Value << " to offset " << offset << std::endl; int* ip = reinterpret_cast<int*>(fStack+offset); *ip = Value; @@ -149,8 +149,8 @@ public: int ToInt( void* p) { unsigned char* pc = static_cast<unsigned char*>(p); - // cout << "toInt: p = " << p << " fStack = " << (void*) fStack << endl; - // VC 7.1 warning:conversin from __w64 int to int + // std::cout << "toInt: p = " << p << " fStack = " << (void*) fStack << std::endl; + // VC 7.1 warning:conversin from __w64 int to int int userBlock = pc - fStack; return userBlock - sizeof(int); // correct for starting int } @@ -179,8 +179,8 @@ public: while (beg < fStackOffset) { end = ReadInt( beg); - // cout << "beg = " << beg << " end = " << end - // << " fStackOffset = " << fStackOffset << endl; + // std::cout << "beg = " << beg << " end = " << end + // << " fStackOffset = " << fStackOffset << std::endl; int beg2 = ReadInt( end - sizeof(int)); if ( beg != beg2) { @@ -213,19 +213,19 @@ private: -class StackAllocatorHolder { - - // t.b.d need to use same trick as Boost singleton.hpp to be sure that - // StackAllocator is created before main() +class StackAllocatorHolder { - public: + // t.b.d need to use same trick as Boost singleton.hpp to be sure that + // StackAllocator is created before main() - - static StackAllocator & Get() { - static StackAllocator gStackAllocator; - return gStackAllocator; + public: + + + static StackAllocator & Get() { + static StackAllocator gStackAllocator; + return gStackAllocator; } -}; +}; diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/VariableMetricBuilder.h b/ThirdParty/RootMinimizers/inc/Minuit2/VariableMetricBuilder.h index dba130c7941cea6da8134c8a20f32da21605f85b..f6c863e2fe81003ca6ec0af419bed35a11c71187 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/VariableMetricBuilder.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/VariableMetricBuilder.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -22,14 +22,14 @@ namespace ROOT { namespace Minuit2 { /** - Build (find) function minimum using the Variable Metric method (MIGRAD) + Build (find) function minimum using the Variable Metric method (MIGRAD) */ class VariableMetricBuilder : public MinimumBuilder { public: - VariableMetricBuilder() : fEstimator(VariableMetricEDMEstimator()), + VariableMetricBuilder() : fEstimator(VariableMetricEDMEstimator()), fErrorUpdator(DavidonErrorUpdator()) {} ~VariableMetricBuilder() {} @@ -40,7 +40,7 @@ public: const VariableMetricEDMEstimator& Estimator() const {return fEstimator;} const DavidonErrorUpdator& ErrorUpdator() const {return fErrorUpdator;} - + void AddResult(std::vector<MinimumState>& result, const MinimumState & state, bool store = false) const; private: diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/VariableMetricEDMEstimator.h b/ThirdParty/RootMinimizers/inc/Minuit2/VariableMetricEDMEstimator.h index 7ca7abb8240d50ae75bb0edfa925c63a18d05163..a2800abd4afe5cb9284c9dcd18be43bfbcc9f590 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/VariableMetricEDMEstimator.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/VariableMetricEDMEstimator.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -23,7 +23,7 @@ class VariableMetricEDMEstimator { public: VariableMetricEDMEstimator() {} - + ~VariableMetricEDMEstimator() {} double Estimate(const FunctionGradient&, const MinimumError&) const; diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/VariableMetricMinimizer.h b/ThirdParty/RootMinimizers/inc/Minuit2/VariableMetricMinimizer.h index cbbbc9137513d6787212a432d5f51952f7ff995f..d7d2edea84b6c0d5786fece35b65798d3a9e9185 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/VariableMetricMinimizer.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/VariableMetricMinimizer.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -20,11 +20,11 @@ namespace ROOT { namespace Minuit2 { //______________________________________________________________________________ -/** +/** Instantiates the SeedGenerator and MinimumBuilder for Variable Metric Minimization method. API is provided in the upper ROOT::Minuit2::ModularFunctionMinimizer class - + */ class VariableMetricMinimizer : public ModularFunctionMinimizer { @@ -33,7 +33,7 @@ public: VariableMetricMinimizer() : fMinSeedGen(MnSeedGenerator()), fMinBuilder(VariableMetricBuilder()) {} - + ~VariableMetricMinimizer() {} const MinimumSeedGenerator& SeedGenerator() const {return fMinSeedGen;} diff --git a/ThirdParty/RootMinimizers/inc/Minuit2/VectorOuterProduct.h b/ThirdParty/RootMinimizers/inc/Minuit2/VectorOuterProduct.h index 909177737bf25a456e81e3f4f37d51e264ae8b85..9d705da6d154e955b6a9947601029777ec0cf8d3 100644 --- a/ThirdParty/RootMinimizers/inc/Minuit2/VectorOuterProduct.h +++ b/ThirdParty/RootMinimizers/inc/Minuit2/VectorOuterProduct.h @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * diff --git a/ThirdParty/RootMinimizers/src/Math/BasicMinimizer.cxx b/ThirdParty/RootMinimizers/src/Math/BasicMinimizer.cxx index 0004f5a3077632423967875f2873a238a67b14fe..fe3109bf087d69c33120d8a16117b907c51a0abe 100644 --- a/ThirdParty/RootMinimizers/src/Math/BasicMinimizer.cxx +++ b/ThirdParty/RootMinimizers/src/Math/BasicMinimizer.cxx @@ -30,174 +30,174 @@ #include <algorithm> #include <functional> #include <ctype.h> // need to use c version of tolower defined here -#include <limits> +#include <limits> -namespace ROOT { +namespace ROOT { - namespace Math { + namespace Math { -BasicMinimizer::BasicMinimizer( ) : - fDim(0), +BasicMinimizer::BasicMinimizer( ) : + fDim(0), fObjFunc(0), fMinVal(0) { - fValues.reserve(10); - fNames.reserve(10); - fSteps.reserve(10); + fValues.reserve(10); + fNames.reserve(10); + fSteps.reserve(10); int niter = ROOT::Math::MinimizerOptions::DefaultMaxIterations(); - if (niter <=0 ) niter = 1000; + if (niter <=0 ) niter = 1000; SetMaxIterations(niter); SetPrintLevel(ROOT::Math::MinimizerOptions::DefaultPrintLevel()); } -BasicMinimizer::~BasicMinimizer () { - if (fObjFunc) delete fObjFunc; +BasicMinimizer::~BasicMinimizer () { + if (fObjFunc) delete fObjFunc; } -bool BasicMinimizer::SetVariable(unsigned int ivar, const std::string & name, double val, double step) { - // set variable in minimizer - support only free variables +bool BasicMinimizer::SetVariable(unsigned int ivar, const std::string & name, double val, double step) { + // set variable in minimizer - support only free variables // no transformation implemented - so far - if (ivar > fValues.size() ) return false; - if (ivar == fValues.size() ) { - fValues.push_back(val); + if (ivar > fValues.size() ) return false; + if (ivar == fValues.size() ) { + fValues.push_back(val); fNames.push_back(name); - fSteps.push_back(step); - fVarTypes.push_back(kDefault); + fSteps.push_back(step); + fVarTypes.push_back(kDefault); } - else { - fValues[ivar] = val; + else { + fValues[ivar] = val; fNames[ivar] = name; - fSteps[ivar] = step; - fVarTypes[ivar] = kDefault; + fSteps[ivar] = step; + fVarTypes[ivar] = kDefault; // remove bounds if needed - std::map<unsigned int, std::pair<double, double> >::iterator iter = fBounds.find(ivar); - if ( iter != fBounds.end() ) fBounds.erase (iter); + std::map<unsigned int, std::pair<double, double> >::iterator iter = fBounds.find(ivar); + if ( iter != fBounds.end() ) fBounds.erase (iter); } - return true; + return true; } -bool BasicMinimizer::SetLowerLimitedVariable(unsigned int ivar, const std::string & name, double val, double step, double lower) { +bool BasicMinimizer::SetLowerLimitedVariable(unsigned int ivar, const std::string & name, double val, double step, double lower) { // set lower limited variable - bool ret = SetVariable(ivar, name, val, step); - if (!ret) return false; - const double upper = std::numeric_limits<double>::infinity(); + bool ret = SetVariable(ivar, name, val, step); + if (!ret) return false; + const double upper = std::numeric_limits<double>::infinity(); fBounds[ivar] = std::make_pair( lower, upper); - fVarTypes[ivar] = kLowBound; - return true; + fVarTypes[ivar] = kLowBound; + return true; } -bool BasicMinimizer::SetUpperLimitedVariable(unsigned int ivar, const std::string & name, double val, double step, double upper ) { +bool BasicMinimizer::SetUpperLimitedVariable(unsigned int ivar, const std::string & name, double val, double step, double upper ) { // set upper limited variable - bool ret = SetVariable(ivar, name, val, step); - if (!ret) return false; - const double lower = -std::numeric_limits<double>::infinity(); + bool ret = SetVariable(ivar, name, val, step); + if (!ret) return false; + const double lower = -std::numeric_limits<double>::infinity(); fBounds[ivar] = std::make_pair( lower, upper); - fVarTypes[ivar] = kUpBound; - return true; + fVarTypes[ivar] = kUpBound; + return true; } -bool BasicMinimizer::SetLimitedVariable(unsigned int ivar, const std::string & name, double val, double step, double lower, double upper) { +bool BasicMinimizer::SetLimitedVariable(unsigned int ivar, const std::string & name, double val, double step, double lower, double upper) { // set double bounded variable - bool ret = SetVariable(ivar, name, val, step); - if (!ret) return false; + bool ret = SetVariable(ivar, name, val, step); + if (!ret) return false; fBounds[ivar] = std::make_pair( lower, upper); - fVarTypes[ivar] = kBounds; - return true; + fVarTypes[ivar] = kBounds; + return true; } -bool BasicMinimizer::SetFixedVariable(unsigned int ivar , const std::string & name , double val ) { - /// set fixed variable - bool ret = SetVariable(ivar, name, val, 0.); - if (!ret) return false; - fVarTypes[ivar] = kFix; - return true; +bool BasicMinimizer::SetFixedVariable(unsigned int ivar , const std::string & name , double val ) { + /// set fixed variable + bool ret = SetVariable(ivar, name, val, 0.); + if (!ret) return false; + fVarTypes[ivar] = kFix; + return true; } -bool BasicMinimizer::SetVariableValue(unsigned int ivar, double val) { - // set variable value in minimizer +bool BasicMinimizer::SetVariableValue(unsigned int ivar, double val) { + // set variable value in minimizer // no change to transformation or variable status - if (ivar > fValues.size() ) return false; - fValues[ivar] = val; - return true; + if (ivar > fValues.size() ) return false; + fValues[ivar] = val; + return true; } -bool BasicMinimizer::SetVariableValues( const double * x) { - // set all variable values in minimizer - if (x == 0) return false; +bool BasicMinimizer::SetVariableValues( const double * x) { + // set all variable values in minimizer + if (x == 0) return false; std::copy(x,x+fValues.size(), fValues.begin() ); - return true; + return true; } -bool BasicMinimizer::SetVariableStepSize(unsigned int ivar, double step) { +bool BasicMinimizer::SetVariableStepSize(unsigned int ivar, double step) { // set step size - if (ivar > fValues.size() ) return false; - fSteps[ivar] = step; - return true; + if (ivar > fValues.size() ) return false; + fSteps[ivar] = step; + return true; } -bool BasicMinimizer::SetVariableLowerLimit(unsigned int ivar, double lower) { +bool BasicMinimizer::SetVariableLowerLimit(unsigned int ivar, double lower) { // set variable lower limit double upper = (fBounds.count(ivar)) ? fBounds[ivar].second : std::numeric_limits<double>::infinity(); return SetVariableLimits(ivar, lower, upper); } -bool BasicMinimizer::SetVariableUpperLimit(unsigned int ivar, double upper) { +bool BasicMinimizer::SetVariableUpperLimit(unsigned int ivar, double upper) { // set variable upper limit double lower = (fBounds.count(ivar)) ? fBounds[ivar].first : - std::numeric_limits<double>::infinity(); return SetVariableLimits(ivar, lower, upper); } -bool BasicMinimizer::SetVariableLimits(unsigned int ivar, double lower, double upper) { +bool BasicMinimizer::SetVariableLimits(unsigned int ivar, double lower, double upper) { // set variable limits (remove limits if lower >= upper) - if (ivar > fVarTypes.size() ) return false; - // if limits do not exists add them or update + if (ivar > fVarTypes.size() ) return false; + // if limits do not exists add them or update fBounds[ivar] = std::make_pair( lower, upper); - if (lower > upper || (lower == - std::numeric_limits<double>::infinity() && - upper == std::numeric_limits<double>::infinity() ) ) { + if (lower > upper || (lower == - std::numeric_limits<double>::infinity() && + upper == std::numeric_limits<double>::infinity() ) ) { fBounds.erase(ivar); - fVarTypes[ivar] = kDefault; + fVarTypes[ivar] = kDefault; } - else if (lower == upper) - FixVariable(ivar); + else if (lower == upper) + FixVariable(ivar); else { if (lower == - std::numeric_limits<double>::infinity() ) - fVarTypes[ivar] = kLowBound; + fVarTypes[ivar] = kLowBound; else if (upper == std::numeric_limits<double>::infinity() ) - fVarTypes[ivar] = kUpBound; + fVarTypes[ivar] = kUpBound; else - fVarTypes[ivar] = kBounds; + fVarTypes[ivar] = kBounds; } - return true; + return true; } bool BasicMinimizer::FixVariable(unsigned int ivar) { // fix variable - if (ivar > fVarTypes.size() ) return false; - fVarTypes[ivar] = kFix; - return true; + if (ivar > fVarTypes.size() ) return false; + fVarTypes[ivar] = kFix; + return true; } bool BasicMinimizer::ReleaseVariable(unsigned int ivar) { // fix variable if (ivar > fVarTypes.size() ) return false; if (fBounds.count(ivar) == 0) { - fVarTypes[ivar] = kDefault; - return true; + fVarTypes[ivar] = kDefault; + return true; } if (fBounds[ivar].first == - std::numeric_limits<double>::infinity() ) - fVarTypes[ivar] = kLowBound; + fVarTypes[ivar] = kLowBound; else if (fBounds[ivar].second == std::numeric_limits<double>::infinity() ) - fVarTypes[ivar] = kUpBound; + fVarTypes[ivar] = kUpBound; else - fVarTypes[ivar] = kBounds; - - return true; + fVarTypes[ivar] = kBounds; + + return true; } bool BasicMinimizer::IsFixedVariable(unsigned int ivar) const { @@ -209,151 +209,151 @@ bool BasicMinimizer::GetVariableSettings(unsigned int ivar, ROOT::Fit::Parameter if (ivar > fValues.size() ) return false; assert(fValues.size() == fNames.size() && fValues.size() == fVarTypes.size() ); varObj.Set(fNames[ivar],fValues[ivar],fSteps[ivar]); - std::map< unsigned int , std::pair< double, double> >::const_iterator itr = fBounds.find(ivar); + std::map< unsigned int , std::pair< double, double> >::const_iterator itr = fBounds.find(ivar); if (itr != fBounds.end() ) { double lower = (itr->second).first; double upper = (itr->second).second; - if (fVarTypes[ivar] == kLowBound) varObj.SetLowerLimit( lower ); - if (fVarTypes[ivar] == kUpBound) varObj.SetUpperLimit( upper ); - else varObj.SetLimits( lower,upper); + if (fVarTypes[ivar] == kLowBound) varObj.SetLowerLimit( lower ); + if (fVarTypes[ivar] == kUpBound) varObj.SetUpperLimit( upper ); + else varObj.SetLimits( lower,upper); } if (fVarTypes[ivar] == kFix ) varObj.Fix(); return true; } -std::string BasicMinimizer::VariableName(unsigned int ivar) const { +std::string BasicMinimizer::VariableName(unsigned int ivar) const { if (ivar > fNames.size() ) return ""; - return fNames[ivar]; + return fNames[ivar]; } -int BasicMinimizer::VariableIndex(const std::string & name) const { +int BasicMinimizer::VariableIndex(const std::string & name) const { std::vector<std::string>::const_iterator itr = std::find( fNames.begin(), fNames.end(), name); - if (itr == fNames.end() ) return -1; + if (itr == fNames.end() ) return -1; return itr - fNames.begin(); } - -void BasicMinimizer::SetFunction(const ROOT::Math::IMultiGenFunction & func) { - // set the function to minimizer + +void BasicMinimizer::SetFunction(const ROOT::Math::IMultiGenFunction & func) { + // set the function to minimizer fObjFunc = func.Clone(); fDim = fObjFunc->NDim(); } -void BasicMinimizer::SetFunction(const ROOT::Math::IMultiGradFunction & func) { - // set the function to minimize - fObjFunc = dynamic_cast<const ROOT::Math::IMultiGradFunction *>( func.Clone()); +void BasicMinimizer::SetFunction(const ROOT::Math::IMultiGradFunction & func) { + // set the function to minimize + fObjFunc = dynamic_cast<const ROOT::Math::IMultiGradFunction *>( func.Clone()); assert(fObjFunc != 0); - fDim = fObjFunc->NDim(); + fDim = fObjFunc->NDim(); } -bool BasicMinimizer::CheckDimension() const { - unsigned int npar = fValues.size(); - if (npar == 0 || npar < fDim ) { +bool BasicMinimizer::CheckDimension() const { + unsigned int npar = fValues.size(); + if (npar == 0 || npar < fDim ) { MATH_ERROR_MSGVAL("BasicMinimizer::CheckDimension","Wrong number of parameters",npar); return false; } - return true; + return true; } -bool BasicMinimizer::CheckObjFunction() const { - if (fObjFunc == 0) { +bool BasicMinimizer::CheckObjFunction() const { + if (fObjFunc == 0) { MATH_ERROR_MSG("BasicMinimizer::CheckFunction","Function has not been set"); - return false; + return false; } - return true; + return true; } -MinimTransformFunction * BasicMinimizer::CreateTransformation(std::vector<double> & startValues, const ROOT::Math::IMultiGradFunction * func) { +MinimTransformFunction * BasicMinimizer::CreateTransformation(std::vector<double> & startValues, const ROOT::Math::IMultiGradFunction * func) { - bool doTransform = (fBounds.size() > 0); - unsigned int ivar = 0; + bool doTransform = (fBounds.size() > 0); + unsigned int ivar = 0; while (!doTransform && ivar < fVarTypes.size() ) { doTransform = (fVarTypes[ivar++] != kDefault ); } startValues = std::vector<double>(fValues.begin(), fValues.end() ); - MinimTransformFunction * trFunc = 0; - + MinimTransformFunction * trFunc = 0; + // in case of transformation wrap objective function in a new transformation function // and transform from external variables to internals one // Transformations are supported only for gradient function - const IMultiGradFunction * gradObjFunc = (func) ? func : dynamic_cast<const IMultiGradFunction *>(fObjFunc); - doTransform &= (gradObjFunc != 0); + const IMultiGradFunction * gradObjFunc = (func) ? func : dynamic_cast<const IMultiGradFunction *>(fObjFunc); + doTransform &= (gradObjFunc != 0); - if (doTransform) { + if (doTransform) { // minim transform function manages the passed function pointer (gradObjFunc) - trFunc = new MinimTransformFunction ( gradObjFunc, fVarTypes, fValues, fBounds ); + trFunc = new MinimTransformFunction ( gradObjFunc, fVarTypes, fValues, fBounds ); // transform from external to internal - trFunc->InvTransformation(&fValues.front(), &startValues[0]); - // size can be different since internal parameter can have smaller size + trFunc->InvTransformation(&fValues.front(), &startValues[0]); + // size can be different since internal parameter can have smaller size // if there are fixed parameters startValues.resize( trFunc->NDim() ); - // no need to save fObjFunc since trFunc will manage it - fObjFunc = trFunc; + // no need to save fObjFunc since trFunc will manage it + fObjFunc = trFunc; } - else { + else { if (func) fObjFunc = func; // to manege the passed function object } -// std::cout << " f has transform " << doTransform << " " << fBounds.size() << " " << startValues.size() << " ndim " << fObjFunc->NDim() << std::endl; std::cout << "InitialValues external : "; -// for (int i = 0; i < fValues.size(); ++i) std::cout << fValues[i] << " "; +// std::cout << " f has transform " << doTransform << " " << fBounds.size() << " " << startValues.size() << " ndim " << fObjFunc->NDim() << std::endl; std::cout << "InitialValues external : "; +// for (int i = 0; i < fValues.size(); ++i) std::cout << fValues[i] << " "; // std::cout << "\n"; -// std::cout << "InitialValues internal : "; -// for (int i = 0; i < startValues.size(); ++i) std::cout << startValues[i] << " "; +// std::cout << "InitialValues internal : "; +// for (int i = 0; i < startValues.size(); ++i) std::cout << startValues[i] << " "; // std::cout << "\n"; - return trFunc; + return trFunc; } -bool BasicMinimizer::Minimize() { +bool BasicMinimizer::Minimize() { - // do nothing - return false; + // do nothing + return false; } -void BasicMinimizer::SetFinalValues(const double * x) { - // check to see if a transformation need to be applied +void BasicMinimizer::SetFinalValues(const double * x) { + // check to see if a transformation need to be applied const MinimTransformFunction * trFunc = TransformFunction(); - if (trFunc) { - assert(fValues.size() >= trFunc->NTot() ); + if (trFunc) { + assert(fValues.size() >= trFunc->NTot() ); trFunc->Transformation(x, &fValues[0]); } - else { - // case of no transformation applied - assert( fValues.size() >= NDim() ); - std::copy(x, x + NDim(), fValues.begin() ); + else { + // case of no transformation applied + assert( fValues.size() >= NDim() ); + std::copy(x, x + NDim(), fValues.begin() ); } } -void BasicMinimizer::PrintResult() const { +void BasicMinimizer::PrintResult() const { int pr = std::cout.precision(18); std::cout << "FVAL = " << fMinVal << std::endl; std::cout.precision(pr); // std::cout << "Edm = " << fState.Edm() << std::endl; std::cout << "Niterations = " << NIterations() << std::endl; - unsigned int ncalls = NCalls(); + unsigned int ncalls = NCalls(); if (ncalls) std::cout << "NCalls = " << ncalls << std::endl; - for (unsigned int i = 0; i < fDim; ++i) - std::cout << fNames[i] << "\t = " << fValues[i] << std::endl; + for (unsigned int i = 0; i < fDim; ++i) + std::cout << fNames[i] << "\t = " << fValues[i] << std::endl; } -const ROOT::Math::IMultiGradFunction * BasicMinimizer::GradObjFunction() const { +const ROOT::Math::IMultiGradFunction * BasicMinimizer::GradObjFunction() const { return dynamic_cast<const ROOT::Math::IMultiGradFunction *>(fObjFunc); } -const MinimTransformFunction * BasicMinimizer::TransformFunction() const { +const MinimTransformFunction * BasicMinimizer::TransformFunction() const { return dynamic_cast<const MinimTransformFunction *>(fObjFunc); } unsigned int BasicMinimizer::NFree() const { // number of free variables - unsigned int nfree = fValues.size(); - for (unsigned int i = 0; i < fVarTypes.size(); ++i) + unsigned int nfree = fValues.size(); + for (unsigned int i = 0; i < fVarTypes.size(); ++i) if (fVarTypes[i] == kFix) nfree--; return nfree; } diff --git a/ThirdParty/RootMinimizers/src/Math/Derivator.cxx b/ThirdParty/RootMinimizers/src/Math/Derivator.cxx index 17158cdce3ded965fc5923b06f023c161791e993..24f041441445467511bd723f65ad91a3f1696d0e 100644 --- a/ThirdParty/RootMinimizers/src/Math/Derivator.cxx +++ b/ThirdParty/RootMinimizers/src/Math/Derivator.cxx @@ -1,5 +1,5 @@ // @(#)root/mathmore:$Id$ -// Authors: L. Moneta, A. Zsenei 08/2005 +// Authors: L. Moneta, A. Zsenei 08/2005 /********************************************************************** * * @@ -23,11 +23,11 @@ **********************************************************************/ // Implementation file for class GSLDerivator -// +// // Created by: moneta at Sat Nov 13 14:46:00 2004 -// +// // Last update: Sat Nov 13 14:46:00 2004 -// +// #include "Math/IFunction.h" #include "Math/IParamFunction.h" @@ -47,36 +47,36 @@ namespace Math { Derivator::Derivator() { fDerivator = new GSLDerivator(); } - -Derivator::Derivator(const IGenFunction &f) + +Derivator::Derivator(const IGenFunction &f) { // allocate a GSLDerivator fDerivator = new GSLDerivator(); - fDerivator->SetFunction(f); + fDerivator->SetFunction(f); } -Derivator::Derivator(const GSLFuncPointer &f, void * p) +Derivator::Derivator(const GSLFuncPointer &f, void * p) { // allocate a GSLDerivator fDerivator = new GSLDerivator(); fDerivator->SetFunction(f,p); - + } -Derivator::~Derivator() +Derivator::~Derivator() { if (fDerivator) delete fDerivator; } -Derivator::Derivator(const Derivator &) +Derivator::Derivator(const Derivator &) { } -Derivator & Derivator::operator = (const Derivator &rhs) +Derivator & Derivator::operator = (const Derivator &rhs) { if (this == &rhs) return *this; // time saving self-test - + return *this; } @@ -90,23 +90,23 @@ void Derivator::SetFunction( const GSLFuncPointer &f, void * p) { } -double Derivator::Eval( double x, double h) const { +double Derivator::Eval( double x, double h) const { return fDerivator->EvalCentral(x, h); } -double Derivator::EvalCentral( double x, double h) const { +double Derivator::EvalCentral( double x, double h) const { return fDerivator->EvalCentral(x, h); } -double Derivator::EvalForward( double x, double h) const { +double Derivator::EvalForward( double x, double h) const { return fDerivator->EvalForward(x, h); } -double Derivator::EvalBackward( double x, double h) const { +double Derivator::EvalBackward( double x, double h) const { return fDerivator->EvalBackward(x, h); } -// static methods +// static methods double Derivator::Eval(const IGenFunction & f, double x, double h ) { return GSLDerivator::EvalCentral(f, x, h ); } @@ -117,7 +117,7 @@ double Derivator::EvalCentral(const IGenFunction & f, double x, double h) { double Derivator::EvalForward(const IGenFunction & f, double x, double h) { return GSLDerivator::EvalForward(f, x, h); -} +} double Derivator::EvalBackward(const IGenFunction & f, double x, double h) { return GSLDerivator::EvalBackward(f, x, h); @@ -125,27 +125,27 @@ double Derivator::EvalBackward(const IGenFunction & f, double x, double h) { double Derivator::Eval(const IMultiGenFunction & f, const double * x, unsigned int icoord, double h ) { // partial derivative for a multi-dim function - GSLDerivator d; + GSLDerivator d; OneDimMultiFunctionAdapter<> adapter(f,x,icoord); - d.SetFunction( &GSLFunctionAdapter<OneDimMultiFunctionAdapter<> >::F,static_cast<void *>(&adapter) ); - return d.EvalCentral(x[icoord],h); + d.SetFunction( &GSLFunctionAdapter<OneDimMultiFunctionAdapter<> >::F,static_cast<void *>(&adapter) ); + return d.EvalCentral(x[icoord],h); } double Derivator::Eval(IParamFunction & f, double x, const double * p, unsigned int ipar, double h ) { // derivative w.r.t parameter for a one-dim param function - GSLDerivator d; - const double xx = x; + GSLDerivator d; + const double xx = x; OneDimParamFunctionAdapter<IParamFunction &> adapter(f,&xx,p,ipar); - d.SetFunction( &GSLFunctionAdapter<OneDimParamFunctionAdapter<IParamFunction &> >::F,static_cast<void *>(&adapter) ); - return d.EvalCentral(p[ipar],h); + d.SetFunction( &GSLFunctionAdapter<OneDimParamFunctionAdapter<IParamFunction &> >::F,static_cast<void *>(&adapter) ); + return d.EvalCentral(p[ipar],h); } double Derivator::Eval(IParamMultiFunction & f, const double * x, const double * p, unsigned int ipar, double h ) { // derivative w.r.t parameter for a multi-dim param function - GSLDerivator d; + GSLDerivator d; OneDimParamFunctionAdapter<IParamMultiFunction &> adapter(f,x,p,ipar); - d.SetFunction( &GSLFunctionAdapter<OneDimParamFunctionAdapter<IParamMultiFunction &> >::F,static_cast<void *>(&adapter) ); - return d.EvalCentral(p[ipar],h); + d.SetFunction( &GSLFunctionAdapter<OneDimParamFunctionAdapter<IParamMultiFunction &> >::F,static_cast<void *>(&adapter) ); + return d.EvalCentral(p[ipar],h); } diff --git a/ThirdParty/RootMinimizers/src/Math/GSL1DMinimizerWrapper.h b/ThirdParty/RootMinimizers/src/Math/GSL1DMinimizerWrapper.h index 114a328d43a9f4ef8a01da2cab9174caaf12924a..963dd8afd6b135fcaf9181610b05f471500ee958 100644 --- a/ThirdParty/RootMinimizers/src/Math/GSL1DMinimizerWrapper.h +++ b/ThirdParty/RootMinimizers/src/Math/GSL1DMinimizerWrapper.h @@ -22,20 +22,20 @@ **********************************************************************/ // Header file for class GSL1DMinimizerWrapper -// +// // Created by: moneta at Wed Dec 1 17:25:44 2004 -// +// // Last update: Wed Dec 1 17:25:44 2004 -// +// #ifndef ROOT_Math_GSL1DMinimizerWrapper #define ROOT_Math_GSL1DMinimizerWrapper #include "gsl/gsl_min.h" -namespace ROOT { +namespace ROOT { -namespace Math { +namespace Math { /** wrapper class for gsl_min_fminimizer structure @@ -43,32 +43,32 @@ namespace Math { */ class GSL1DMinimizerWrapper { -public: - GSL1DMinimizerWrapper( const gsl_min_fminimizer_type * T) +public: + GSL1DMinimizerWrapper( const gsl_min_fminimizer_type * T) { - fMinimizer = gsl_min_fminimizer_alloc(T); + fMinimizer = gsl_min_fminimizer_alloc(T); } - virtual ~GSL1DMinimizerWrapper() { + virtual ~GSL1DMinimizerWrapper() { gsl_min_fminimizer_free(fMinimizer); } private: // usually copying is non trivial, so we make this unaccessible - GSL1DMinimizerWrapper(const GSL1DMinimizerWrapper &); - GSL1DMinimizerWrapper & operator = (const GSL1DMinimizerWrapper &); + GSL1DMinimizerWrapper(const GSL1DMinimizerWrapper &); + GSL1DMinimizerWrapper & operator = (const GSL1DMinimizerWrapper &); -public: +public: - gsl_min_fminimizer * Get() const { - return fMinimizer; + gsl_min_fminimizer * Get() const { + return fMinimizer; } -private: +private: - gsl_min_fminimizer * fMinimizer; + gsl_min_fminimizer * fMinimizer; -}; +}; } // end namespace Math } // end namespace ROOT diff --git a/ThirdParty/RootMinimizers/src/Math/GSLDerivator.cxx b/ThirdParty/RootMinimizers/src/Math/GSLDerivator.cxx index ff9ae35ded1dea56ed41bda3a2be90d8c1022d3c..b75b29fb381dc62de16721505d666f5f70ae0dab 100644 --- a/ThirdParty/RootMinimizers/src/Math/GSLDerivator.cxx +++ b/ThirdParty/RootMinimizers/src/Math/GSLDerivator.cxx @@ -1,5 +1,5 @@ // @(#)root/mathmore:$Id$ -// Authors: L. Moneta, A. Zsenei 08/2005 +// Authors: L. Moneta, A. Zsenei 08/2005 /********************************************************************** * * @@ -23,11 +23,11 @@ **********************************************************************/ // Implementation file for class GSLDerivator -// +// // Created by: moneta at Sat Nov 13 14:46:00 2004 -// +// // Last update: Sat Nov 13 14:46:00 2004 -// +// #include "GSLDerivator.h" @@ -44,63 +44,63 @@ namespace Math { -double GSLDerivator::EvalCentral( double x, double h) { - // Central evaluation using previously set function - if ( !fFunction.IsValid() ) { +double GSLDerivator::EvalCentral( double x, double h) { + // Central evaluation using previously set function + if ( !fFunction.IsValid() ) { std::cerr << "GSLDerivator: Error : The function has not been specified" << std::endl; - fStatus = -1; - return 0; + fStatus = -1; + return 0; } - fStatus = gsl_deriv_central( fFunction.GetFunc(), x, h, &fResult, &fError); + fStatus = gsl_deriv_central( fFunction.GetFunc(), x, h, &fResult, &fError); return fResult; } double GSLDerivator::EvalForward( double x, double h) { - // Forward evaluation using previously set function - if ( !fFunction.IsValid() ) { + // Forward evaluation using previously set function + if ( !fFunction.IsValid() ) { std::cerr << "GSLDerivator: Error : The function has not been specified" << std::endl; - fStatus = -1; - return 0; + fStatus = -1; + return 0; } - fStatus = gsl_deriv_forward( fFunction.GetFunc(), x, h, &fResult, &fError); + fStatus = gsl_deriv_forward( fFunction.GetFunc(), x, h, &fResult, &fError); return fResult; } -double GSLDerivator::EvalBackward( double x, double h) { - // Backward evaluation using previously set function - if ( !fFunction.IsValid() ) { +double GSLDerivator::EvalBackward( double x, double h) { + // Backward evaluation using previously set function + if ( !fFunction.IsValid() ) { std::cerr << "GSLDerivator: Error : The function has not been specified" << std::endl; - fStatus = -1; - return 0; + fStatus = -1; + return 0; } - fStatus = gsl_deriv_backward( fFunction.GetFunc(), x, h, &fResult, &fError); + fStatus = gsl_deriv_backward( fFunction.GetFunc(), x, h, &fResult, &fError); return fResult; } // static methods not requiring the function -double GSLDerivator::EvalCentral(const IGenFunction & f, double x, double h) { - // Central evaluation using given function - GSLFunctionWrapper gslfw; - double result, error = 0; - gslfw.SetFunction(f); +double GSLDerivator::EvalCentral(const IGenFunction & f, double x, double h) { + // Central evaluation using given function + GSLFunctionWrapper gslfw; + double result, error = 0; + gslfw.SetFunction(f); gsl_deriv_central( gslfw.GetFunc(), x, h, &result, &error); return result; } -double GSLDerivator::EvalForward(const IGenFunction & f, double x, double h) { - // Forward evaluation using given function - GSLFunctionWrapper gslfw; - double result, error = 0; - gslfw.SetFunction(f); +double GSLDerivator::EvalForward(const IGenFunction & f, double x, double h) { + // Forward evaluation using given function + GSLFunctionWrapper gslfw; + double result, error = 0; + gslfw.SetFunction(f); gsl_deriv_forward( gslfw.GetFunc(), x, h, &result, &error); return result; } -double GSLDerivator::EvalBackward(const IGenFunction & f, double x, double h) { - // Backward evaluation using given function - GSLFunctionWrapper gslfw; - double result, error = 0; - gslfw.SetFunction(f); +double GSLDerivator::EvalBackward(const IGenFunction & f, double x, double h) { + // Backward evaluation using given function + GSLFunctionWrapper gslfw; + double result, error = 0; + gslfw.SetFunction(f); gsl_deriv_backward( gslfw.GetFunc(), x, h, &result, &error); return result; } @@ -114,14 +114,14 @@ int GSLDerivator::Status() const { return fStatus; } // fill GSLFunctionWrapper with the pointer to the function -void GSLDerivator::SetFunction( GSLFuncPointer fp, void * p) { - fFunction.SetFuncPointer( fp ); - fFunction.SetParams ( p ); +void GSLDerivator::SetFunction( GSLFuncPointer fp, void * p) { + fFunction.SetFuncPointer( fp ); + fFunction.SetParams ( p ); } -void GSLDerivator::SetFunction(const IGenFunction &f) { - fFunction.SetFunction(f); +void GSLDerivator::SetFunction(const IGenFunction &f) { + fFunction.SetFunction(f); } } // namespace Math diff --git a/ThirdParty/RootMinimizers/src/Math/GSLDerivator.h b/ThirdParty/RootMinimizers/src/Math/GSLDerivator.h index 7060fd5751412d95ca845bc8f9fcd9e1a381bbcf..edb24579b4238d1200e6411c141a4c0f29f3aa2e 100644 --- a/ThirdParty/RootMinimizers/src/Math/GSLDerivator.h +++ b/ThirdParty/RootMinimizers/src/Math/GSLDerivator.h @@ -1,5 +1,5 @@ // @(#)root/mathmore:$Id$ -// Authors: L. Moneta, A. Zsenei 08/2005 +// Authors: L. Moneta, A. Zsenei 08/2005 /********************************************************************** * * @@ -23,20 +23,20 @@ **********************************************************************/ // Header file for class Derivator -// +// // class for calculating Derivative of functions -// +// // Created by: moneta at Sat Nov 13 14:46:00 2004 -// +// // Last update: Sat Nov 13 14:46:00 2004 -// +// #ifndef ROOT_Math_GSLDerivator #define ROOT_Math_GSLDerivator -/** +/** @defgroup Deriv Numerical Differentiation */ - + #include "Math/GSLFunctionAdapter.h" #include "GSLFunctionWrapper.h" @@ -48,14 +48,14 @@ namespace ROOT { namespace Math { -class GSLFunctionWrapper; +class GSLFunctionWrapper; -/** - Class for computing numerical derivative of a function based on the GSL numerical algorithm +/** + Class for computing numerical derivative of a function based on the GSL numerical algorithm This class is implemented using the numerical derivatives algorithms provided by GSL (see <A HREF="http://www.gnu.org/software/gsl/manual/html_node/Numerical-Differentiation.html">GSL Online Manual</A> ). - + @ingroup Deriv */ @@ -71,100 +71,100 @@ public: virtual ~GSLDerivator() {} // // disable copying -// private: +// private: // GSLDerivator(const GSLDerivator &); -// GSLDerivator & operator = (const GSLDerivator &); +// GSLDerivator & operator = (const GSLDerivator &); -// public: +// public: /** - Set the function for calculating the derivatives. + Set the function for calculating the derivatives. The function must implement the ROOT::Math::IGenFunction signature */ void SetFunction(const IGenFunction &f); - /** - Set the function f for evaluating the derivative using a GSL function pointer type + /** + Set the function f for evaluating the derivative using a GSL function pointer type @param f : free function pointer of the GSL required type - @param p : pointer to the object carrying the function state + @param p : pointer to the object carrying the function state (for example the function object itself) */ void SetFunction( GSLFuncPointer f, void * p = 0); - /** - Computes the numerical derivative at a point x using an adaptive central - difference algorithm with a step size h. + /** + Computes the numerical derivative at a point x using an adaptive central + difference algorithm with a step size h. */ - double EvalCentral( double x, double h); + double EvalCentral( double x, double h); - /** - Computes the numerical derivative at a point x using an adaptive forward + /** + Computes the numerical derivative at a point x using an adaptive forward difference algorithm with a step size h. The function is evaluated only at points greater than x and at x itself. */ - double EvalForward( double x, double h); + double EvalForward( double x, double h); - /** - Computes the numerical derivative at a point x using an adaptive backward + /** + Computes the numerical derivative at a point x using an adaptive backward difference algorithm with a step size h. The function is evaluated only at points less than x and at x itself. */ - double EvalBackward( double x, double h); + double EvalBackward( double x, double h); /** @name --- Static methods --- **/ - /** - Computes the numerical derivative of a function f at a point x using an adaptive central + /** + Computes the numerical derivative of a function f at a point x using an adaptive central difference algorithm with a step size h */ - static double EvalCentral(const IGenFunction & f, double x, double h); + static double EvalCentral(const IGenFunction & f, double x, double h); - /** - Computes the numerical derivative of a function f at a point x using an adaptive forward + /** + Computes the numerical derivative of a function f at a point x using an adaptive forward difference algorithm with a step size h. The function is evaluated only at points greater than x and at x itself - */ + */ static double EvalForward(const IGenFunction & f, double x, double h); - /** - Computes the numerical derivative of a function f at a point x using an adaptive backward + /** + Computes the numerical derivative of a function f at a point x using an adaptive backward difference algorithm with a step size h. The function is evaluated only at points less than x and at x itself */ - - static double EvalBackward(const IGenFunction & f, double x, double h); - + static double EvalBackward(const IGenFunction & f, double x, double h); + + /** return the error status of the last integral calculation - */ - int Status() const; + */ + int Status() const; /** return the result of the last derivative calculation */ - double Result() const; + double Result() const; /** return the estimate of the absolute error of the last derivative calculation */ - double Error() const; + double Error() const; -private: +private: int fStatus; - double fResult; - double fError; + double fResult; + double fError; - GSLFunctionWrapper fFunction; + GSLFunctionWrapper fFunction; -}; +}; diff --git a/ThirdParty/RootMinimizers/src/Math/GSLFunctionWrapper.h b/ThirdParty/RootMinimizers/src/Math/GSLFunctionWrapper.h index 0dc090548011a5e748b6ecc4c29ef8dc174c312b..2b27bec48668aee6cb6fd71aa884e6cb727e7aed 100644 --- a/ThirdParty/RootMinimizers/src/Math/GSLFunctionWrapper.h +++ b/ThirdParty/RootMinimizers/src/Math/GSLFunctionWrapper.h @@ -1,5 +1,5 @@ // @(#)root/mathmore:$Id$ -// Authors: L. Moneta, A. Zsenei 08/2005 +// Authors: L. Moneta, A. Zsenei 08/2005 /********************************************************************** * * @@ -23,11 +23,11 @@ **********************************************************************/ // Header file for class GSLFunctionWrapper -// +// // Created by: moneta at Sat Nov 13 14:54:41 2004 -// +// // Last update: Sat Nov 13 14:54:41 2004 -// +// #ifndef ROOT_Math_GSLFunctionWrapper #define ROOT_Math_GSLFunctionWrapper @@ -47,98 +47,98 @@ typedef void ( * GSLFdfPointer ) ( double, void *, double *, double *); /** - Wrapper class to the gsl_function C structure. - This class to fill the GSL C structure gsl_function with - the C++ function objcet. - Use the class ROOT::Math::GSLFunctionAdapter to adapt the - C++ function object to the right signature (function pointer type) - requested by GSL + Wrapper class to the gsl_function C structure. + This class to fill the GSL C structure gsl_function with + the C++ function objcet. + Use the class ROOT::Math::GSLFunctionAdapter to adapt the + C++ function object to the right signature (function pointer type) + requested by GSL */ -class GSLFunctionWrapper { +class GSLFunctionWrapper { -public: +public: - GSLFunctionWrapper() + GSLFunctionWrapper() { - fFunc.function = 0; + fFunc.function = 0; fFunc.params = 0; } - /// set in the GSL C struct the pointer to the function evaluation - void SetFuncPointer( GSLFuncPointer f) { fFunc.function = f; } + /// set in the GSL C struct the pointer to the function evaluation + void SetFuncPointer( GSLFuncPointer f) { fFunc.function = f; } /// set in the GSL C struct the extra-object pointer void SetParams ( void * p) { fFunc.params = p; } - /// fill the GSL C struct from a generic C++ callable object - /// implementing operator() - template<class FuncType> - void SetFunction(const FuncType &f) { + /// fill the GSL C struct from a generic C++ callable object + /// implementing operator() + template<class FuncType> + void SetFunction(const FuncType &f) { const void * p = &f; - assert (p != 0); + assert (p != 0); SetFuncPointer(&GSLFunctionAdapter<FuncType >::F); SetParams(const_cast<void *>(p)); } - - gsl_function * GetFunc() { return &fFunc; } + + gsl_function * GetFunc() { return &fFunc; } GSLFuncPointer FunctionPtr() { return fFunc.function; } - // evaluate the function + // evaluate the function double operator() (double x) { return GSL_FN_EVAL(&fFunc, x); } - /// check if function is valid (has been set) - bool IsValid() { - return (fFunc.function != 0) ? true : false; + /// check if function is valid (has been set) + bool IsValid() { + return (fFunc.function != 0) ? true : false; } -private: - gsl_function fFunc; +private: + gsl_function fFunc; }; /** - class to wrap a gsl_function_fdf (with derivatives) + class to wrap a gsl_function_fdf (with derivatives) */ - class GSLFunctionDerivWrapper { + class GSLFunctionDerivWrapper { - public: + public: - GSLFunctionDerivWrapper() + GSLFunctionDerivWrapper() { - fFunc.f = 0; - fFunc.df = 0; - fFunc.fdf = 0; + fFunc.f = 0; + fFunc.df = 0; + fFunc.fdf = 0; fFunc.params = 0; } - void SetFuncPointer( GSLFuncPointer f) { fFunc.f = f; } - void SetDerivPointer( GSLFuncPointer f) { fFunc.df = f; } - void SetFdfPointer( GSLFdfPointer f) { fFunc.fdf = f; } + void SetFuncPointer( GSLFuncPointer f) { fFunc.f = f; } + void SetDerivPointer( GSLFuncPointer f) { fFunc.df = f; } + void SetFdfPointer( GSLFdfPointer f) { fFunc.fdf = f; } void SetParams ( void * p) { fFunc.params = p; } - - gsl_function_fdf * GetFunc() { return &fFunc; } + + gsl_function_fdf * GetFunc() { return &fFunc; } // evaluate the function and derivatives double operator() (double x) { return GSL_FN_FDF_EVAL_F(&fFunc, x); } - double Derivative (double x) { return GSL_FN_FDF_EVAL_DF(&fFunc, x); } + double Derivative (double x) { return GSL_FN_FDF_EVAL_DF(&fFunc, x); } - void Fdf(double x, double & f, double & df) { + void Fdf(double x, double & f, double & df) { return GSL_FN_FDF_EVAL_F_DF(&fFunc, x, &f, &df); } - /// check if function is valid (has been set) - bool IsValid() { - return (fFunc.f != 0 ) ? true : false; + /// check if function is valid (has been set) + bool IsValid() { + return (fFunc.f != 0 ) ? true : false; } - private: - gsl_function_fdf fFunc; + private: + gsl_function_fdf fFunc; }; diff --git a/ThirdParty/RootMinimizers/src/Math/GSLMinimizer.cxx b/ThirdParty/RootMinimizers/src/Math/GSLMinimizer.cxx index 7e5ed5115247777ff5ddbf83b76807c1d13ecc54..b22801b59f96e5328b319e7944b16d29bbac074b 100644 --- a/ThirdParty/RootMinimizers/src/Math/GSLMinimizer.cxx +++ b/ThirdParty/RootMinimizers/src/Math/GSLMinimizer.cxx @@ -41,132 +41,132 @@ #include <algorithm> #include <functional> #include <ctype.h> // need to use c version of tolower defined here -#include <limits> +#include <limits> -namespace ROOT { +namespace ROOT { - namespace Math { + namespace Math { -GSLMinimizer::GSLMinimizer( ROOT::Math::EGSLMinimizerType type) : +GSLMinimizer::GSLMinimizer( ROOT::Math::EGSLMinimizerType type) : BasicMinimizer() { // Constructor implementation : create GSLMultiMin wrapper object //std::cout << "create GSL Minimizer of type " << type << std::endl; - fGSLMultiMin = new GSLMultiMinimizer((ROOT::Math::EGSLMinimizerType) type); + fGSLMultiMin = new GSLMultiMinimizer((ROOT::Math::EGSLMinimizerType) type); fLSTolerance = 0.1; // line search tolerance (use fixed) int niter = ROOT::Math::MinimizerOptions::DefaultMaxIterations(); - if (niter <=0 ) niter = 1000; + if (niter <=0 ) niter = 1000; SetMaxIterations(niter); SetPrintLevel(ROOT::Math::MinimizerOptions::DefaultPrintLevel()); } GSLMinimizer::GSLMinimizer( const char * type) : BasicMinimizer() { - // Constructor implementation from a string + // Constructor implementation from a string std::string algoname(type); - std::transform(algoname.begin(), algoname.end(), algoname.begin(), (int(*)(int)) tolower ); + std::transform(algoname.begin(), algoname.end(), algoname.begin(), (int(*)(int)) tolower ); ROOT::Math::EGSLMinimizerType algo = kVectorBFGS2; // default value - if (algoname == "conjugatefr") algo = kConjugateFR; - if (algoname == "conjugatepr") algo = kConjugatePR; - if (algoname == "bfgs") algo = kVectorBFGS; - if (algoname == "bfgs2") algo = kVectorBFGS2; - if (algoname == "steepestdescent") algo = kSteepestDescent; - + if (algoname == "conjugatefr") algo = kConjugateFR; + if (algoname == "conjugatepr") algo = kConjugatePR; + if (algoname == "bfgs") algo = kVectorBFGS; + if (algoname == "bfgs2") algo = kVectorBFGS2; + if (algoname == "steepestdescent") algo = kSteepestDescent; + //std::cout << "create GSL Minimizer of type " << algo << std::endl; - fGSLMultiMin = new GSLMultiMinimizer(algo); + fGSLMultiMin = new GSLMultiMinimizer(algo); - fLSTolerance = 0.1; // use 10**-4 + fLSTolerance = 0.1; // use 10**-4 int niter = ROOT::Math::MinimizerOptions::DefaultMaxIterations(); - if (niter <=0 ) niter = 1000; + if (niter <=0 ) niter = 1000; SetMaxIterations(niter); SetPrintLevel(ROOT::Math::MinimizerOptions::DefaultPrintLevel()); } -GSLMinimizer::~GSLMinimizer () { - assert(fGSLMultiMin != 0); - delete fGSLMultiMin; +GSLMinimizer::~GSLMinimizer () { + assert(fGSLMultiMin != 0); + delete fGSLMultiMin; } - -void GSLMinimizer::SetFunction(const ROOT::Math::IMultiGenFunction & func) { - // set the function to minimizer + +void GSLMinimizer::SetFunction(const ROOT::Math::IMultiGenFunction & func) { + // set the function to minimizer // need to calculate numerically the derivatives: do via class MultiNumGradFunction // no need to clone the passed function - ROOT::Math::MultiNumGradFunction gradFunc(func); + ROOT::Math::MultiNumGradFunction gradFunc(func); // function is cloned inside so can be delete afterwards - // called base class method setfunction + // called base class method setfunction // (note: write explicitly otherwise it will call back itself) BasicMinimizer::SetFunction(gradFunc); } unsigned int GSLMinimizer::NCalls() const { - // return numbr of function calls - // if method support + // return numbr of function calls + // if method support const ROOT::Math::MultiNumGradFunction * fnumgrad = dynamic_cast<const ROOT::Math::MultiNumGradFunction *>(ObjFunction()); if (fnumgrad) return fnumgrad->NCalls(); const ROOT::Math::FitMethodGradFunction * ffitmethod = dynamic_cast<const ROOT::Math::FitMethodGradFunction *>(ObjFunction()); - if (ffitmethod) return ffitmethod->NCalls(); + if (ffitmethod) return ffitmethod->NCalls(); // not supported in the other case - return 0; + return 0; } -bool GSLMinimizer::Minimize() { +bool GSLMinimizer::Minimize() { // set initial parameters of the minimizer - if (fGSLMultiMin == 0) return false; + if (fGSLMultiMin == 0) return false; const ROOT::Math::IMultiGradFunction * function = GradObjFunction(); - if (function == 0) { + if (function == 0) { MATH_ERROR_MSG("GSLMinimizer::Minimize","Function has not been set"); - return false; + return false; } unsigned int npar = NPar(); unsigned int ndim = NDim(); - if (npar == 0 || npar < NDim() ) { + if (npar == 0 || npar < NDim() ) { MATH_ERROR_MSGVAL("GSLMinimizer::Minimize","Wrong number of parameters",npar); return false; } - if (npar > ndim ) { + if (npar > ndim ) { MATH_WARN_MSGVAL("GSLMinimizer::Minimize","number of parameters larger than function dimension - ignore extra parameters",npar); } - const double eps = std::numeric_limits<double>::epsilon(); + const double eps = std::numeric_limits<double>::epsilon(); std::vector<double> startValues; std::vector<double> steps(StepSizes(), StepSizes()+npar); - + MinimTransformFunction * trFunc = CreateTransformation(startValues); - if (trFunc) { - function = trFunc; - // need to transform also the steps - trFunc->InvStepTransformation(X(), StepSizes(), &steps[0]); + if (trFunc) { + function = trFunc; + // need to transform also the steps + trFunc->InvStepTransformation(X(), StepSizes(), &steps[0]); steps.resize(trFunc->NDim()); } // in case all parameters are free - just evaluate the function - if (NFree() == 0) { + if (NFree() == 0) { MATH_INFO_MSG("GSLMinimizer::Minimize","There are no free parameter - just compute the function value"); double fval = (*function)((double*)0); // no need to pass parameters SetFinalValues(&startValues[0]); - SetMinValue(fval); + SetMinValue(fval); fStatus = 0; return true; } - // use a global step size = modules of step vectors - double stepSize = 0; - for (unsigned int i = 0; i < steps.size(); ++i) - stepSize += steps[i]*steps[i]; + // use a global step size = modules of step vectors + double stepSize = 0; + for (unsigned int i = 0; i < steps.size(); ++i) + stepSize += steps[i]*steps[i]; stepSize = std::sqrt(stepSize); if (stepSize < eps) { MATH_ERROR_MSGVAL("GSLMinimizer::Minimize","Step size is too small",stepSize); @@ -174,46 +174,46 @@ bool GSLMinimizer::Minimize() { } - // set parameters in internal GSL minimization class - fGSLMultiMin->Set(*function, &startValues.front(), stepSize, fLSTolerance ); + // set parameters in internal GSL minimization class + fGSLMultiMin->Set(*function, &startValues.front(), stepSize, fLSTolerance ); - int debugLevel = PrintLevel(); + int debugLevel = PrintLevel(); - if (debugLevel >=1 ) std::cout <<"Minimize using GSLMinimizer " << fGSLMultiMin->Name() << std::endl; + if (debugLevel >=1 ) std::cout <<"Minimize using GSLMinimizer " << fGSLMultiMin->Name() << std::endl; - //std::cout <<"print Level " << debugLevel << std::endl; - //debugLevel = 3; + //std::cout <<"print Level " << debugLevel << std::endl; + //debugLevel = 3; - // start iteration - unsigned int iter = 0; - int status; - bool minFound = false; - bool iterFailed = false; - do { - status = fGSLMultiMin->Iterate(); - if (status) { + // start iteration + unsigned int iter = 0; + int status; + bool minFound = false; + bool iterFailed = false; + do { + status = fGSLMultiMin->Iterate(); + if (status) { iterFailed = true; - break; + break; } status = fGSLMultiMin->TestGradient( Tolerance() ); if (status == GSL_SUCCESS) { - minFound = true; + minFound = true; } - if (debugLevel >=2) { - std::cout << "----------> Iteration " << std::setw(4) << iter; + if (debugLevel >=2) { + std::cout << "----------> Iteration " << std::setw(4) << iter; int pr = std::cout.precision(18); - std::cout << " FVAL = " << fGSLMultiMin->Minimum() << std::endl; + std::cout << " FVAL = " << fGSLMultiMin->Minimum() << std::endl; std::cout.precision(pr); - if (debugLevel >=3) { - std::cout << " Parameter Values : "; + if (debugLevel >=3) { + std::cout << " Parameter Values : "; const double * xtmp = fGSLMultiMin->X(); - std::cout << std::endl; - if (trFunc != 0 ) { - xtmp = trFunc->Transformation(xtmp); + std::cout << std::endl; + if (trFunc != 0 ) { + xtmp = trFunc->Transformation(xtmp); } for (unsigned int i = 0; i < NDim(); ++i) { std::cout << " " << VariableName(i) << " = " << xtmp[i]; @@ -221,7 +221,7 @@ bool GSLMinimizer::Minimize() { // if (std::isnan(xtmp[i])) status = -11; } std::cout << std::endl; - } + } } @@ -233,61 +233,61 @@ bool GSLMinimizer::Minimize() { // save state with values and function value - double * x = fGSLMultiMin->X(); - if (x == 0) return false; + double * x = fGSLMultiMin->X(); + if (x == 0) return false; SetFinalValues(x); - double minVal = fGSLMultiMin->Minimum(); + double minVal = fGSLMultiMin->Minimum(); SetMinValue(minVal); - fStatus = status; + fStatus = status; + - - if (minFound) { - if (debugLevel >=1 ) { - std::cout << "GSLMinimizer: Minimum Found" << std::endl; + if (minFound) { + if (debugLevel >=1 ) { + std::cout << "GSLMinimizer: Minimum Found" << std::endl; int pr = std::cout.precision(18); std::cout << "FVAL = " << MinValue() << std::endl; std::cout.precision(pr); // std::cout << "Edm = " << fState.Edm() << std::endl; std::cout << "Niterations = " << iter << std::endl; - unsigned int ncalls = NCalls(); + unsigned int ncalls = NCalls(); if (ncalls) std::cout << "NCalls = " << ncalls << std::endl; - for (unsigned int i = 0; i < NDim(); ++i) - std::cout << VariableName(i) << "\t = " << X()[i] << std::endl; + for (unsigned int i = 0; i < NDim(); ++i) + std::cout << VariableName(i) << "\t = " << X()[i] << std::endl; } - return true; + return true; } - else { - if (debugLevel >= -1 ) { - std::cout << "GSLMinimizer: Minimization did not converge" << std::endl; - if (iterFailed) { + else { + if (debugLevel >= -1 ) { + std::cout << "GSLMinimizer: Minimization did not converge" << std::endl; + if (iterFailed) { if (status == GSL_ENOPROG) // case status 27 std::cout << "\t Iteration is not making progress towards solution" << std::endl; - else + else std::cout << "\t Iteration failed with status " << status << std::endl; if (debugLevel >= 1) { double * g = fGSLMultiMin->Gradient(); - double dg2 = 0; - for (unsigned int i = 0; i < NDim(); ++i) dg2 += g[i] * g[1]; - std::cout << "Grad module is " << std::sqrt(dg2) << std::endl; - for (unsigned int i = 0; i < NDim(); ++i) - std::cout << VariableName(i) << "\t = " << X()[i] << std::endl; + double dg2 = 0; + for (unsigned int i = 0; i < NDim(); ++i) dg2 += g[i] * g[1]; + std::cout << "Grad module is " << std::sqrt(dg2) << std::endl; + for (unsigned int i = 0; i < NDim(); ++i) + std::cout << VariableName(i) << "\t = " << X()[i] << std::endl; std::cout << "FVAL = " << MinValue() << std::endl; // std::cout << "Edm = " << fState.Edm() << std::endl; std::cout << "Niterations = " << iter << std::endl; } } } - return false; + return false; } - return false; + return false; } const double * GSLMinimizer::MinGradient() const { - // return gradient (internal values) - return fGSLMultiMin->Gradient(); + // return gradient (internal values) + return fGSLMultiMin->Gradient(); } diff --git a/ThirdParty/RootMinimizers/src/Math/GSLMinimizer1D.cxx b/ThirdParty/RootMinimizers/src/Math/GSLMinimizer1D.cxx index ede23fcc7c78774c57a49f917de042ae0758e0f6..b797a94efe6992d888683eb2bdd86aa67fdfd11a 100644 --- a/ThirdParty/RootMinimizers/src/Math/GSLMinimizer1D.cxx +++ b/ThirdParty/RootMinimizers/src/Math/GSLMinimizer1D.cxx @@ -22,11 +22,11 @@ **********************************************************************/ // Implementation file for class GSLMinimizer1D -// +// // Created by: moneta at Wed Dec 1 15:04:51 2004 -// +// // Last update: Wed Dec 1 15:04:51 2004 -// +// #include <assert.h> @@ -40,17 +40,17 @@ #include "gsl/gsl_min.h" #include "gsl/gsl_errno.h" -#include <iostream> +#include <iostream> #include <cmath> -namespace ROOT { +namespace ROOT { -namespace Math { +namespace Math { -GSLMinimizer1D::GSLMinimizer1D(Minim1D::Type type) : - fXmin(0), fXlow(0), fXup(0), fMin(0), fLow(0), fUp(0), - fIter(0), fStatus(-1), fIsSet(false), +GSLMinimizer1D::GSLMinimizer1D(Minim1D::Type type) : + fXmin(0), fXlow(0), fXup(0), fMin(0), fLow(0), fUp(0), + fIter(0), fStatus(-1), fIsSet(false), fMinimizer(0), fFunction(0) { // construct a minimizer passing the algorithm type as an enumeration @@ -58,26 +58,26 @@ GSLMinimizer1D::GSLMinimizer1D(Minim1D::Type type) : const gsl_min_fminimizer_type* T = 0 ; switch ( type ) { - case Minim1D::kGOLDENSECTION : - T = gsl_min_fminimizer_goldensection; + case Minim1D::kGOLDENSECTION : + T = gsl_min_fminimizer_goldensection; break ; case Minim1D::kBRENT : - T = gsl_min_fminimizer_brent; + T = gsl_min_fminimizer_brent; break ; default : - // default case is brent - T = gsl_min_fminimizer_brent; + // default case is brent + T = gsl_min_fminimizer_brent; break ; } - fMinimizer = new GSL1DMinimizerWrapper(T); + fMinimizer = new GSL1DMinimizerWrapper(T); fFunction = new GSLFunctionWrapper(); } -GSLMinimizer1D::~GSLMinimizer1D() +GSLMinimizer1D::~GSLMinimizer1D() { - // destructor: clean up minimizer and function pointers + // destructor: clean up minimizer and function pointers if (fMinimizer) delete fMinimizer; if (fFunction) delete fFunction; @@ -88,104 +88,104 @@ GSLMinimizer1D::GSLMinimizer1D(const GSLMinimizer1D &): IMinimizer1D() // dummy copy ctr } -GSLMinimizer1D & GSLMinimizer1D::operator = (const GSLMinimizer1D &rhs) +GSLMinimizer1D & GSLMinimizer1D::operator = (const GSLMinimizer1D &rhs) { - // dummy operator = + // dummy operator = if (this == &rhs) return *this; // time saving self-test return *this; } -void GSLMinimizer1D::SetFunction( GSLFuncPointer f, void * p, double xmin, double xlow, double xup) { - // set the function to be minimized +void GSLMinimizer1D::SetFunction( GSLFuncPointer f, void * p, double xmin, double xlow, double xup) { + // set the function to be minimized assert(fFunction); assert(fMinimizer); - fXlow = xlow; + fXlow = xlow; fXup = xup; fXmin = xmin; - fFunction->SetFuncPointer( f ); - fFunction->SetParams( p ); + fFunction->SetFuncPointer( f ); + fFunction->SetParams( p ); #ifdef DEBUG std::cout << " [ "<< xlow << " , " << xup << " ]" << std::endl; #endif int status = gsl_min_fminimizer_set( fMinimizer->Get(), fFunction->GetFunc(), xmin, xlow, xup); - if (status != GSL_SUCCESS) - std::cerr <<"GSLMinimizer1D: Error: Interval [ "<< xlow << " , " << xup << " ] does not contain a minimum" << std::endl; + if (status != GSL_SUCCESS) + std::cerr <<"GSLMinimizer1D: Error: Interval [ "<< xlow << " , " << xup << " ] does not contain a minimum" << std::endl; - fIsSet = true; + fIsSet = true; fStatus = -1; return; } int GSLMinimizer1D::Iterate() { - // perform an iteration and update values + // perform an iteration and update values if (!fIsSet) { std::cerr << "GSLMinimizer1D- Error: Function has not been set in Minimizer" << std::endl; - return -1; + return -1; } - + int status = gsl_min_fminimizer_iterate(fMinimizer->Get()); // update values fXmin = gsl_min_fminimizer_x_minimum(fMinimizer->Get() ); fMin = gsl_min_fminimizer_f_minimum(fMinimizer->Get() ); // update interval values - fXlow = gsl_min_fminimizer_x_lower(fMinimizer->Get() ); + fXlow = gsl_min_fminimizer_x_lower(fMinimizer->Get() ); fXup = gsl_min_fminimizer_x_upper(fMinimizer->Get() ); - fLow = gsl_min_fminimizer_f_lower(fMinimizer->Get() ); + fLow = gsl_min_fminimizer_f_lower(fMinimizer->Get() ); fUp = gsl_min_fminimizer_f_upper(fMinimizer->Get() ); return status; } -double GSLMinimizer1D::XMinimum() const { +double GSLMinimizer1D::XMinimum() const { // return x value at function minimum return fXmin; } -double GSLMinimizer1D::XLower() const { +double GSLMinimizer1D::XLower() const { // return lower x value of bracketing interval - return fXlow; + return fXlow; } -double GSLMinimizer1D::XUpper() const { +double GSLMinimizer1D::XUpper() const { // return upper x value of bracketing interval return fXup; } -double GSLMinimizer1D::FValMinimum() const { +double GSLMinimizer1D::FValMinimum() const { // return function value at minimum return fMin; } -double GSLMinimizer1D::FValLower() const { +double GSLMinimizer1D::FValLower() const { // return function value at x lower - return fLow; + return fLow; } -double GSLMinimizer1D::FValUpper() const { +double GSLMinimizer1D::FValUpper() const { // return function value at x upper return fUp; } const char * GSLMinimizer1D::Name() const { // return name of minimization algorithm - return gsl_min_fminimizer_name(fMinimizer->Get() ); + return gsl_min_fminimizer_name(fMinimizer->Get() ); } -bool GSLMinimizer1D::Minimize (int maxIter, double absTol, double relTol) -{ +bool GSLMinimizer1D::Minimize (int maxIter, double absTol, double relTol) +{ // find the minimum via multiple iterations - fStatus = -1; - int iter = 0; - int status = 0; - do { + fStatus = -1; + int iter = 0; + int status = 0; + do { iter++; status = Iterate(); - if (status != GSL_SUCCESS) { + if (status != GSL_SUCCESS) { MATH_ERROR_MSG("GSLMinimizer1D::Minimize","error returned when performing an iteration"); - fStatus = status; - return false; + fStatus = status; + return false; } #ifdef DEBUG @@ -193,26 +193,26 @@ bool GSLMinimizer1D::Minimize (int maxIter, double absTol, double relTol) << " fmin " << fMin << " f(a) " << fLow << " f(b) " << fUp << std::endl; #endif - - status = TestInterval(fXlow, fXup, absTol, relTol); - if (status == GSL_SUCCESS) { + + status = TestInterval(fXlow, fXup, absTol, relTol); + if (status == GSL_SUCCESS) { fIter = iter; fStatus = status; - return true; + return true; } } - while (status == GSL_CONTINUE && iter < maxIter); - if (status == GSL_CONTINUE) { + while (status == GSL_CONTINUE && iter < maxIter); + if (status == GSL_CONTINUE) { double tol = std::abs(fXup-fXlow); MATH_INFO_MSGVAL("GSLMinimizer1D::Minimize","exceeded max iterations, reached tolerance is not sufficient",tol); } - fStatus = status; + fStatus = status; return false; } -int GSLMinimizer1D::TestInterval( double xlow, double xup, double epsAbs, double epsRel) { -// static function to test interval +int GSLMinimizer1D::TestInterval( double xlow, double xup, double epsAbs, double epsRel) { +// static function to test interval return gsl_min_test_interval(xlow, xup, epsAbs, epsRel); } diff --git a/ThirdParty/RootMinimizers/src/Math/GSLMultiFit.h b/ThirdParty/RootMinimizers/src/Math/GSLMultiFit.h index a1cb348a063b06e5dd9f3c5790a8da4d421050ce..1d86da5c52d9db12775415f39358c3816203da15 100644 --- a/ThirdParty/RootMinimizers/src/Math/GSLMultiFit.h +++ b/ThirdParty/RootMinimizers/src/Math/GSLMultiFit.h @@ -35,169 +35,173 @@ #include "Math/IFunction.h" #include <string> -#include <cassert> +#include <cassert> -namespace ROOT { +namespace ROOT { - namespace Math { + namespace Math { -/** - GSLMultiFit, internal class for implementing GSL non linear least square GSL fitting +/** + GSLMultiFit, internal class for implementing GSL non linear least square GSL fitting @ingroup MultiMin -*/ +*/ class GSLMultiFit { -public: +public: - /** + /** Default constructor No need to specify the type so far since only one solver exists so far - */ - GSLMultiFit (const gsl_multifit_fdfsolver_type * type = 0) : - fSolver(0), + */ + GSLMultiFit (const gsl_multifit_fdfsolver_type * type = 0) : + fSolver(0), fVec(0), fCov(0), fType(type) { - if (fType == 0) fType = gsl_multifit_fdfsolver_lmsder; // default value - } + if (fType == 0) fType = gsl_multifit_fdfsolver_lmsder; // default value + } - /** + /** Destructor (no operations) - */ + */ ~GSLMultiFit () { if (fSolver) gsl_multifit_fdfsolver_free(fSolver); - if (fVec != 0) gsl_vector_free(fVec); - if (fCov != 0) gsl_matrix_free(fCov); - } + if (fVec != 0) gsl_vector_free(fVec); + if (fCov != 0) gsl_matrix_free(fCov); + } private: // usually copying is non trivial, so we make this unaccessible - /** + /** Copy constructor - */ - GSLMultiFit(const GSLMultiFit &) {} + */ + GSLMultiFit(const GSLMultiFit &) {} - /** + /** Assignment operator - */ + */ GSLMultiFit & operator = (const GSLMultiFit & rhs) { if (this == &rhs) return *this; // time saving self-test return *this; } -public: +public: - /// create the minimizer from the type and size of number of fitting points and number of parameters - void CreateSolver(unsigned int npoints, unsigned int npar) { + /// create the minimizer from the type and size of number of fitting points and number of parameters + void CreateSolver(unsigned int npoints, unsigned int npar) { if (fSolver) gsl_multifit_fdfsolver_free(fSolver); fSolver = gsl_multifit_fdfsolver_alloc(fType, npoints, npar); - } + } - /// set the solver parameters - template<class Func> - int Set(const std::vector<Func> & funcVec, const double * x) { + /// set the solver parameters + template<class Func> + int Set(const std::vector<Func> & funcVec, const double * x) { // create a vector of the fit contributions // create function wrapper from an iterator of functions - unsigned int npts = funcVec.size(); - if (npts == 0) return -1; - - unsigned int npar = funcVec[0].NDim(); - fFunc.SetFunction(funcVec, npts, npar); - // create solver object - CreateSolver( npts, npar ); - // set initial values - if (fVec != 0) gsl_vector_free(fVec); - fVec = gsl_vector_alloc( npar ); - std::copy(x,x+npar, fVec->data); - assert(fSolver != 0); - return gsl_multifit_fdfsolver_set(fSolver, fFunc.GetFunc(), fVec); + unsigned int npts = funcVec.size(); + if (npts == 0) return -1; + + unsigned int npar = funcVec[0].NDim(); + // Remove unused typedef to remove warning in GCC48 + // http://gcc.gnu.org/gcc-4.8/porting_to.html + // typedef typename std::vector<Func> FuncVec; + //FuncIt funcIter = funcVec.begin(); + fFunc.SetFunction(funcVec, npts, npar); + // create solver object + CreateSolver( npts, npar ); + // set initial values + if (fVec != 0) gsl_vector_free(fVec); + fVec = gsl_vector_alloc( npar ); + std::copy(x,x+npar, fVec->data); + assert(fSolver != 0); + return gsl_multifit_fdfsolver_set(fSolver, fFunc.GetFunc(), fVec); } - std::string Name() const { + std::string Name() const { if (fSolver == 0) return "undefined"; - return std::string(gsl_multifit_fdfsolver_name(fSolver) ); + return std::string(gsl_multifit_fdfsolver_name(fSolver) ); } - - int Iterate() { - if (fSolver == 0) return -1; - return gsl_multifit_fdfsolver_iterate(fSolver); + + int Iterate() { + if (fSolver == 0) return -1; + return gsl_multifit_fdfsolver_iterate(fSolver); } - /// parameter values at the minimum - const double * X() const { - if (fSolver == 0) return 0; - gsl_vector * x = gsl_multifit_fdfsolver_position(fSolver); - return x->data; - } - - /// gradient value at the minimum - const double * Gradient() const { - if (fSolver == 0) return 0; - gsl_multifit_gradient(fSolver->J, fSolver->f,fVec); - return fVec->data; + /// parameter values at the minimum + const double * X() const { + if (fSolver == 0) return 0; + gsl_vector * x = gsl_multifit_fdfsolver_position(fSolver); + return x->data; + } + + /// gradient value at the minimum + const double * Gradient() const { + if (fSolver == 0) return 0; + gsl_multifit_gradient(fSolver->J, fSolver->f,fVec); + return fVec->data; } /// return covariance matrix of the parameters - const double * CovarMatrix() const { - if (fSolver == 0) return 0; - if (fCov != 0) gsl_matrix_free(fCov); - unsigned int npar = fSolver->fdf->p; - fCov = gsl_matrix_alloc( npar, npar ); + const double * CovarMatrix() const { + if (fSolver == 0) return 0; + if (fCov != 0) gsl_matrix_free(fCov); + unsigned int npar = fSolver->fdf->p; + fCov = gsl_matrix_alloc( npar, npar ); static double kEpsrel = 0.0001; int ret = gsl_multifit_covar(fSolver->J, kEpsrel, fCov); - if (ret != GSL_SUCCESS) return 0; - return fCov->data; + if (ret != GSL_SUCCESS) return 0; + return fCov->data; } /// test gradient (ask from solver gradient vector) - int TestGradient(double absTol) const { - if (fSolver == 0) return -1; - Gradient(); - return gsl_multifit_test_gradient( fVec, absTol); + int TestGradient(double absTol) const { + if (fSolver == 0) return -1; + Gradient(); + return gsl_multifit_test_gradient( fVec, absTol); } /// test using abs and relative tolerance /// |dx| < absTol + relTol*|x| for every component - int TestDelta(double absTol, double relTol) const { - if (fSolver == 0) return -1; + int TestDelta(double absTol, double relTol) const { + if (fSolver == 0) return -1; return gsl_multifit_test_delta(fSolver->dx, fSolver->x, absTol, relTol); } // calculate edm 1/2 * ( grad^T * Cov * grad ) - double Edm() const { + double Edm() const { // product C * g double edm = -1; - const double * g = Gradient(); + const double * g = Gradient(); if (g == 0) return edm; - const double * c = CovarMatrix(); + const double * c = CovarMatrix(); if (c == 0) return edm; - gsl_vector * tmp = gsl_vector_alloc( fSolver->fdf->p ); - int status = gsl_blas_dgemv(CblasNoTrans, 1.0, fCov, fVec, 0.,tmp); - if (status == 0) status |= gsl_blas_ddot(fVec, tmp, &edm); + gsl_vector * tmp = gsl_vector_alloc( fSolver->fdf->p ); + int status = gsl_blas_dgemv(CblasNoTrans, 1.0, fCov, fVec, 0.,tmp); + if (status == 0) status |= gsl_blas_ddot(fVec, tmp, &edm); gsl_vector_free(tmp); - if (status != 0) return -1; + if (status != 0) return -1; // need to divide by 2 ?? - return 0.5*edm; - + return 0.5*edm; + } - -private: - GSLMultiFitFunctionWrapper fFunc; +private: + + GSLMultiFitFunctionWrapper fFunc; gsl_multifit_fdfsolver * fSolver; // cached vector to avoid re-allocating every time a new one - mutable gsl_vector * fVec; - mutable gsl_matrix * fCov; - const gsl_multifit_fdfsolver_type * fType; + mutable gsl_vector * fVec; + mutable gsl_matrix * fCov; + const gsl_multifit_fdfsolver_type * fType; -}; +}; } // end namespace Math diff --git a/ThirdParty/RootMinimizers/src/Math/GSLMultiFitFunctionAdapter.h b/ThirdParty/RootMinimizers/src/Math/GSLMultiFitFunctionAdapter.h index ee6b88a321ac441f8eecc519e4b8f20c69c60067..54cd33f209db854c2d7f29fb9f259282d5e6bc6c 100644 --- a/ThirdParty/RootMinimizers/src/Math/GSLMultiFitFunctionAdapter.h +++ b/ThirdParty/RootMinimizers/src/Math/GSLMultiFitFunctionAdapter.h @@ -24,13 +24,13 @@ // Header file for class GSLMultiMinFunctionAdapter // -// Generic adapter for gsl_multimin_function signature -// usable for any c++ class which defines operator( ) -// +// Generic adapter for gsl_multimin_function signature +// usable for any c++ class which defines operator( ) +// // Created by: Lorenzo Moneta at Fri Nov 12 16:58:51 2004 -// +// // Last update: Fri Nov 12 16:58:51 2004 -// +// #ifndef ROOT_Math_GSLMultiFitFunctionAdapter #define ROOT_Math_GSLMultiFitFunctionAdapter @@ -47,78 +47,78 @@ namespace Math { /** - Class for adapting a C++ functor class to C function pointers used by GSL MultiFit + Class for adapting a C++ functor class to C function pointers used by GSL MultiFit Algorithm - The templated C++ function class must implement: + The templated C++ function class must implement: <em> double operator( const double * x)</em> - and if the derivatives are required: + and if the derivatives are required: <em> void Gradient( const double * x, double * g)</em> - and + and <em> void FdF( const double * x, double &f, double * g)</em> - - This class defines static methods with will be used to fill the - \a gsl_multimin_function and - \a gsl_multimin_function_fdf structs used by GSL. - See for examples the + + This class defines static methods with will be used to fill the + \a gsl_multimin_function and + \a gsl_multimin_function_fdf structs used by GSL. + See for examples the <A HREF="http://www.gnu.org/software/gsl/manual/html_node/Providing-a-function-to-minimize.html#Providing-a-function-to-minimize">GSL online manual</A> @ingroup MultiMin - */ - + */ -template<class FuncVector> + +template<class FuncVector> class GSLMultiFitFunctionAdapter { -public: - - static int F( const gsl_vector * x, void * p, gsl_vector * f ) { +public: + + static int F( const gsl_vector * x, void * p, gsl_vector * f ) { // p is a pointer to an iterator of functions unsigned int n = f->size; - // need to copy iterator otherwise next time the function is called it wont work + // need to copy iterator otherwise next time the function is called it wont work FuncVector & funcVec = *( reinterpret_cast< FuncVector *> (p) ); - if (n == 0) return -1; - for (unsigned int i = 0; i < n ; ++i) { + if (n == 0) return -1; + for (unsigned int i = 0; i < n ; ++i) { gsl_vector_set(f, i, (funcVec[i])(x->data) ); } - return 0; + return 0; } - - static int Df( const gsl_vector * x, void * p, gsl_matrix * h) { - + + static int Df( const gsl_vector * x, void * p, gsl_matrix * h) { + // p is a pointer to an iterator of functions unsigned int n = h->size1; unsigned int npar = h->size2; - if (n == 0) return -1; - if (npar == 0) return -2; + if (n == 0) return -1; + if (npar == 0) return -2; FuncVector & funcVec = *( reinterpret_cast< FuncVector *> (p) ); - for (unsigned int i = 0; i < n ; ++i) { + for (unsigned int i = 0; i < n ; ++i) { double * g = (h->data)+i*npar; //pointer to start of i-th row assert ( npar == (funcVec[i]).NDim() ); - (funcVec[i]).Gradient(x->data, g); + (funcVec[i]).Gradient(x->data, g); } - return 0; + return 0; } - /// evaluate derivative and function at the same time - static int FDf( const gsl_vector * x, void * p, gsl_vector * f, gsl_matrix * h) { + /// evaluate derivative and function at the same time + static int FDf( const gsl_vector * x, void * p, gsl_vector * f, gsl_matrix * h) { // should be implemented in the function // p is a pointer to an iterator of functions unsigned int n = h->size1; unsigned int npar = h->size2; - if (n == 0) return -1; - if (npar == 0) return -2; + if (n == 0) return -1; + if (npar == 0) return -2; FuncVector & funcVec = *( reinterpret_cast< FuncVector *> (p) ); - assert ( f->size == n); - for (unsigned int i = 0; i < n ; ++i) { + assert ( f->size == n); + for (unsigned int i = 0; i < n ; ++i) { assert ( npar == (funcVec[i]).NDim() ); - double fval = 0; + double fval = 0; double * g = (h->data)+i*npar; //pointer to start of i-th row - (funcVec[i]).FdF(x->data, fval, g); + (funcVec[i]).FdF(x->data, fval, g); gsl_vector_set(f, i, fval ); } - return 0; + return 0; } }; diff --git a/ThirdParty/RootMinimizers/src/Math/GSLMultiFitFunctionWrapper.h b/ThirdParty/RootMinimizers/src/Math/GSLMultiFitFunctionWrapper.h index 4eadcdcc1a5aabd382d27543ba92b8eb58109bfe..d3639bf4d2886e4af9b95284cf643e3b90fd8189 100644 --- a/ThirdParty/RootMinimizers/src/Math/GSLMultiFitFunctionWrapper.h +++ b/ThirdParty/RootMinimizers/src/Math/GSLMultiFitFunctionWrapper.h @@ -1,5 +1,5 @@ // @(#)root/mathmore:$Id$ -// Authors: L. Moneta Dec 2006 +// Authors: L. Moneta Dec 2006 /********************************************************************** * * @@ -23,11 +23,11 @@ **********************************************************************/ // Header file for class GSLMultiMinFunctionWrapper -// +// // Created by: moneta at Sat Nov 13 14:54:41 2004 -// +// // Last update: Sat Nov 13 14:54:41 2004 -// +// #ifndef ROOT_Math_GSLMultiFitFunctionWrapper #define ROOT_Math_GSLMultiFitFunctionWrapper @@ -49,46 +49,46 @@ namespace Math { /** - wrapper to a multi-dim function withtout derivatives for multi-dimensional + wrapper to a multi-dim function withtout derivatives for multi-dimensional minimization algorithm @ingroup MultiMin */ -class GSLMultiFitFunctionWrapper { +class GSLMultiFitFunctionWrapper { -public: +public: - GSLMultiFitFunctionWrapper() + GSLMultiFitFunctionWrapper() { - fFunc.f = 0; - fFunc.df = 0; - fFunc.fdf = 0; - fFunc.n = 0; - fFunc.p = 0; + fFunc.f = 0; + fFunc.df = 0; + fFunc.fdf = 0; + fFunc.n = 0; + fFunc.p = 0; fFunc.params = 0; } /// Fill gsl function structure from a C++ function iterator and size and number of residuals - template<class FuncVector> - void SetFunction(const FuncVector & f, unsigned int nres, unsigned int npar ) { + template<class FuncVector> + void SetFunction(const FuncVector & f, unsigned int nres, unsigned int npar ) { const void * p = &f; - assert (p != 0); + assert (p != 0); fFunc.f = &GSLMultiFitFunctionAdapter<FuncVector >::F; fFunc.df = &GSLMultiFitFunctionAdapter<FuncVector >::Df; fFunc.fdf = &GSLMultiFitFunctionAdapter<FuncVector >::FDf; - fFunc.n = nres; - fFunc.p = npar; - fFunc.params = const_cast<void *>(p); + fFunc.n = nres; + fFunc.p = npar; + fFunc.params = const_cast<void *>(p); } - - gsl_multifit_function_fdf * GetFunc() { return &fFunc; } + gsl_multifit_function_fdf * GetFunc() { return &fFunc; } - private: - - gsl_multifit_function_fdf fFunc; + + private: + + gsl_multifit_function_fdf fFunc; }; diff --git a/ThirdParty/RootMinimizers/src/Math/GSLMultiMinFunctionAdapter.h b/ThirdParty/RootMinimizers/src/Math/GSLMultiMinFunctionAdapter.h index 0be4d68798450a22d33f579698c6a52e1a09e525..7011ef2dae093d0ff45827c31f6191368d02d6bd 100644 --- a/ThirdParty/RootMinimizers/src/Math/GSLMultiMinFunctionAdapter.h +++ b/ThirdParty/RootMinimizers/src/Math/GSLMultiMinFunctionAdapter.h @@ -1,5 +1,5 @@ // @(#)root/mathmore:$Id$ -// Authors: L. Moneta, 12/2006 +// Authors: L. Moneta, 12/2006 /********************************************************************** * * @@ -24,13 +24,13 @@ // Header file for class GSLMultiMinFunctionAdapter // -// Generic adapter for gsl_multimin_function signature -// usable for any c++ class which defines operator( ) -// +// Generic adapter for gsl_multimin_function signature +// usable for any c++ class which defines operator( ) +// // Created by: Lorenzo Moneta at Fri Nov 12 16:58:51 2004 -// +// // Last update: Fri Nov 12 16:58:51 2004 -// +// #ifndef ROOT_Math_GSLMultiMinFunctionAdapter #define ROOT_Math_GSLMultiMinFunctionAdapter @@ -43,50 +43,50 @@ namespace Math { /** - Class for adapting any multi-dimension C++ functor class to C function pointers used by - GSL MultiMin algorithms. - The templated C++ function class must implement: + Class for adapting any multi-dimension C++ functor class to C function pointers used by + GSL MultiMin algorithms. + The templated C++ function class must implement: <em> double operator( const double * x)</em> - and if the derivatives are required: + and if the derivatives are required: <em> void Gradient( const double * x, double * g)</em> - - This class defines static methods with will be used to fill the - \a gsl_multimin_function and - \a gsl_multimin_function_fdf structs used by GSL. - See for examples the + + This class defines static methods with will be used to fill the + \a gsl_multimin_function and + \a gsl_multimin_function_fdf structs used by GSL. + See for examples the <A HREF="http://www.gnu.org/software/gsl/manual/html_node/Providing-a-function-to-minimize.html#Providing-a-function-to-minimize">GSL online manual</A> @ingroup MultiMin - */ - + */ - template<class UserFunc> + + template<class UserFunc> struct GSLMultiMinFunctionAdapter { - - static double F( const gsl_vector * x, void * p) { - + + static double F( const gsl_vector * x, void * p) { + UserFunc * function = reinterpret_cast< UserFunc *> (p); // get pointer to data from gsl_vector - return (*function)( x->data ); + return (*function)( x->data ); } - - static void Df( const gsl_vector * x, void * p, gsl_vector * g) { - - UserFunc * function = reinterpret_cast< UserFunc *> (p); + + static void Df( const gsl_vector * x, void * p, gsl_vector * g) { + + UserFunc * function = reinterpret_cast< UserFunc *> (p); (*function).Gradient( x->data, g->data ); - + } - static void Fdf( const gsl_vector * x, void * p, double *f, gsl_vector * g ) { - - UserFunc * function = reinterpret_cast< UserFunc *> (p); -// *f = (*function) ( x ); -// *df = (*function).Gradient( x ); + static void Fdf( const gsl_vector * x, void * p, double *f, gsl_vector * g ) { + + UserFunc * function = reinterpret_cast< UserFunc *> (p); +// *f = (*function) ( x ); +// *df = (*function).Gradient( x ); - (*function).FdF( x->data, *f, g->data); + (*function).FdF( x->data, *f, g->data); } }; diff --git a/ThirdParty/RootMinimizers/src/Math/GSLMultiMinFunctionWrapper.h b/ThirdParty/RootMinimizers/src/Math/GSLMultiMinFunctionWrapper.h index e70e5b83d6e160608c703c1a5eebdbab97cee371..d80068042ae8d3fb7061c36c64c7e3c98142d782 100644 --- a/ThirdParty/RootMinimizers/src/Math/GSLMultiMinFunctionWrapper.h +++ b/ThirdParty/RootMinimizers/src/Math/GSLMultiMinFunctionWrapper.h @@ -1,5 +1,5 @@ // @(#)root/mathmore:$Id$ -// Authors: L. Moneta, 12/2006 +// Authors: L. Moneta, 12/2006 /********************************************************************** * * @@ -23,11 +23,11 @@ **********************************************************************/ // Header file for class GSLMultiMinFunctionWrapper -// +// // Created by: moneta at Sat Nov 13 14:54:41 2004 -// +// // Last update: Sat Nov 13 14:54:41 2004 -// +// #ifndef ROOT_Math_GSLMultiMinFunctionWrapper #define ROOT_Math_GSLMultiMinFunctionWrapper @@ -49,47 +49,47 @@ namespace Math { /** - wrapper to a multi-dim function withtout derivatives for multi-dimensional + wrapper to a multi-dim function withtout derivatives for multi-dimensional minimization algorithm @ingroup MultiMin */ -class GSLMultiMinFunctionWrapper { +class GSLMultiMinFunctionWrapper { -public: +public: - GSLMultiMinFunctionWrapper() + GSLMultiMinFunctionWrapper() { - fFunc.f = 0; - fFunc.n = 0; + fFunc.f = 0; + fFunc.n = 0; fFunc.params = 0; } - void SetFuncPointer( GSLMultiMinFuncPointer f) { fFunc.f = f; } + void SetFuncPointer( GSLMultiMinFuncPointer f) { fFunc.f = f; } void SetDim ( unsigned int n ) { fFunc.n = n; } void SetParams ( void * p) { fFunc.params = p; } - /// Fill gsl function structure from a C++ Function class - template<class FuncType> - void SetFunction(const FuncType &f) { + /// Fill gsl function structure from a C++ Function class + template<class FuncType> + void SetFunction(const FuncType &f) { const void * p = &f; - assert (p != 0); + assert (p != 0); SetFuncPointer(&GSLMultiMinFunctionAdapter<FuncType >::F); - SetDim( f.NDim() ); + SetDim( f.NDim() ); SetParams(const_cast<void *>(p)); } - - gsl_multimin_function * GetFunc() { return &fFunc; } - bool IsValid() { - return (fFunc.f != 0) ? true : false; + gsl_multimin_function * GetFunc() { return &fFunc; } + + bool IsValid() { + return (fFunc.f != 0) ? true : false; } - private: + private: - gsl_multimin_function fFunc; + gsl_multimin_function fFunc; }; @@ -101,57 +101,57 @@ public: @ingroup MultiMin */ - class GSLMultiMinDerivFunctionWrapper { + class GSLMultiMinDerivFunctionWrapper { - public: + public: - GSLMultiMinDerivFunctionWrapper() + GSLMultiMinDerivFunctionWrapper() { - fFunc.f = 0; - fFunc.df = 0; - fFunc.fdf = 0; - fFunc.n = 0; + fFunc.f = 0; + fFunc.df = 0; + fFunc.fdf = 0; + fFunc.n = 0; fFunc.params = 0; } - void SetFuncPointer( GSLMultiMinFuncPointer f) { fFunc.f = f; } - void SetDerivPointer( GSLMultiMinDfPointer f) { fFunc.df = f; } - void SetFdfPointer( GSLMultiMinFdfPointer f) { fFunc.fdf = f; } + void SetFuncPointer( GSLMultiMinFuncPointer f) { fFunc.f = f; } + void SetDerivPointer( GSLMultiMinDfPointer f) { fFunc.df = f; } + void SetFdfPointer( GSLMultiMinFdfPointer f) { fFunc.fdf = f; } void SetDim ( unsigned int n ) { fFunc.n = n; } void SetParams ( void * p) { fFunc.params = p; } - /// Fill gsl function structure from a C++ Function class - template<class FuncType> - void SetFunction(const FuncType &f) { + /// Fill gsl function structure from a C++ Function class + template<class FuncType> + void SetFunction(const FuncType &f) { const void * p = &f; - assert (p != 0); + assert (p != 0); SetFuncPointer(&GSLMultiMinFunctionAdapter<FuncType >::F); SetDerivPointer(&GSLMultiMinFunctionAdapter<FuncType >::Df); SetFdfPointer(&GSLMultiMinFunctionAdapter<FuncType >::Fdf); - SetDim( f.NDim() ); + SetDim( f.NDim() ); SetParams(const_cast<void *>(p)); } - - gsl_multimin_function_fdf * GetFunc() { return &fFunc; } + + gsl_multimin_function_fdf * GetFunc() { return &fFunc; } #ifdef NEEDED_LATER - // evaluate the function - double operator() (const double * x) { + // evaluate the function + double operator() (const double * x) { // vx must be a gsl_vector - return GSL_MULTIMIN_FN_EVAL(&fFunc, vx); + return GSL_MULTIMIN_FN_EVAL(&fFunc, vx); } #endif - /// check if function is valid (has been set) - bool IsValid() { - return (fFunc.f != 0) ? true : false; + /// check if function is valid (has been set) + bool IsValid() { + return (fFunc.f != 0) ? true : false; } - private: + private: + + gsl_multimin_function_fdf fFunc; - gsl_multimin_function_fdf fFunc; - }; diff --git a/ThirdParty/RootMinimizers/src/Math/GSLMultiMinimizer.h b/ThirdParty/RootMinimizers/src/Math/GSLMultiMinimizer.h index e8e83bcf9ed19056118d37a23387f322c13ee18d..249556b981dae2badc52384bbf44a06bb897eee7 100644 --- a/ThirdParty/RootMinimizers/src/Math/GSLMultiMinimizer.h +++ b/ThirdParty/RootMinimizers/src/Math/GSLMultiMinimizer.h @@ -29,34 +29,35 @@ #include "gsl/gsl_vector.h" #include "gsl/gsl_multimin.h" +#include "gsl/gsl_version.h" #include "GSLMultiMinFunctionWrapper.h" #include "Math/Error.h" #include "Math/IFunction.h" -#include <cassert> +#include <cassert> -namespace ROOT { +namespace ROOT { - namespace Math { + namespace Math { -/** - GSLMultiMinimizer class , for minimizing multi-dimensional function - using derivatives +/** + GSLMultiMinimizer class , for minimizing multi-dimensional function + using derivatives @ingroup MultiMin -*/ +*/ class GSLMultiMinimizer { -public: +public: - /** + /** Default constructor - */ - GSLMultiMinimizer (ROOT::Math::EGSLMinimizerType type) : + */ + GSLMultiMinimizer (ROOT::Math::EGSLMinimizerType type) : fMinimizer(0), fType(0), fVec(0) @@ -64,146 +65,146 @@ public: switch(type) { case ROOT::Math::kConjugateFR : - fType = gsl_multimin_fdfminimizer_conjugate_fr; - break; - case ROOT::Math::kConjugatePR : - fType = gsl_multimin_fdfminimizer_conjugate_pr; + fType = gsl_multimin_fdfminimizer_conjugate_fr; + break; + case ROOT::Math::kConjugatePR : + fType = gsl_multimin_fdfminimizer_conjugate_pr; break; - case ROOT::Math::kVectorBFGS : - fType = gsl_multimin_fdfminimizer_vector_bfgs; - break; - case ROOT::Math::kVectorBFGS2 : -#if defined (GSL_VERSION_NUM) && GSL_VERSION_NUM >= 1009 - // bfgs2 is available only for v>= 1.9 - fType = gsl_multimin_fdfminimizer_vector_bfgs2; -#else + case ROOT::Math::kVectorBFGS : + fType = gsl_multimin_fdfminimizer_vector_bfgs; + break; + case ROOT::Math::kVectorBFGS2 : +#if (GSL_MAJOR_VERSION > 1) || ((GSL_MAJOR_VERSION == 1) && (GSL_MINOR_VERSION >= 9)) + // bfgs2 is available only for v>= 1.9 + fType = gsl_multimin_fdfminimizer_vector_bfgs2; +#else MATH_INFO_MSG("GSLMultiMinimizer","minimizer BFSG2 does not exist with this GSL version , use BFGS"); fType = gsl_multimin_fdfminimizer_vector_bfgs; -#endif - break; +#endif + break; case ROOT::Math::kSteepestDescent: - fType = gsl_multimin_fdfminimizer_steepest_descent; - break; - default: - fType = gsl_multimin_fdfminimizer_conjugate_fr; - break; + fType = gsl_multimin_fdfminimizer_steepest_descent; + break; + default: + fType = gsl_multimin_fdfminimizer_conjugate_fr; + break; } - + } - /** - Destructor - */ + /** + Destructor + */ ~GSLMultiMinimizer () { - if (fMinimizer != 0 ) gsl_multimin_fdfminimizer_free(fMinimizer); + if (fMinimizer != 0 ) gsl_multimin_fdfminimizer_free(fMinimizer); // can free vector (is copied inside) - if (fVec != 0) gsl_vector_free(fVec); - } + if (fVec != 0) gsl_vector_free(fVec); + } private: // usually copying is non trivial, so we make this unaccessible - /** + /** Copy constructor - */ - GSLMultiMinimizer(const GSLMultiMinimizer &) {} + */ + GSLMultiMinimizer(const GSLMultiMinimizer &) {} - /** + /** Assignment operator - */ + */ GSLMultiMinimizer & operator = (const GSLMultiMinimizer & rhs) { if (this == &rhs) return *this; // time saving self-test return *this; } -public: +public: /** - set the function to be minimize the initial minimizer parameters, - step size and tolerance in the line search - */ - int Set(const ROOT::Math::IMultiGradFunction & func, const double * x, double stepSize, double tol) { + set the function to be minimize the initial minimizer parameters, + step size and tolerance in the line search + */ + int Set(const ROOT::Math::IMultiGradFunction & func, const double * x, double stepSize, double tol) { // create function wrapper - fFunc.SetFunction(func); - // create minimizer object (free previous one if already existing) - unsigned int ndim = func.NDim(); - CreateMinimizer( ndim ); - // set initial values - if (fVec != 0) gsl_vector_free(fVec); - fVec = gsl_vector_alloc( ndim ); - std::copy(x,x+ndim, fVec->data); - assert(fMinimizer != 0); - return gsl_multimin_fdfminimizer_set(fMinimizer, fFunc.GetFunc(), fVec, stepSize, tol); + fFunc.SetFunction(func); + // create minimizer object (free previous one if already existing) + unsigned int ndim = func.NDim(); + CreateMinimizer( ndim ); + // set initial values + if (fVec != 0) gsl_vector_free(fVec); + fVec = gsl_vector_alloc( ndim ); + std::copy(x,x+ndim, fVec->data); + assert(fMinimizer != 0); + return gsl_multimin_fdfminimizer_set(fMinimizer, fFunc.GetFunc(), fVec, stepSize, tol); } - /// create the minimizer from the type and size - void CreateMinimizer(unsigned int n) { - if (fMinimizer) gsl_multimin_fdfminimizer_free(fMinimizer); + /// create the minimizer from the type and size + void CreateMinimizer(unsigned int n) { + if (fMinimizer) gsl_multimin_fdfminimizer_free(fMinimizer); fMinimizer = gsl_multimin_fdfminimizer_alloc(fType, n); - } + } - std::string Name() const { + std::string Name() const { if (fMinimizer == 0) return "undefined"; - return std::string(gsl_multimin_fdfminimizer_name(fMinimizer) ); + return std::string(gsl_multimin_fdfminimizer_name(fMinimizer) ); } - - int Iterate() { - if (fMinimizer == 0) return -1; - return gsl_multimin_fdfminimizer_iterate(fMinimizer); + + int Iterate() { + if (fMinimizer == 0) return -1; + return gsl_multimin_fdfminimizer_iterate(fMinimizer); + } + + /// x values at the minimum + double * X() const { + if (fMinimizer == 0) return 0; + gsl_vector * x = gsl_multimin_fdfminimizer_x(fMinimizer); + return x->data; } - /// x values at the minimum - double * X() const { - if (fMinimizer == 0) return 0; - gsl_vector * x = gsl_multimin_fdfminimizer_x(fMinimizer); - return x->data; - } - - /// function value at the minimum - double Minimum() const { - if (fMinimizer == 0) return 0; - return gsl_multimin_fdfminimizer_minimum(fMinimizer); + /// function value at the minimum + double Minimum() const { + if (fMinimizer == 0) return 0; + return gsl_multimin_fdfminimizer_minimum(fMinimizer); } - /// gradient value at the minimum - double * Gradient() const { - if (fMinimizer == 0) return 0; - gsl_vector * g = gsl_multimin_fdfminimizer_gradient(fMinimizer); - return g->data; + /// gradient value at the minimum + double * Gradient() const { + if (fMinimizer == 0) return 0; + gsl_vector * g = gsl_multimin_fdfminimizer_gradient(fMinimizer); + return g->data; } /// restart minimization from current point - int Restart() { - if (fMinimizer == 0) return -1; - return gsl_multimin_fdfminimizer_restart(fMinimizer); + int Restart() { + if (fMinimizer == 0) return -1; + return gsl_multimin_fdfminimizer_restart(fMinimizer); } - /// test gradient (ask from minimizer gradient vector) - int TestGradient(double absTol) const { - if (fMinimizer == 0) return -1; - gsl_vector * g = gsl_multimin_fdfminimizer_gradient(fMinimizer); - return gsl_multimin_test_gradient( g, absTol); + /// test gradient (ask from minimizer gradient vector) + int TestGradient(double absTol) const { + if (fMinimizer == 0) return -1; + gsl_vector * g = gsl_multimin_fdfminimizer_gradient(fMinimizer); + return gsl_multimin_test_gradient( g, absTol); } - /// test gradient (require a vector gradient) - int TestGradient(const double * g, double absTol) const { - if (fVec == 0 ) return -1; - unsigned int n = fVec->size; - if (n == 0 ) return -1; + /// test gradient (require a vector gradient) + int TestGradient(const double * g, double absTol) const { + if (fVec == 0 ) return -1; + unsigned int n = fVec->size; + if (n == 0 ) return -1; std::copy(g,g+n, fVec->data); - return gsl_multimin_test_gradient( fVec, absTol); + return gsl_multimin_test_gradient( fVec, absTol); } -private: +private: - gsl_multimin_fdfminimizer * fMinimizer; - GSLMultiMinDerivFunctionWrapper fFunc; - const gsl_multimin_fdfminimizer_type * fType; + gsl_multimin_fdfminimizer * fMinimizer; + GSLMultiMinDerivFunctionWrapper fFunc; + const gsl_multimin_fdfminimizer_type * fType; // cached vector to avoid re-allocating every time a new one - mutable gsl_vector * fVec; + mutable gsl_vector * fVec; -}; +}; } // end namespace Math diff --git a/ThirdParty/RootMinimizers/src/Math/GSLRndmEngines.cxx b/ThirdParty/RootMinimizers/src/Math/GSLRndmEngines.cxx index 6faac2b08714559487012f4185dccbf87f699feb..3c37a0a7dc98c0a8f4ae91a8f5d9eb300c2b1e40 100644 --- a/ThirdParty/RootMinimizers/src/Math/GSLRndmEngines.cxx +++ b/ThirdParty/RootMinimizers/src/Math/GSLRndmEngines.cxx @@ -1,5 +1,5 @@ // @(#)root/mathmore:$Id$ -// Authors: L. Moneta, A. Zsenei 08/2005 +// Authors: L. Moneta, A. Zsenei 08/2005 /********************************************************************** * * @@ -23,11 +23,11 @@ **********************************************************************/ // Header file for class GSLRandom -// +// // Created by: moneta at Sun Nov 21 16:26:03 2004 -// +// // Last update: Sun Nov 21 16:26:03 2004 -// +// @@ -55,21 +55,21 @@ namespace Math { // default constructor (need to call set type later) - GSLRandomEngine::GSLRandomEngine() : + GSLRandomEngine::GSLRandomEngine() : fRng(0 ), - fCurTime(0) - { } + fCurTime(0) + { } // constructor from external rng - // internal generator will be managed or not depending on + // internal generator will be managed or not depending on // how the GSLRngWrapper is created - GSLRandomEngine::GSLRandomEngine( GSLRngWrapper * rng) : + GSLRandomEngine::GSLRandomEngine( GSLRngWrapper * rng) : fRng(new GSLRngWrapper(*rng) ), fCurTime(0) {} - // copy constructor - GSLRandomEngine::GSLRandomEngine(const GSLRandomEngine & eng) : + // copy constructor + GSLRandomEngine::GSLRandomEngine(const GSLRandomEngine & eng) : fRng(new GSLRngWrapper(*eng.fRng) ), fCurTime(0) {} @@ -79,104 +79,104 @@ namespace Math { if (fRng) Terminate(); } - // assignment operator + // assignment operator GSLRandomEngine & GSLRandomEngine::operator=(const GSLRandomEngine & eng) { if (this == &eng) return *this; - if (fRng) + if (fRng) *fRng = *eng.fRng; - else + else fRng = new GSLRngWrapper(*eng.fRng); fCurTime = eng.fCurTime; return *this; } - void GSLRandomEngine::Initialize() { + void GSLRandomEngine::Initialize() { // initialize the generator by allocating the GSL object // if type was not passed create with default generator - if (!fRng) fRng = new GSLRngWrapper(); - fRng->Allocate(); + if (!fRng) fRng = new GSLRngWrapper(); + fRng->Allocate(); } - void GSLRandomEngine::Terminate() { + void GSLRandomEngine::Terminate() { // terminate the generator by freeing the GSL object if (!fRng) return; fRng->Free(); - delete fRng; - fRng = 0; + delete fRng; + fRng = 0; } - double GSLRandomEngine::operator() () const { - // generate random between 0 and 1. - // 0 is excluded - return gsl_rng_uniform_pos(fRng->Rng() ); + double GSLRandomEngine::operator() () const { + // generate random between 0 and 1. + // 0 is excluded + return gsl_rng_uniform_pos(fRng->Rng() ); } - unsigned int GSLRandomEngine::RndmInt(unsigned int max) const { + unsigned int GSLRandomEngine::RndmInt(unsigned int max) const { // generate a random integer number between 0 and MAX return gsl_rng_uniform_int( fRng->Rng(), max ); } -// int GSLRandomEngine::GetMin() { +// int GSLRandomEngine::GetMin() { // // return minimum integer value used in RndmInt // return gsl_rng_min( fRng->Rng() ); // } -// int GSLRandomEngine::GetMax() { +// int GSLRandomEngine::GetMax() { // // return maximum integr value used in RndmInt // return gsl_rng_max( fRng->Rng() ); // } - void GSLRandomEngine::RandomArray(double * begin, double * end ) const { - // generate array of randoms betweeen 0 and 1. 0 is excluded - // specialization for double * (to be faster) - for ( double * itr = begin; itr != end; ++itr ) { - *itr = gsl_rng_uniform_pos(fRng->Rng() ); + void GSLRandomEngine::RandomArray(double * begin, double * end ) const { + // generate array of randoms betweeen 0 and 1. 0 is excluded + // specialization for double * (to be faster) + for ( double * itr = begin; itr != end; ++itr ) { + *itr = gsl_rng_uniform_pos(fRng->Rng() ); } } - void GSLRandomEngine::SetSeed(unsigned int seed) const { + void GSLRandomEngine::SetSeed(unsigned int seed) const { // set the seed, if = 0then the seed is set randomly using an std::rand() - // seeded with the current time. Be carefuk in case the current time is - // the same in consecutive calls - if (seed == 0) { + // seeded with the current time. Be carefuk in case the current time is + // the same in consecutive calls + if (seed == 0) { // use like in root (use time) - time_t curtime; - time(&curtime); + time_t curtime; + time(&curtime); unsigned int ct = static_cast<unsigned int>(curtime); - if (ct != fCurTime) { - fCurTime = ct; + if (ct != fCurTime) { + fCurTime = ct; // set the seed for rand - srand(ct); + srand(ct); } seed = rand(); - } + } assert(fRng); - gsl_rng_set(fRng->Rng(), seed ); + gsl_rng_set(fRng->Rng(), seed ); } - std::string GSLRandomEngine::Name() const { + std::string GSLRandomEngine::Name() const { //---------------------------------------------------- - assert ( fRng != 0); - assert ( fRng->Rng() != 0 ); - return std::string( gsl_rng_name( fRng->Rng() ) ); + assert ( fRng != 0); + assert ( fRng->Rng() != 0 ); + return std::string( gsl_rng_name( fRng->Rng() ) ); } - unsigned int GSLRandomEngine::Size() const { + unsigned int GSLRandomEngine::Size() const { //---------------------------------------------------- assert (fRng != 0); - return gsl_rng_size( fRng->Rng() ); + return gsl_rng_size( fRng->Rng() ); } // Random distributions - + double GSLRandomEngine::GaussianZig(double sigma) const { - // Gaussian distribution. Use fast ziggurat algorithm implemented since GSL 1.8 + // Gaussian distribution. Use fast ziggurat algorithm implemented since GSL 1.8 return gsl_ran_gaussian_ziggurat( fRng->Rng(), sigma); } @@ -193,19 +193,19 @@ namespace Math { } - double GSLRandomEngine::GaussianTail(double a , double sigma) const + double GSLRandomEngine::GaussianTail(double a , double sigma) const { - // Gaussian Tail distribution: eeturn values larger than a distributed - // according to the gaussian + // Gaussian Tail distribution: eeturn values larger than a distributed + // according to the gaussian return gsl_ran_gaussian_tail( fRng->Rng(), a, sigma); } void GSLRandomEngine::Gaussian2D(double sigmaX, double sigmaY, double rho, double &x, double &y) const - { + { // Gaussian Bivariate distribution, with correlation coefficient rho gsl_ran_bivariate_gaussian( fRng->Rng(), sigmaX, sigmaY, rho, &x, &y); } - + double GSLRandomEngine::Exponential(double mu) const { // Exponential distribution @@ -224,7 +224,7 @@ namespace Math { return gsl_ran_landau( fRng->Rng()); } - double GSLRandomEngine::Gamma(double a, double b) const + double GSLRandomEngine::Gamma(double a, double b) const { // Gamma distribution return gsl_ran_gamma( fRng->Rng(), a, b); @@ -236,7 +236,7 @@ namespace Math { return gsl_ran_lognormal( fRng->Rng(), zeta, sigma); } - double GSLRandomEngine::ChiSquare(double nu) const + double GSLRandomEngine::ChiSquare(double nu) const { // Chi square distribution return gsl_ran_chisq( fRng->Rng(), nu); @@ -254,50 +254,50 @@ namespace Math { // t distribution return gsl_ran_tdist( fRng->Rng(), nu); } - - void GSLRandomEngine::Dir2D(double &x, double &y) const - { - // generate random numbers in a 2D circle of radious 1 + + void GSLRandomEngine::Dir2D(double &x, double &y) const + { + // generate random numbers in a 2D circle of radious 1 gsl_ran_dir_2d( fRng->Rng(), &x, &y); } void GSLRandomEngine::Dir3D(double &x, double &y, double &z) const - { - // generate random numbers in a 3D sphere of radious 1 + { + // generate random numbers in a 3D sphere of radious 1 gsl_ran_dir_3d( fRng->Rng(), &x, &y, &z); } - + unsigned int GSLRandomEngine::Poisson(double mu) const - { + { // Poisson distribution return gsl_ran_poisson( fRng->Rng(), mu); } unsigned int GSLRandomEngine::Binomial(double p, unsigned int n) const - { + { // Binomial distribution return gsl_ran_binomial( fRng->Rng(), p, n); } unsigned int GSLRandomEngine::NegativeBinomial(double p, double n) const - { + { // Negative Binomial distribution return gsl_ran_negative_binomial( fRng->Rng(), p, n); } std::vector<unsigned int> GSLRandomEngine::Multinomial( unsigned int ntot, const std::vector<double> & p ) const - { + { // Multinomial distribution return vector of integers which sum is ntot - std::vector<unsigned int> ival( p.size()); + std::vector<unsigned int> ival( p.size()); gsl_ran_multinomial( fRng->Rng(), p.size(), ntot, &p.front(), &ival[0]); - return ival; + return ival; } //---------------------------------------------------- - // generators + // generators //---------------------------------------------------- //---------------------------------------------------- @@ -308,74 +308,74 @@ namespace Math { // old ranlux - equivalent to TRandom1 - GSLRngRanLux::GSLRngRanLux() : GSLRandomEngine() + GSLRngRanLux::GSLRngRanLux() : GSLRandomEngine() { SetType(new GSLRngWrapper(gsl_rng_ranlux) ); } // second generation of Ranlux (single precision version - luxury 1) - GSLRngRanLuxS1::GSLRngRanLuxS1() : GSLRandomEngine() + GSLRngRanLuxS1::GSLRngRanLuxS1() : GSLRandomEngine() { SetType(new GSLRngWrapper(gsl_rng_ranlxs1) ); } // second generation of Ranlux (single precision version - luxury 2) - GSLRngRanLuxS2::GSLRngRanLuxS2() : GSLRandomEngine() + GSLRngRanLuxS2::GSLRngRanLuxS2() : GSLRandomEngine() { SetType(new GSLRngWrapper(gsl_rng_ranlxs2) ); } - // double precision version - luxury 1 - GSLRngRanLuxD1::GSLRngRanLuxD1() : GSLRandomEngine() + // double precision version - luxury 1 + GSLRngRanLuxD1::GSLRngRanLuxD1() : GSLRandomEngine() { SetType(new GSLRngWrapper(gsl_rng_ranlxd1) ); } - - // double precision version - luxury 2 - GSLRngRanLuxD2::GSLRngRanLuxD2() : GSLRandomEngine() + + // double precision version - luxury 2 + GSLRngRanLuxD2::GSLRngRanLuxD2() : GSLRandomEngine() { SetType(new GSLRngWrapper(gsl_rng_ranlxd2) ); } //---------------------------------------------------- - GSLRngTaus::GSLRngTaus() : GSLRandomEngine() + GSLRngTaus::GSLRngTaus() : GSLRandomEngine() { SetType(new GSLRngWrapper(gsl_rng_taus2) ); } //---------------------------------------------------- - GSLRngGFSR4::GSLRngGFSR4() : GSLRandomEngine() + GSLRngGFSR4::GSLRngGFSR4() : GSLRandomEngine() { SetType(new GSLRngWrapper(gsl_rng_gfsr4) ); } //---------------------------------------------------- - GSLRngCMRG::GSLRngCMRG() : GSLRandomEngine() + GSLRngCMRG::GSLRngCMRG() : GSLRandomEngine() { SetType(new GSLRngWrapper(gsl_rng_cmrg) ); } //---------------------------------------------------- - GSLRngMRG::GSLRngMRG() : GSLRandomEngine() + GSLRngMRG::GSLRngMRG() : GSLRandomEngine() { SetType(new GSLRngWrapper(gsl_rng_mrg) ); } //---------------------------------------------------- - GSLRngRand::GSLRngRand() : GSLRandomEngine() + GSLRngRand::GSLRngRand() : GSLRandomEngine() { SetType(new GSLRngWrapper(gsl_rng_rand) ); } //---------------------------------------------------- - GSLRngRanMar::GSLRngRanMar() : GSLRandomEngine() + GSLRngRanMar::GSLRngRanMar() : GSLRandomEngine() { SetType(new GSLRngWrapper(gsl_rng_ranmar) ); } //---------------------------------------------------- - GSLRngMinStd::GSLRngMinStd() : GSLRandomEngine() + GSLRngMinStd::GSLRngMinStd() : GSLRandomEngine() { SetType(new GSLRngWrapper(gsl_rng_minstd) ); } diff --git a/ThirdParty/RootMinimizers/src/Math/GSLRngWrapper.h b/ThirdParty/RootMinimizers/src/Math/GSLRngWrapper.h index 3cc65b1d61b9428cc5de0e8fe42b99dd628eaa12..c89baf09ce742e5e3c251117d53cd4bb414a78e6 100644 --- a/ThirdParty/RootMinimizers/src/Math/GSLRngWrapper.h +++ b/ThirdParty/RootMinimizers/src/Math/GSLRngWrapper.h @@ -14,73 +14,73 @@ #define ROOT_Math_GSLRngWrapper -namespace ROOT { +namespace ROOT { - namespace Math { + namespace Math { -/** - GSLRngWrapper class to wrap gsl_rng structure -*/ +/** + GSLRngWrapper class to wrap gsl_rng structure +*/ class GSLRngWrapper { -public: +public: - /** - Default constructor - */ - GSLRngWrapper () : + /** + Default constructor + */ + GSLRngWrapper () : fOwn(0), fRng(0), - fRngType(0) + fRngType(0) { } - /** - Constructor with type - */ - GSLRngWrapper(const gsl_rng_type * type) : + /** + Constructor with type + */ + GSLRngWrapper(const gsl_rng_type * type) : fOwn(1), fRng(0), - fRngType(type) + fRngType(type) { } - /** + /** construct from an existing gsl_rng it is managed externally - so will not be deleted at the end */ - GSLRngWrapper(const gsl_rng * r ) : + GSLRngWrapper(const gsl_rng * r ) : fOwn(0), - fRngType(0) + fRngType(0) { - fRng = const_cast<gsl_rng *>(r); + fRng = const_cast<gsl_rng *>(r); } - /** + /** Copy constructor - clone the GSL object and manage it - */ + */ GSLRngWrapper(GSLRngWrapper & r) : fOwn(1), fRngType(r.fRngType) - { + { fRng = gsl_rng_clone(r.fRng); - } + } - /** + /** Assignment operator - */ + */ GSLRngWrapper & operator = (const GSLRngWrapper & rhs) { if (this == &rhs) return *this; // time saving self-test fRngType = rhs.fRngType; - int iret = 0; - if (fRngType == rhs.fRngType) { - iret = gsl_rng_memcpy(fRng, rhs.fRng); + int iret = 0; + if (fRngType == rhs.fRngType) { + iret = gsl_rng_memcpy(fRng, rhs.fRng); if (!iret) return *this; } // otherwise create a new copy - if (fOwn) Free(); + if (fOwn) Free(); fRng = gsl_rng_clone(rhs.fRng); fOwn = true; return *this; @@ -89,52 +89,52 @@ public: /** Destructor (free the rng if not done before) */ - ~GSLRngWrapper() { + ~GSLRngWrapper() { if (fOwn) Free(); - } + } - void Allocate() { + void Allocate() { if (fRngType == 0) SetDefaultType(); - if (fRng != 0 && fOwn) Free(); + if (fRng != 0 && fOwn) Free(); fRng = gsl_rng_alloc( fRngType ); //std::cout << " allocate " << fRng << std::endl; } - void Free() { - if (!fOwn) return; // no operation if pointer is not own + void Free() { + if (!fOwn) return; // no operation if pointer is not own //std::cout << "free gslrng " << fRngType << " " << fRng << std::endl; - if (fRng != 0) gsl_rng_free(fRng); - fRng = 0; + if (fRng != 0) gsl_rng_free(fRng); + fRng = 0; } - void SetType(const gsl_rng_type * type) { - fRngType = type; + void SetType(const gsl_rng_type * type) { + fRngType = type; } - void SetDefaultType() { + void SetDefaultType() { // construct default engine - gsl_rng_env_setup(); - fRngType = gsl_rng_default; + gsl_rng_env_setup(); + fRngType = gsl_rng_default; } - void PrintState() const { + void PrintState() const { gsl_rng_print_state(fRng); } - inline gsl_rng * Rng() { return fRng; } + inline gsl_rng * Rng() { return fRng; } - inline const gsl_rng * Rng() const { return fRng; } + inline const gsl_rng * Rng() const { return fRng; } -private: +private: bool fOwn; // ownership of contained pointer - gsl_rng * fRng; - const gsl_rng_type * fRngType; + gsl_rng * fRng; + const gsl_rng_type * fRngType; }; - + } // end namespace Math diff --git a/ThirdParty/RootMinimizers/src/Math/GSLSimAnnealing.cxx b/ThirdParty/RootMinimizers/src/Math/GSLSimAnnealing.cxx index 92091ac967b4ac10e5d11fe2741823cbc6241aec..78ae368bd9e57a78c6148dcc6dcbbbec460fa6ce 100644 --- a/ThirdParty/RootMinimizers/src/Math/GSLSimAnnealing.cxx +++ b/ThirdParty/RootMinimizers/src/Math/GSLSimAnnealing.cxx @@ -19,215 +19,215 @@ #include "GSLRngWrapper.h" -#include <cassert> -#include <iostream> -#include <cmath> +#include <cassert> +#include <iostream> +#include <cmath> #include <vector> -namespace ROOT { +namespace ROOT { - namespace Math { + namespace Math { // implementation of GSLSimAnFunc -GSLSimAnFunc::GSLSimAnFunc(const ROOT::Math::IMultiGenFunction & func, const double * x) : - fX( std::vector<double>(x, x + func.NDim() ) ), - fScale( std::vector<double>(func.NDim() )), +GSLSimAnFunc::GSLSimAnFunc(const ROOT::Math::IMultiGenFunction & func, const double * x) : + fX( std::vector<double>(x, x + func.NDim() ) ), + fScale( std::vector<double>(func.NDim() )), fFunc(&func) { // set scale factors to 1 fScale.assign(fScale.size(), 1.); } -GSLSimAnFunc::GSLSimAnFunc(const ROOT::Math::IMultiGenFunction & func, const double * x, const double * scale) : - fX( std::vector<double>(x, x + func.NDim() ) ), - fScale( std::vector<double>(scale, scale + func.NDim() ) ), - fFunc(&func) +GSLSimAnFunc::GSLSimAnFunc(const ROOT::Math::IMultiGenFunction & func, const double * x, const double * scale) : + fX( std::vector<double>(x, x + func.NDim() ) ), + fScale( std::vector<double>(scale, scale + func.NDim() ) ), + fFunc(&func) {} - -double GSLSimAnFunc::Energy() const { + +double GSLSimAnFunc::Energy() const { // evaluate the energy return (*fFunc)(&fX.front() ); } -void GSLSimAnFunc::Step(const GSLRandomEngine & random, double maxstep) { +void GSLSimAnFunc::Step(const GSLRandomEngine & random, double maxstep) { // x -> x + Random[-step,step] for each coordinate unsigned int ndim = NDim(); - for (unsigned int i = 0; i < ndim; ++i) { - double urndm = random(); + for (unsigned int i = 0; i < ndim; ++i) { + double urndm = random(); double sstep = maxstep * fScale[i]; - fX[i] += 2 * sstep * urndm - sstep; + fX[i] += 2 * sstep * urndm - sstep; } } -double GSLSimAnFunc::Distance(const GSLSimAnFunc & f) const { +double GSLSimAnFunc::Distance(const GSLSimAnFunc & f) const { // calculate the distance with respect onother configuration const std::vector<double> & x = fX; const std::vector<double> & y = f.X(); unsigned int n = x.size(); assert (n == y.size()); - if (n > 1) { - double d2 = 0; - for (unsigned int i = 0; i < n; ++i) - d2 += ( x[i] - y[i] ) * ( x[i] - y[i] ); - return std::sqrt(d2); + if (n > 1) { + double d2 = 0; + for (unsigned int i = 0; i < n; ++i) + d2 += ( x[i] - y[i] ) * ( x[i] - y[i] ); + return std::sqrt(d2); } - else + else // avoid doing a sqrt for 1 dim return std::abs( x[0] - y[0] ); -} +} -void GSLSimAnFunc::Print() { - // print the position x in standard ostream +void GSLSimAnFunc::Print() { + // print the position x in standard std::ostream // GSL prints also niter- ntrials - temperature and then the energy and energy min value (from 1.10) - std::cout << "\tx = ( "; - unsigned n = NDim(); - for (unsigned int i = 0; i < n-1; ++i) { - std::cout << fX[i] << " , "; + std::cout << "\tx = ( "; + unsigned n = NDim(); + for (unsigned int i = 0; i < n-1; ++i) { + std::cout << fX[i] << " , "; } std::cout << fX.back() << " )\t"; - // energy us printed by GSL (and also end-line) - std::cout << "E / E_best = "; // GSL print then E and E best + // energy us printed by GSL (and also end-line) + std::cout << "E / E_best = "; // GSL print then E and E best } -GSLSimAnFunc & GSLSimAnFunc::FastCopy(const GSLSimAnFunc & rhs) { - // copy only the information which is changed during the process - // in this case only the x values - std::copy(rhs.fX.begin(), rhs.fX.end(), fX.begin() ); +GSLSimAnFunc & GSLSimAnFunc::FastCopy(const GSLSimAnFunc & rhs) { + // copy only the information which is changed during the process + // in this case only the x values + std::copy(rhs.fX.begin(), rhs.fX.end(), fX.begin() ); return *this; } -// definition and implementations of the static functions required by GSL +// definition and implementations of the static functions required by GSL -namespace GSLSimAn { +namespace GSLSimAn { - double E( void * xp) { - // evaluate the energy given a state xp - GSLSimAnFunc * fx = reinterpret_cast<GSLSimAnFunc *> (xp); + double E( void * xp) { + // evaluate the energy given a state xp + GSLSimAnFunc * fx = reinterpret_cast<GSLSimAnFunc *> (xp); assert (fx != 0); - return fx->Energy(); + return fx->Energy(); } - void Step( const gsl_rng * r, void * xp, double step_size) { - // change xp according to the random step - GSLSimAnFunc * fx = reinterpret_cast<GSLSimAnFunc *> (xp); - assert (fx != 0); - // create GSLRandomEngine class + void Step( const gsl_rng * r, void * xp, double step_size) { + // change xp according to the random step + GSLSimAnFunc * fx = reinterpret_cast<GSLSimAnFunc *> (xp); + assert (fx != 0); + // create GSLRandomEngine class // cast away constness (we make sure we don't delete (no call to Terminate() ) GSLRngWrapper rng(const_cast<gsl_rng *>(r)); GSLRandomEngine random(&rng); // wrapper classes random and rng must exist during call to Step() fx->Step(random, step_size); } - - double Dist( void * xp, void * yp) { + + double Dist( void * xp, void * yp) { // calculate the distance between two configuration - GSLSimAnFunc * fx = reinterpret_cast<GSLSimAnFunc *> (xp); - GSLSimAnFunc * fy = reinterpret_cast<GSLSimAnFunc *> (yp); - + GSLSimAnFunc * fx = reinterpret_cast<GSLSimAnFunc *> (xp); + GSLSimAnFunc * fy = reinterpret_cast<GSLSimAnFunc *> (yp); + assert (fx != 0); assert (fy != 0); return fx->Distance(*fy); } - void Print(void * xp) { + void Print(void * xp) { // print the position xp - // GSL prints also first niter- ntrials - temperature and then the energy - GSLSimAnFunc * fx = reinterpret_cast<GSLSimAnFunc *> (xp); + // GSL prints also first niter- ntrials - temperature and then the energy + GSLSimAnFunc * fx = reinterpret_cast<GSLSimAnFunc *> (xp); assert (fx != 0); fx->Print(); - } + } + +// static function to pass to GSL copy - create and destroy the object -// static function to pass to GSL copy - create and destroy the object - - void Copy( void * source, void * dest) { - GSLSimAnFunc * fx = reinterpret_cast<GSLSimAnFunc *> (source); + void Copy( void * source, void * dest) { + GSLSimAnFunc * fx = reinterpret_cast<GSLSimAnFunc *> (source); assert (fx != 0); - GSLSimAnFunc * gx = reinterpret_cast<GSLSimAnFunc *> (dest); + GSLSimAnFunc * gx = reinterpret_cast<GSLSimAnFunc *> (dest); assert (gx != 0); - gx->FastCopy(*fx); + gx->FastCopy(*fx); } - void * CopyCtor( void * xp) { - GSLSimAnFunc * fx = reinterpret_cast<GSLSimAnFunc *> (xp); + void * CopyCtor( void * xp) { + GSLSimAnFunc * fx = reinterpret_cast<GSLSimAnFunc *> (xp); assert (fx != 0); - return static_cast<void *> ( fx->Clone() ); + return static_cast<void *> ( fx->Clone() ); } - void Destroy( void * xp) { - GSLSimAnFunc * fx = reinterpret_cast<GSLSimAnFunc *> (xp); + void Destroy( void * xp) { + GSLSimAnFunc * fx = reinterpret_cast<GSLSimAnFunc *> (xp); assert (fx != 0); - delete fx; + delete fx; } } -// implementation of GSLSimAnnealing class +// implementation of GSLSimAnnealing class -GSLSimAnnealing::GSLSimAnnealing() +GSLSimAnnealing::GSLSimAnnealing() { // Default constructor implementation. } -// function for solving (from a Genfunction interface) +// function for solving (from a Genfunction interface) -int GSLSimAnnealing::Solve(const ROOT::Math::IMultiGenFunction & func, const double * x0, const double * scale, double * xmin, bool debug) { +int GSLSimAnnealing::Solve(const ROOT::Math::IMultiGenFunction & func, const double * x0, const double * scale, double * xmin, bool debug) { // solve the simulated annealing problem given starting point and objective function interface - + // initial conditions - GSLSimAnFunc fx(func, x0, scale); + GSLSimAnFunc fx(func, x0, scale); - int iret = Solve(fx, debug); + int iret = Solve(fx, debug); - if (iret == 0) { + if (iret == 0) { // copy value of the minimum in xmin std::copy(fx.X().begin(), fx.X().end(), xmin); } - return iret; + return iret; } -int GSLSimAnnealing::Solve(GSLSimAnFunc & fx, bool debug) { +int GSLSimAnnealing::Solve(GSLSimAnFunc & fx, bool debug) { // solve the simulated annealing problem given starting point and GSLSimAnfunc object - - gsl_rng * r = gsl_rng_alloc(gsl_rng_mt19937); + + gsl_rng * r = gsl_rng_alloc(gsl_rng_mt19937); - gsl_siman_params_t simanParams; + gsl_siman_params_t simanParams; // parameters for the simulated annealing // copy them in GSL structure simanParams.n_tries = fParams.n_tries; /* how many points to try for each step */ - simanParams.iters_fixed_T = fParams.iters_fixed_T; /* how many iterations at each temperature? */ + simanParams.iters_fixed_T = fParams.iters_fixed_T; /* how many iterations at each temperature? */ simanParams.step_size = fParams.step_size; /* max step size in the random walk */ // the following parameters are for the Boltzmann distribution */ - simanParams.k = fParams.k; - simanParams.t_initial = fParams.t_initial; + simanParams.k = fParams.k; + simanParams.t_initial = fParams.t_initial; simanParams.mu_t = fParams.mu; simanParams.t_min = fParams.t_min; - if (debug) - gsl_siman_solve(r, &fx, &GSLSimAn::E, &GSLSimAn::Step, &GSLSimAn::Dist, + if (debug) + gsl_siman_solve(r, &fx, &GSLSimAn::E, &GSLSimAn::Step, &GSLSimAn::Dist, &GSLSimAn::Print, &GSLSimAn::Copy, &GSLSimAn::CopyCtor , &GSLSimAn::Destroy, 0, simanParams ); - else - gsl_siman_solve(r, &fx, &GSLSimAn::E, &GSLSimAn::Step, &GSLSimAn::Dist, + else + gsl_siman_solve(r, &fx, &GSLSimAn::E, &GSLSimAn::Step, &GSLSimAn::Dist, 0, &GSLSimAn::Copy, &GSLSimAn::CopyCtor , &GSLSimAn::Destroy, 0, simanParams ); - return 0; + return 0; } diff --git a/ThirdParty/RootMinimizers/src/Math/GenAlgoOptions.cxx b/ThirdParty/RootMinimizers/src/Math/GenAlgoOptions.cxx index 339e511e715dda205c3b725e47561e18cc7162de..841d1df7536e5090e210ee9115898751f4139fd8 100644 --- a/ThirdParty/RootMinimizers/src/Math/GenAlgoOptions.cxx +++ b/ThirdParty/RootMinimizers/src/Math/GenAlgoOptions.cxx @@ -1,4 +1,4 @@ -// @(#)root/mathcore:$Id$ +// @(#)root/mathcore:$Id$ // Author: L. Moneta Nov 2010 /********************************************************************** * * @@ -8,7 +8,7 @@ **********************************************************************/ // implementation file for static methods of GenAlgoOptions -// this file contains also the pointer to the static map<algorithm name, options> +// this file contains also the pointer to the static std::map<algorithm name, options> #include "Math/GenAlgoOptions.h" #include <cassert> @@ -16,48 +16,47 @@ // for toupper #include <algorithm> #include <functional> -#include <string> #include <ctype.h> // need to use c version of tolower defined here -namespace ROOT { -namespace Math { +namespace ROOT { +namespace Math { -typedef std::map<std::string, ROOT::Math::GenAlgoOptions > OptionsMap; +typedef std::map<std::string, ROOT::Math::GenAlgoOptions > OptionsMap; namespace GenAlgoOptUtil { - // map with the generic options for all ROOT::Math numerical algorithm - static OptionsMap gAlgoOptions; - + // map with the generic options for all ROOT::Math numerical algorithm + static OptionsMap gAlgoOptions; - IOptions * DoFindDefault(std::string & algoname, OptionsMap & gOpts) { - // internal function to retrieve the - // default extra options for the given algorithm type + + IOptions * DoFindDefault(std::string & algoname, OptionsMap & gOpts) { + // internal function to retrieve the + // default extra options for the given algorithm type // return zero if not found // store always name in upper case - std::transform(algoname.begin(), algoname.end(), algoname.begin(), (int(*)(int)) toupper ); - - OptionsMap::iterator pos = gOpts.find(algoname); - if (pos != gOpts.end() ) { - return &(pos->second); + std::transform(algoname.begin(), algoname.end(), algoname.begin(), (int(*)(int)) toupper ); + + OptionsMap::iterator pos = gOpts.find(algoname); + if (pos != gOpts.end() ) { + return &(pos->second); } - return 0; + return 0; } } - - IOptions * GenAlgoOptions::FindDefault(const char * algo) { + + IOptions * GenAlgoOptions::FindDefault(const char * algo) { // find default options - return 0 if not found std::string algoname(algo); - OptionsMap & gOpts = GenAlgoOptUtil::gAlgoOptions; - return GenAlgoOptUtil::DoFindDefault(algoname, gOpts); + OptionsMap & gOpts = GenAlgoOptUtil::gAlgoOptions; + return GenAlgoOptUtil::DoFindDefault(algoname, gOpts); } - IOptions & GenAlgoOptions::Default(const char * algo) { - // create default extra options for the given algorithm type + IOptions & GenAlgoOptions::Default(const char * algo) { + // create default extra options for the given algorithm type std::string algoname(algo); - OptionsMap & gOpts = GenAlgoOptUtil::gAlgoOptions; - IOptions * opt = GenAlgoOptUtil::DoFindDefault(algoname, gOpts); - if (opt == 0) { + OptionsMap & gOpts = GenAlgoOptUtil::gAlgoOptions; + IOptions * opt = GenAlgoOptUtil::DoFindDefault(algoname, gOpts); + if (opt == 0) { // create new extra options for the given type std::pair<OptionsMap::iterator,bool> ret = gOpts.insert( OptionsMap::value_type(algoname, ROOT::Math::GenAlgoOptions()) ); assert(ret.second); @@ -66,12 +65,12 @@ namespace GenAlgoOptUtil { return *opt; } - void GenAlgoOptions::PrintAllDefault(std::ostream & os) { - const OptionsMap & gOpts = GenAlgoOptUtil::gAlgoOptions; - for ( OptionsMap::const_iterator pos = gOpts.begin(); - pos != gOpts.end(); ++pos) { - os << std::string("Default specific options for algorithm ") << pos->first << std::string(" : ") << std::endl; - (pos->second).Print(os); + void GenAlgoOptions::PrintAllDefault(std::ostream & os) { + const OptionsMap & gOpts = GenAlgoOptUtil::gAlgoOptions; + for ( OptionsMap::const_iterator pos = gOpts.begin(); + pos != gOpts.end(); ++pos) { + os << "Default specific options for algorithm " << pos->first << " : " << std::endl; + (pos->second).Print(os); } } diff --git a/ThirdParty/RootMinimizers/src/Math/GeneticMinimizer.cxx b/ThirdParty/RootMinimizers/src/Math/GeneticMinimizer.cxx index b454194f9ddb596be685409fbe77c28f0a70e753..c513c199540df1edd08f5de4f441bc9c1a9d60fb 100644 --- a/ThirdParty/RootMinimizers/src/Math/GeneticMinimizer.cxx +++ b/ThirdParty/RootMinimizers/src/Math/GeneticMinimizer.cxx @@ -12,64 +12,64 @@ namespace ROOT { namespace Math { - + // wrapper class for TMVA interface to evaluate objective function class MultiGenFunctionFitness : public TMVA::IFitterTarget { private: unsigned int fNCalls; - unsigned int fNFree; + unsigned int fNFree; const ROOT::Math::IMultiGenFunction& fFunc; - std::vector<int> fFixedParFlag; - mutable std::vector<double> fValues; + std::vector<int> fFixedParFlag; + mutable std::vector<double> fValues; public: - MultiGenFunctionFitness(const ROOT::Math::IMultiGenFunction& function) : fNCalls(0), + MultiGenFunctionFitness(const ROOT::Math::IMultiGenFunction& function) : fNCalls(0), fFunc(function) { fNFree = fFunc.NDim(); } unsigned int NCalls() const { return fNCalls; } unsigned int NDims() const { return fNFree; } - unsigned int NTotal() const { return fFunc.NDim(); } + unsigned int NTotal() const { return fFunc.NDim(); } - void FixParameter(unsigned int ipar, double value, bool fix = true) { + void FixParameter(unsigned int ipar, double value, bool fix = true) { if (fValues.size() != fFunc.NDim() ) { fValues.resize(fFunc.NDim() ); fFixedParFlag.resize(fFunc.NDim()); } - + if (ipar >= fValues.size() ) return; - // first find if it has been already fixed + // first find if it has been already fixed fFixedParFlag[ipar] = fix; fValues[ipar] = value; // count number of fixed params for (unsigned int i = 0; i < fFixedParFlag.size(); ++i) if (!fFixedParFlag[i] ) fNFree++; - + } - + // transfrom from internal parameters (not fixed to external vector which include the fixed ones) - const std::vector<double> & Transform( const std::vector<double> & factors) const { - unsigned int n = fValues.size(); - if (n == 0 || fNFree == n ) + const std::vector<double> & Transform( const std::vector<double> & factors) const { + unsigned int n = fValues.size(); + if (n == 0 || fNFree == n ) return factors; - // in case of fixed parameters - for (unsigned int i = 0, j = 0; i < n ; ++i) { + // in case of fixed parameters + for (unsigned int i = 0, j = 0; i < n ; ++i) { if (!fFixedParFlag[i] ) { assert (j < fNFree); fValues[i] = factors[j]; j++; - } + } } return fValues; } Double_t Evaluate(const std::vector<double> & factors ) const { - const std::vector<double> & x = Transform( factors); + const std::vector<double> & x = Transform( factors); return fFunc(&x[0]); } @@ -79,40 +79,40 @@ public: } }; -GeneticMinimizerParameters::GeneticMinimizerParameters() -{ +GeneticMinimizerParameters::GeneticMinimizerParameters() +{ // constructor of parameters with default values (use 100 is max iterations is not defined) int defmaxiter = ROOT::Math::MinimizerOptions::DefaultMaxIterations(); - fNsteps = (defmaxiter > 0) ? defmaxiter : 100; + fNsteps = (defmaxiter > 0) ? defmaxiter : 100; fPopSize =300; fCycles = 3; fSC_steps =10; fSC_rate =5; fSC_factor=0.95; fConvCrit =10.0 * ROOT::Math::MinimizerOptions::DefaultTolerance(); // default is 0.001 - if (fConvCrit <=0 ) fConvCrit = 0.001; + if (fConvCrit <=0 ) fConvCrit = 0.001; fSeed=0; // random seed } -// genetic minimizer class +// genetic minimizer class -GeneticMinimizer::GeneticMinimizer(int ): - fFitness(0), +GeneticMinimizer::GeneticMinimizer(int ): + fFitness(0), fMinValue(0), fParameters(GeneticMinimizerParameters() ) { // check with default minimizer options ROOT::Math::IOptions * geneticOpt = ROOT::Math::MinimizerOptions::FindDefault("Genetic"); - if (geneticOpt) { + if (geneticOpt) { ROOT::Math::MinimizerOptions opt; // create using default options opt.SetExtraOptions(*geneticOpt); this->SetOptions(opt); - } + } - // set the parameters - SetTolerance(0.1 * fParameters.fConvCrit); - SetMaxIterations( fParameters.fNsteps); + // set the parameters + SetTolerance(0.1 * fParameters.fConvCrit); + SetMaxIterations( fParameters.fNsteps); } GeneticMinimizer::~GeneticMinimizer() @@ -124,7 +124,7 @@ GeneticMinimizer::~GeneticMinimizer() } } -void GeneticMinimizer::Clear() +void GeneticMinimizer::Clear() { fRanges.clear(); fResult.clear(); @@ -135,23 +135,23 @@ void GeneticMinimizer::Clear() } } -void GeneticMinimizer::SetFunction(const ROOT::Math::IMultiGenFunction & func) +void GeneticMinimizer::SetFunction(const ROOT::Math::IMultiGenFunction & func) { Clear(); fFitness = new MultiGenFunctionFitness(func); fResult = std::vector<double>(func.NDim() ); assert(fResult.size() == NDim() ); -} +} -bool GeneticMinimizer::SetLimitedVariable(unsigned int , const std::string & , double , double , double lower , double upper ) -{ +bool GeneticMinimizer::SetLimitedVariable(unsigned int , const std::string & , double , double , double lower , double upper ) +{ fRanges.push_back( new TMVA::Interval(lower,upper) ); return true; } -bool GeneticMinimizer::SetVariable(unsigned int, const std::string& name, double value, double step) +bool GeneticMinimizer::SetVariable(unsigned int, const std::string& name, double value, double step) { //It does nothing! As there is no variable if it has no limits! double lower = value - (50 * step); @@ -159,12 +159,12 @@ bool GeneticMinimizer::SetVariable(unsigned int, const std::string& name, double Info("GeneticMinimizer::SetVariable", "Variables should be limited - set automatic range to 50 times step size for %s : [%f, %f]", name.c_str(),lower,upper); fRanges.push_back( new TMVA::Interval(lower, upper ) ); - + return true; } bool GeneticMinimizer::SetFixedVariable(unsigned int par, const std::string& name, double value) { - // set a fixed variable + // set a fixed variable if (!fFitness) { Error("GeneticMinimizer::SetFixedVariable", "Function has not been set - cannot set fixed variables %s",name.c_str()); return false; @@ -172,28 +172,28 @@ bool GeneticMinimizer::SetFixedVariable(unsigned int par, const std::string& nam static_cast<MultiGenFunctionFitness*>(fFitness)->FixParameter(par, value); return true; -} +} void GeneticMinimizer::SetParameters(const GeneticMinimizerParameters & params ) { - fParameters = params; + fParameters = params; // set also the one defined in Minimizer SetTolerance( 0.1 * fParameters.fConvCrit); SetMaxIterations( fParameters.fNsteps ); } -ROOT::Math::MinimizerOptions GeneticMinimizer::Options() const { - ROOT::Math::MinimizerOptions opt; +ROOT::Math::MinimizerOptions GeneticMinimizer::Options() const { + ROOT::Math::MinimizerOptions opt; GetGeneticOptions(opt); - return opt; + return opt; } -void GeneticMinimizer::GetGeneticOptions(ROOT::Math::MinimizerOptions & opt) const { +void GeneticMinimizer::GetGeneticOptions(ROOT::Math::MinimizerOptions & opt) const { // get the genetic options of the class and return them in the MinimizerOptions class opt.SetTolerance(fParameters.fConvCrit/10); // use a factor of 10 to have default as Minuit - opt.SetPrintLevel(PrintLevel() ); - opt.SetMaxIterations(fParameters.fNsteps); + opt.SetPrintLevel(PrintLevel() ); + opt.SetMaxIterations(fParameters.fNsteps); // use fixed or dammy value for the other options opt.SetMinimizerType("Genetic"); opt.SetMaxFunctionCalls(0); @@ -202,7 +202,7 @@ void GeneticMinimizer::GetGeneticOptions(ROOT::Math::MinimizerOptions & opt) co opt.SetPrecision(0); opt.SetMinimizerAlgorithm(""); - ROOT::Math::GenAlgoOptions geneticOpt; + ROOT::Math::GenAlgoOptions geneticOpt; geneticOpt.SetValue("PopSize",fParameters.fPopSize); geneticOpt.SetValue("Steps",fParameters.fNsteps); geneticOpt.SetValue("Cycles",fParameters.fCycles); @@ -212,10 +212,10 @@ void GeneticMinimizer::GetGeneticOptions(ROOT::Math::MinimizerOptions & opt) co geneticOpt.SetValue("ConvCrit",fParameters.fConvCrit); geneticOpt.SetValue("RandomSeed",fParameters.fSeed); - opt.SetExtraOptions(geneticOpt); + opt.SetExtraOptions(geneticOpt); } -void GeneticMinimizer::SetOptions(const ROOT::Math::MinimizerOptions & opt) +void GeneticMinimizer::SetOptions(const ROOT::Math::MinimizerOptions & opt) { SetTolerance(opt.Tolerance() ); SetPrintLevel(opt.PrintLevel() ); @@ -224,11 +224,11 @@ void GeneticMinimizer::SetOptions(const ROOT::Math::MinimizerOptions & opt) fParameters.fConvCrit = 10.*opt.Tolerance(); // use a factor of 10 to have default as Minuit - // set genetic parameter from minimizer options - const ROOT::Math::IOptions * geneticOpt = opt.ExtraOptions(); - if (!geneticOpt) { - Warning("GeneticMinimizer::SetOptions", "No specific genetic minimizer options have been set"); - return; + // set genetic parameter from minimizer options + const ROOT::Math::IOptions * geneticOpt = opt.ExtraOptions(); + if (!geneticOpt) { + Warning("GeneticMinimizer::SetOptions", "No specific genetic minimizer options have been set"); + return; } // if options are not existing values will not be set @@ -244,81 +244,81 @@ void GeneticMinimizer::SetOptions(const ROOT::Math::MinimizerOptions & opt) // use same of options in base class int maxiter = opt.MaxIterations(); if (maxiter > 0 && fParameters.fNsteps > 0 && maxiter != fParameters.fNsteps ) { - Warning("GeneticMinimizer::SetOptions", "max iterations value given different than than Steps - set equal to Steps %d",fParameters.fNsteps); + Warning("GeneticMinimizer::SetOptions", "max iterations value given different than than Steps - set equal to Steps %d",fParameters.fNsteps); } - if (fParameters.fNsteps > 0) SetMaxIterations(fParameters.fNsteps); + if (fParameters.fNsteps > 0) SetMaxIterations(fParameters.fNsteps); } -bool GeneticMinimizer::Minimize() +bool GeneticMinimizer::Minimize() { if (!fFitness) { - Error("GeneticMinimizer::Minimize","Fitness function has not been set"); - return false; + Error("GeneticMinimizer::Minimize","Fitness function has not been set"); + return false; } - // sync parameters - if (MaxIterations() > 0) fParameters.fNsteps = MaxIterations(); + // sync parameters + if (MaxIterations() > 0) fParameters.fNsteps = MaxIterations(); if (Tolerance() > 0) fParameters.fConvCrit = 10* Tolerance(); TMVA::GeneticAlgorithm mg( *fFitness, fParameters.fPopSize, fRanges, fParameters.fSeed ); - if (PrintLevel() > 0) { - std::cout << "GeneticMinimizer::Minimize - Start iterating - max iterations = " << MaxIterations() + if (PrintLevel() > 0) { + std::cout << "GeneticMinimizer::Minimize - Start iterating - max iterations = " << MaxIterations() << " conv criteria (tolerance) = " << fParameters.fConvCrit << std::endl; } - + fStatus = 0; - unsigned int niter = 0; + unsigned int niter = 0; do { mg.Init(); - + mg.CalculateFitness(); - + // Just for debugging options //mg.GetGeneticPopulation().Print(0); - + mg.GetGeneticPopulation().TrimPopulation(); - + mg.SpreadControl( fParameters.fSC_steps, fParameters.fSC_rate, fParameters.fSC_factor ); - if (PrintLevel() > 2) { + if (PrintLevel() > 2) { std::cout << "New Iteration " << niter << " with parameter values :" << std::endl; TMVA::GeneticGenes* genes = mg.GetGeneticPopulation().GetGenes( 0 ); - if (genes) { + if (genes) { std::vector<Double_t> gvec; - gvec = genes->GetFactors(); + gvec = genes->GetFactors(); for (unsigned int i = 0; i < gvec.size(); ++i) { std::cout << gvec[i] << " "; } std::cout << std::endl; std::cout << "\tFitness function value = " << static_cast<MultiGenFunctionFitness*>(fFitness)->Evaluate(gvec) << std::endl; - } - } + } + } niter++; - if ( niter > MaxIterations() && MaxIterations() > 0) { - if (PrintLevel() > 0) { + if ( niter > MaxIterations() && MaxIterations() > 0) { + if (PrintLevel() > 0) { Info("GeneticMinimizer::Minimize","Max number of iterations %d reached - stop iterating",MaxIterations()); } - fStatus = 1; + fStatus = 1; break; } - + } while (!mg.HasConverged( fParameters.fNsteps, fParameters.fConvCrit )); // converged if: fitness-improvement < CONVCRIT within the last CONVSTEPS loops - + TMVA::GeneticGenes* genes = mg.GetGeneticPopulation().GetGenes( 0 ); std::vector<Double_t> gvec; gvec = genes->GetFactors(); // transform correctly gvec on fresult in case there are fixed parameters - const std::vector<double> & transVec = static_cast<MultiGenFunctionFitness*>(fFitness)->Transform(gvec); + const std::vector<double> & transVec = static_cast<MultiGenFunctionFitness*>(fFitness)->Transform(gvec); std::copy(transVec.begin(), transVec.end(), fResult.begin() ); fMinValue = static_cast<MultiGenFunctionFitness*>(fFitness)->Evaluate(gvec); - if (PrintLevel() > 0) { + if (PrintLevel() > 0) { if (PrintLevel() > 2) std::cout << std::endl; std::cout << "Finished Iteration (niter = " << niter << " with fitness function value = " << MinValue() << std::endl; for (unsigned int i = 0; i < fResult.size(); ++i) { @@ -327,18 +327,18 @@ bool GeneticMinimizer::Minimize() } return true; -} +} -double GeneticMinimizer::MinValue() const +double GeneticMinimizer::MinValue() const { - return (fFitness) ? fMinValue : 0; -} + return (fFitness) ? fMinValue : 0; +} -const double * GeneticMinimizer::X() const { - return (fFitness) ? &fResult[0] : 0; -} +const double * GeneticMinimizer::X() const { + return (fFitness) ? &fResult[0] : 0; +} -unsigned int GeneticMinimizer::NCalls() const +unsigned int GeneticMinimizer::NCalls() const { if ( fFitness ) return static_cast<MultiGenFunctionFitness*>(fFitness)->NCalls(); @@ -346,24 +346,24 @@ unsigned int GeneticMinimizer::NCalls() const return 0; } -unsigned int GeneticMinimizer::NDim() const +unsigned int GeneticMinimizer::NDim() const { if ( fFitness ) return static_cast<MultiGenFunctionFitness*>(fFitness)->NTotal(); else return 0; -} -unsigned int GeneticMinimizer::NFree() const +} +unsigned int GeneticMinimizer::NFree() const { if ( fFitness ) return static_cast<MultiGenFunctionFitness*>(fFitness)->NDims(); else return 0; -} +} // Functions we don't need... -const double * GeneticMinimizer::MinGradient() const { return 0; } -bool GeneticMinimizer::ProvidesError() const { return false; } +const double * GeneticMinimizer::MinGradient() const { return 0; } +bool GeneticMinimizer::ProvidesError() const { return false; } const double * GeneticMinimizer::Errors() const { return 0; } double GeneticMinimizer::Edm() const { return 0; } double GeneticMinimizer::CovMatrix(unsigned int, unsigned int) const { return 0; } diff --git a/ThirdParty/RootMinimizers/src/Math/MinimTransformFunction.cxx b/ThirdParty/RootMinimizers/src/Math/MinimTransformFunction.cxx index 063836ca995f352840c5b0a580436d0fa0964213..943d155824ed21b85c75682a69203d635f264c11 100644 --- a/ThirdParty/RootMinimizers/src/Math/MinimTransformFunction.cxx +++ b/ThirdParty/RootMinimizers/src/Math/MinimTransformFunction.cxx @@ -16,40 +16,40 @@ #include <cmath> #include <cassert> -namespace ROOT { +namespace ROOT { - namespace Math { + namespace Math { -MinimTransformFunction::MinimTransformFunction ( const IMultiGradFunction * f, const std::vector<EMinimVariableType> & types, - const std::vector<double> & values, - const std::map<unsigned int, std::pair<double, double> > & bounds) : +MinimTransformFunction::MinimTransformFunction ( const IMultiGradFunction * f, const std::vector<EMinimVariableType> & types, + const std::vector<double> & values, + const std::map<unsigned int, std::pair<double, double> > & bounds) : fX( values ), fFunc(f) { - // constructor of the class from a pointer to the function (which is managed) + // constructor of the class from a pointer to the function (which is managed) // vector specifying the variable types (free, bounded or fixed, defined in enum EMinimVariableTypes ) // variable values (used for the fixed ones) and a map with the bounds (for the bounded variables) unsigned int ntot = NTot(); // NTot is fFunc->NDim() - assert ( types.size() == ntot ); - fVariables.reserve(ntot); - fIndex.reserve(ntot); - for (unsigned int i = 0; i < ntot; ++i ) { - if (types[i] == kFix ) - fVariables.push_back( MinimTransformVariable( values[i]) ); - else { - fIndex.push_back(i); + assert ( types.size() == ntot ); + fVariables.reserve(ntot); + fIndex.reserve(ntot); + for (unsigned int i = 0; i < ntot; ++i ) { + if (types[i] == kFix ) + fVariables.push_back( MinimTransformVariable( values[i]) ); + else { + fIndex.push_back(i); if ( types[i] == kDefault) fVariables.push_back( MinimTransformVariable() ); - else { - std::map<unsigned int, std::pair<double,double> >::const_iterator itr = bounds.find(i); + else { + std::map<unsigned int, std::pair<double,double> >::const_iterator itr = bounds.find(i); assert ( itr != bounds.end() ); - double low = itr->second.first; + double low = itr->second.first; double up = itr->second.second; - if (types[i] == kBounds ) + if (types[i] == kBounds ) fVariables.push_back( MinimTransformVariable( low, up, new SinVariableTransformation())); - else if (types[i] == kLowBound) + else if (types[i] == kLowBound) fVariables.push_back( MinimTransformVariable( low, new SqrtLowVariableTransformation())); else if (types[i] == kUpBound) fVariables.push_back( MinimTransformVariable( up, new SqrtUpVariableTransformation())); @@ -59,98 +59,98 @@ MinimTransformFunction::MinimTransformFunction ( const IMultiGradFunction * f, c } -void MinimTransformFunction::Transformation( const double * x, double * xext) const { - // transform from internal to external +void MinimTransformFunction::Transformation( const double * x, double * xext) const { + // transform from internal to external - unsigned int nfree = fIndex.size(); + unsigned int nfree = fIndex.size(); -// std::cout << "Transform: internal "; -// for (int i = 0; i < nfree; ++i) std::cout << x[i] << " "; +// std::cout << "Transform: internal "; +// for (int i = 0; i < nfree; ++i) std::cout << x[i] << " "; // std::cout << "\t\t"; - for (unsigned int i = 0; i < nfree; ++i ) { - unsigned int extIndex = fIndex[i]; - const MinimTransformVariable & var = fVariables[ extIndex ]; - if (var.IsLimited() ) - xext[ extIndex ] = var.InternalToExternal( x[i] ); + for (unsigned int i = 0; i < nfree; ++i ) { + unsigned int extIndex = fIndex[i]; + const MinimTransformVariable & var = fVariables[ extIndex ]; + if (var.IsLimited() ) + xext[ extIndex ] = var.InternalToExternal( x[i] ); else - xext[ extIndex ] = x[i]; + xext[ extIndex ] = x[i]; } -// std::cout << "Transform: external "; -// for (int i = 0; i < fX.size(); ++i) std::cout << fX[i] << " "; +// std::cout << "Transform: external "; +// for (int i = 0; i < fX.size(); ++i) std::cout << fX[i] << " "; // std::cout << "\n"; } -void MinimTransformFunction::InvTransformation(const double * xExt, double * xInt) const { +void MinimTransformFunction::InvTransformation(const double * xExt, double * xInt) const { // inverse function transformation (external -> internal) - for (unsigned int i = 0; i < NDim(); ++i ) { - unsigned int extIndex = fIndex[i]; - const MinimTransformVariable & var = fVariables[ extIndex ]; + for (unsigned int i = 0; i < NDim(); ++i ) { + unsigned int extIndex = fIndex[i]; + const MinimTransformVariable & var = fVariables[ extIndex ]; assert ( !var.IsFixed() ); - if (var.IsLimited() ) - xInt[ i ] = var.ExternalToInternal( xExt[extIndex] ); - else - xInt[ i ] = xExt[extIndex]; + if (var.IsLimited() ) + xInt[ i ] = var.ExternalToInternal( xExt[extIndex] ); + else + xInt[ i ] = xExt[extIndex]; } } -void MinimTransformFunction::InvStepTransformation(const double * x, const double * sExt, double * sInt) const { +void MinimTransformFunction::InvStepTransformation(const double * x, const double * sExt, double * sInt) const { // inverse function transformation for steps (external -> internal) - for (unsigned int i = 0; i < NDim(); ++i ) { - unsigned int extIndex = fIndex[i]; - const MinimTransformVariable & var = fVariables[ extIndex ]; + for (unsigned int i = 0; i < NDim(); ++i ) { + unsigned int extIndex = fIndex[i]; + const MinimTransformVariable & var = fVariables[ extIndex ]; assert ( !var.IsFixed() ); if (var.IsLimited() ) { - // bound variables - double x2 = x[extIndex] + sExt[extIndex]; - if (var.HasUpperBound() && x2 >= var.UpperBound() ) - x2 = x[extIndex] - sExt[extIndex]; - // transform x and x2 + // bound variables + double x2 = x[extIndex] + sExt[extIndex]; + if (var.HasUpperBound() && x2 >= var.UpperBound() ) + x2 = x[extIndex] - sExt[extIndex]; + // transform x and x2 double xint = var.ExternalToInternal ( x[extIndex] ); - double x2int = var.ExternalToInternal( x2 ); - sInt[i] = std::abs( x2int - xint); + double x2int = var.ExternalToInternal( x2 ); + sInt[i] = std::abs( x2int - xint); } - else - sInt[ i ] = sExt[extIndex]; + else + sInt[ i ] = sExt[extIndex]; } } -void MinimTransformFunction::GradientTransformation(const double * x, const double *gExt, double * gInt) const { +void MinimTransformFunction::GradientTransformation(const double * x, const double *gExt, double * gInt) const { //transform gradient vector (external -> internal) at internal point x - unsigned int nfree = fIndex.size(); - for (unsigned int i = 0; i < nfree; ++i ) { - unsigned int extIndex = fIndex[i]; + unsigned int nfree = fIndex.size(); + for (unsigned int i = 0; i < nfree; ++i ) { + unsigned int extIndex = fIndex[i]; const MinimTransformVariable & var = fVariables[ extIndex ]; assert (!var.IsFixed() ); - if (var.IsLimited() ) - gInt[i] = gExt[ extIndex ] * var.DerivativeIntToExt( x[i] ); + if (var.IsLimited() ) + gInt[i] = gExt[ extIndex ] * var.DerivativeIntToExt( x[i] ); else - gInt[i] = gExt[ extIndex ]; + gInt[i] = gExt[ extIndex ]; } } -void MinimTransformFunction::MatrixTransformation(const double * x, const double *covInt, double * covExt) const { +void MinimTransformFunction::MatrixTransformation(const double * x, const double *covInt, double * covExt) const { //transform covariance matrix (internal -> external) at internal point x // use row storages for matrices m(i,j) = rep[ i * dim + j] - // ignore fixed points - unsigned int nfree = fIndex.size(); - unsigned int ntot = NTot(); - for (unsigned int i = 0; i < nfree; ++i ) { - unsigned int iext = fIndex[i]; + // ignore fixed points + unsigned int nfree = fIndex.size(); + unsigned int ntot = NTot(); + for (unsigned int i = 0; i < nfree; ++i ) { + unsigned int iext = fIndex[i]; const MinimTransformVariable & ivar = fVariables[ iext ]; - assert (!ivar.IsFixed()); - double ddi = ( ivar.IsLimited() ) ? ivar.DerivativeIntToExt( x[i] ) : 1.0; - // loop on j variables for not fixed i variables (forget that matrix is symmetric) - could be optimized - for (unsigned int j = 0; j < nfree; ++j ) { - unsigned int jext = fIndex[j]; + assert (!ivar.IsFixed()); + double ddi = ( ivar.IsLimited() ) ? ivar.DerivativeIntToExt( x[i] ) : 1.0; + // loop on j variables for not fixed i variables (forget that matrix is symmetric) - could be optimized + for (unsigned int j = 0; j < nfree; ++j ) { + unsigned int jext = fIndex[j]; const MinimTransformVariable & jvar = fVariables[ jext ]; - double ddj = ( jvar.IsLimited() ) ? jvar.DerivativeIntToExt( x[j] ) : 1.0; + double ddj = ( jvar.IsLimited() ) ? jvar.DerivativeIntToExt( x[j] ) : 1.0; assert (!jvar.IsFixed() ); covExt[ iext * ntot + jext] = ddi * ddj * covInt[ i * nfree + j]; - } + } } } diff --git a/ThirdParty/RootMinimizers/src/Math/MinimizerVariableTransformation.cxx b/ThirdParty/RootMinimizers/src/Math/MinimizerVariableTransformation.cxx index c3859fbe6e6f981bf1ff0ca997fc944b407219c3..5f0f49aa914c0e96f9cbe67c9c2a1e219cb6ff16 100644 --- a/ThirdParty/RootMinimizers/src/Math/MinimizerVariableTransformation.cxx +++ b/ThirdParty/RootMinimizers/src/Math/MinimizerVariableTransformation.cxx @@ -1,17 +1,17 @@ // @(#)root/mathmore:$Id$ // Author: L. Moneta 2009 -// Implementation file for all the MinimizerVariableTransormation's -// (implementations taken from minuit2 classes) +// Implementation file for all the MinimizerVariableTransormation's +// (implementations taken from minuit2 classes) #include "Math/MinimizerVariableTransformation.h" #include <cmath> #include <limits> -namespace ROOT { +namespace ROOT { - namespace Math { + namespace Math { // implementations for the class SinVariableTransformation @@ -22,13 +22,13 @@ double SinVariableTransformation::Int2ext(double value, double lower, double upp double SinVariableTransformation::Ext2int(double value, double lower, double upper) const { // transformation from external (limited by lower/upper ) to internal (unlimited) values given the lower/upper limits - + double piby2 = 2.*std::atan(1.); - static const double eps = std::numeric_limits<double>::epsilon(); + static const double eps = std::numeric_limits<double>::epsilon(); double distnn = 8.*std::sqrt(eps); double vlimhi = piby2 - distnn; double vlimlo = -piby2 + distnn; - + double yy = 2.*(value - lower)/(upper - lower) - 1.; double yy2 = yy*yy; if(yy2 > (1. - 8 * eps) ) { @@ -41,66 +41,66 @@ double SinVariableTransformation::Ext2int(double value, double lower, double upp // std::cout<<"SinVariableTransformation warning: is at its upper allowed limit."<<std::endl; return vlimhi; } - + } else { - return std::asin(yy); + return std::asin(yy); } } double SinVariableTransformation::DInt2Ext(double value, double lower, double upper) const { - // return the derivative of the internal to external transformation (Int2Ext) : d Int2Ext / d Int + // return the derivative of the internal to external transformation (Int2Ext) : d Int2Ext / d Int return 0.5*((upper - lower)*std::cos(value)); -} +} -// sqrt up +// sqrt up // implementations for the class SqrtUpVariableTransformation double SqrtLowVariableTransformation::Int2ext(double value, double lower, double) const { - /// internal to external transformation + /// internal to external transformation double val = lower - 1. + std::sqrt( value*value + 1.); - return val; + return val; } double SqrtLowVariableTransformation::Ext2int(double value, double lower, double ) const { // external to internal transformation - double yy = value - lower + 1.; - double yy2 = yy*yy; - if (yy2 < 1. ) - return 0; - else - return std::sqrt( yy2 -1); + double yy = value - lower + 1.; + double yy2 = yy*yy; + if (yy2 < 1. ) + return 0; + else + return std::sqrt( yy2 -1); } double SqrtLowVariableTransformation::DInt2Ext(double value, double, double) const { - // derivative of internal to external transofrmation : d (Int2Ext) / d Int + // derivative of internal to external transofrmation : d (Int2Ext) / d Int double val = value/( std::sqrt( value*value + 1.) ); - return val; + return val; } -// sqrt up +// sqrt up // implementations for the class SqrtUpVariableTransformation double SqrtUpVariableTransformation::Int2ext(double value, double upper, double) const { // internal to external transformation double val = upper + 1. - std::sqrt( value*value + 1.); - return val; + return val; } double SqrtUpVariableTransformation::Ext2int(double value, double upper, double ) const { - // external to internal transformation - double yy = upper - value + 1.; - double arg = yy*yy - 1; - return ( arg < 0 ) ? 0 : std::sqrt(arg); + // external to internal transformation + double yy = upper - value + 1.; + double arg = yy*yy - 1; + return ( arg < 0 ) ? 0 : std::sqrt(arg); } double SqrtUpVariableTransformation::DInt2Ext(double value, double, double) const { - // derivative of internal to external transofrmation : d Ext / d Int + // derivative of internal to external transofrmation : d Ext / d Int double val = - value/( std::sqrt( value*value + 1.) ); - return val; + return val; } diff --git a/ThirdParty/RootMinimizers/src/Math/MultiNumGradFunction.cxx b/ThirdParty/RootMinimizers/src/Math/MultiNumGradFunction.cxx index 1cecdca1069b5fc876eaddb74c7898a298e20f36..e0e665f256ff8d0a381ea03190ec187619b30d1e 100644 --- a/ThirdParty/RootMinimizers/src/Math/MultiNumGradFunction.cxx +++ b/ThirdParty/RootMinimizers/src/Math/MultiNumGradFunction.cxx @@ -34,22 +34,24 @@ #endif -namespace ROOT { +namespace ROOT { - namespace Math { + namespace Math { -double MultiNumGradFunction::fgEps = 0.001; +double MultiNumGradFunction::fgEps = 0.001; -double MultiNumGradFunction::DoDerivative (const double * x, unsigned int icoord ) const { - // calculate derivative using mathcore derivator class +double MultiNumGradFunction::DoDerivative (const double * x, unsigned int icoord ) const { + // calculate derivative using mathcore derivator class // step size can be changes using SetDerivPrecision() static double kPrecision = std::sqrt ( std::numeric_limits<double>::epsilon() ); - double x0 = x[icoord]; - double step = std::max( fgEps* std::abs(x0), 8.0*kPrecision*(std::abs(x0) + kPrecision) ); - return ROOT::Math::Derivator::Eval(*fFunc, x, icoord, step); -} + double x0 = std::abs(x[icoord]); + //double step = (x0 > 0) ? kPrecision * x0 : kPrecision; + // this seems to work better than above + double step = (x0>0) ? std::max( fgEps* x0, 8.0*kPrecision*(x0 + kPrecision) ) : kPrecision; + return ROOT::Math::Derivator::Eval(*fFunc, x, icoord, step); +} void MultiNumGradFunction::SetDerivPrecision(double eps) { fgEps = eps; } diff --git a/ThirdParty/RootMinimizers/src/Minuit2/AnalyticalGradientCalculator.cxx b/ThirdParty/RootMinimizers/src/Minuit2/AnalyticalGradientCalculator.cxx index 4ab5498b3289b5ba9c249d5e12120f1f5799e98d..dd0482deebdc3a5d1e45b1c503a40996ff7017a0 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/AnalyticalGradientCalculator.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/AnalyticalGradientCalculator.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -19,30 +19,30 @@ namespace ROOT { FunctionGradient AnalyticalGradientCalculator::operator()(const MinimumParameters& par) const { - // evaluate analytical gradient. take care of parameter transformations - + // evaluate analytical gradient. take care of parameter transformations + std::vector<double> grad = fGradCalc.Gradient(fTransformation(par.Vec())); assert(grad.size() == fTransformation.Parameters().size()); - + MnAlgebraicVector v(par.Vec().size()); for(unsigned int i = 0; i < par.Vec().size(); i++) { unsigned int ext = fTransformation.ExtOfInt(i); if(fTransformation.Parameter(ext).HasLimits()) { //double dd = (fTransformation.Parameter(ext).Upper() - fTransformation.Parameter(ext).Lower())*0.5*cos(par.Vec()(i)); - // const ParameterTransformation * pt = fTransformation.transformation(ext); - // double dd = pt->dInt2ext(par.Vec()(i), fTransformation.Parameter(ext).Lower(), fTransformation.Parameter(ext).Upper() ); + // const ParameterTransformation * pt = fTransformation.transformation(ext); + // double dd = pt->dInt2ext(par.Vec()(i), fTransformation.Parameter(ext).Lower(), fTransformation.Parameter(ext).Upper() ); double dd = fTransformation.DInt2Ext(i, par.Vec()(i)); v(i) = dd*grad[ext]; } else { v(i) = grad[ext]; } } - + return FunctionGradient(v); } FunctionGradient AnalyticalGradientCalculator::operator()(const MinimumParameters& par, const FunctionGradient&) const { - // needed from base class + // needed from base class return (*this)(par); } diff --git a/ThirdParty/RootMinimizers/src/Minuit2/BasicMinimumError.cxx b/ThirdParty/RootMinimizers/src/Minuit2/BasicMinimumError.cxx index 68c62c3e500c03282b7bd400a6a846134469e346..dd9de57fa232cffa45326d4b04bbf2ba71e8a652 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/BasicMinimumError.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/BasicMinimumError.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -10,18 +10,18 @@ #include "Minuit2/BasicMinimumError.h" #if defined(DEBUG) || defined(WARNINGMSG) -#include "Minuit2/MnPrint.h" +#include "Minuit2/MnPrint.h" #endif namespace ROOT { - + namespace Minuit2 { - - - + + + MnAlgebraicSymMatrix BasicMinimumError::Hessian() const { - // calculate Heassian: inverse of error matrix + // calculate Heassian: inverse of error matrix MnAlgebraicSymMatrix tmp(fMatrix); int ifail = Invert(tmp); if(ifail != 0) { @@ -38,5 +38,5 @@ MnAlgebraicSymMatrix BasicMinimumError::Hessian() const { } } // namespace Minuit2 - + } // namespace ROOT diff --git a/ThirdParty/RootMinimizers/src/Minuit2/CombinedMinimumBuilder.cxx b/ThirdParty/RootMinimizers/src/Minuit2/CombinedMinimumBuilder.cxx index ce8bc3fa66bbcdcc78e630e2457ab312c574eebf..6d6064aa5d7076ef7d899efa352fd580bf4b7cc2 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/CombinedMinimumBuilder.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/CombinedMinimumBuilder.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -12,7 +12,7 @@ #include "Minuit2/MnStrategy.h" #if defined(DEBUG) || defined(WARNINGMSG) -#include "Minuit2/MnPrint.h" +#include "Minuit2/MnPrint.h" #endif @@ -22,14 +22,14 @@ namespace ROOT { FunctionMinimum CombinedMinimumBuilder::Minimum(const MnFcn& fcn, const GradientCalculator& gc, const MinimumSeed& seed, const MnStrategy& strategy, unsigned int maxfcn, double edmval) const { - // find minimum using combined method - // (Migrad then if fails try Simplex and then Migrad again) - + // find minimum using combined method + // (Migrad then if fails try Simplex and then Migrad again) + FunctionMinimum min = fVMMinimizer.Builder().Minimum(fcn, gc, seed, strategy, maxfcn, edmval); - + if(!min.IsValid()) { #ifdef WARNINGMSG - MN_INFO_MSG("CombinedMinimumBuilder: migrad method fails, will try with simplex method first."); + MN_INFO_MSG("CombinedMinimumBuilder: migrad method fails, will try with simplex method first."); #endif MnStrategy str(2); FunctionMinimum min1 = fSimplexMinimizer.Builder().Minimum(fcn, gc, seed, str, maxfcn, edmval); @@ -40,7 +40,7 @@ FunctionMinimum CombinedMinimumBuilder::Minimum(const MnFcn& fcn, const Gradient return min1; } MinimumSeed seed1 = fVMMinimizer.SeedGenerator()(fcn, gc, min1.UserState(), str); - + FunctionMinimum min2 = fVMMinimizer.Builder().Minimum(fcn, gc, seed1, str, maxfcn, edmval); if(!min2.IsValid()) { #ifdef WARNINGMSG @@ -49,10 +49,10 @@ FunctionMinimum CombinedMinimumBuilder::Minimum(const MnFcn& fcn, const Gradient #endif return min1; } - + return min2; } - + return min; } diff --git a/ThirdParty/RootMinimizers/src/Minuit2/DavidonErrorUpdator.cxx b/ThirdParty/RootMinimizers/src/Minuit2/DavidonErrorUpdator.cxx index 205d460d1e93b5ef892f619b75a44dfe92f1ecb9..2d7302e36434d97847b9fc015b09b3c08369a675 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/DavidonErrorUpdator.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/DavidonErrorUpdator.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -12,10 +12,10 @@ #include "Minuit2/LaSum.h" #include "Minuit2/LaProd.h" -//#define DEBUG +//#define DEBUG #if defined(DEBUG) || defined(WARNINGMSG) -#include "Minuit2/MnPrint.h" +#include "Minuit2/MnPrint.h" #endif @@ -29,29 +29,29 @@ double inner_product(const LAVector&, const LAVector&); double similarity(const LAVector&, const LASymMatrix&); double sum_of_elements(const LASymMatrix&); -MinimumError DavidonErrorUpdator::Update(const MinimumState& s0, +MinimumError DavidonErrorUpdator::Update(const MinimumState& s0, const MinimumParameters& p1, const FunctionGradient& g1) const { // update of the covarianze matrix (Davidon formula, see Tutorial, par. 4.8 pag 26) - // in case of delgam > gvg (PHI > 1) use rank one formula + // in case of delgam > gvg (PHI > 1) use rank one formula // see par 4.10 pag 30 const MnAlgebraicSymMatrix& v0 = s0.Error().InvHessian(); MnAlgebraicVector dx = p1.Vec() - s0.Vec(); MnAlgebraicVector dg = g1.Vec() - s0.Gradient().Vec(); - + double delgam = inner_product(dx, dg); double gvg = similarity(dg, v0); #ifdef DEBUG - std::cout << "dx = " << dx << std::endl; - std::cout << "dg = " << dg << std::endl; + std::cout << "dx = " << dx << std::endl; + std::cout << "dg = " << dg << std::endl; std::cout<<"delgam= "<<delgam<<" gvg= "<<gvg<<std::endl; #endif - if (delgam == 0 ) { + if (delgam == 0 ) { #ifdef WARNINGMSG MN_INFO_MSG("DavidonErrorUpdator: delgam = 0 : cannot update - return same matrix "); #endif @@ -61,10 +61,10 @@ MinimumError DavidonErrorUpdator::Update(const MinimumState& s0, if (delgam < 0) MN_INFO_MSG("DavidonErrorUpdator: delgam < 0 : first derivatives increasing along search line"); #endif - if (gvg <= 0 ) { + if (gvg <= 0 ) { // since v0 is pos def this gvg can be only = 0 if dg = 0 - should never be here #ifdef WARNINGMSG - MN_INFO_MSG("DavidonErrorUpdator: gvg <= 0 : cannot update - return same matrix "); + MN_INFO_MSG("DavidonErrorUpdator: gvg <= 0 : cannot update - return same matrix "); #endif return s0.Error(); } @@ -81,21 +81,21 @@ MinimumError DavidonErrorUpdator::Update(const MinimumState& s0, double sum_upd = sum_of_elements(vUpd); vUpd += v0; - + double dcov = 0.5*(s0.Error().Dcovar() + sum_upd/sum_of_elements(vUpd)); - + return MinimumError(vUpd, dcov); } /* -MinimumError DavidonErrorUpdator::Update(const MinimumState& s0, +MinimumError DavidonErrorUpdator::Update(const MinimumState& s0, const MinimumParameters& p1, const FunctionGradient& g1) const { const MnAlgebraicSymMatrix& v0 = s0.Error().InvHessian(); MnAlgebraicVector dx = p1.Vec() - s0.Vec(); MnAlgebraicVector dg = g1.Vec() - s0.Gradient().Vec(); - + double delgam = inner_product(dx, dg); double gvg = similarity(dg, v0); @@ -110,7 +110,7 @@ MinimumError DavidonErrorUpdator::Update(const MinimumState& s0, // vUpd = dd - VggV; // MnAlgebraicSymMatrix vUpd = ( 1./delgam )*outer_product(dx) - ( 1./gvg )*outer_product(vg); MnAlgebraicSymMatrix vUpd = Outer_product(dx)/delgam - Outer_product(vg)/gvg; - + if(delgam > gvg) { // dx *= ( 1./delgam ); // vg *= ( 1./gvg ); @@ -121,14 +121,14 @@ MinimumError DavidonErrorUpdator::Update(const MinimumState& s0, vUpd += gvg*outer_product(dx/delgam - vg/gvg); } -// +// // MnAlgebraicSymMatrix dd = Outer_product(dx); // dd *= ( 1./delgam ); // MnAlgebraicSymMatrix VggV = Outer_product(vg); // VggV *= ( 1./gvg ); // vUpd = dd - VggV; -// -// +// +// // double phi = delgam/(delgam - gvg); // MnAlgebraicSymMatrix vUpd(v0.Nrow()); @@ -146,15 +146,15 @@ MinimumError DavidonErrorUpdator::Update(const MinimumState& s0, // vUpd = Outer_product(tmp); // vUpd *= ( 1./(delgam - gvg) ); // } -// +// -// +// // if(delgam > gvg) { // // rank-1 Update // MnAlgebraicVector tmp = dx - vg; // vUpd = Outer_product(tmp); // vUpd *= ( 1./(delgam - gvg) ); -// } else { +// } else { // // rank-2 Update // MnAlgebraicSymMatrix dd = Outer_product(dx); // dd *= ( 1./delgam ); @@ -162,16 +162,16 @@ MinimumError DavidonErrorUpdator::Update(const MinimumState& s0, // VggV *= ( 1./gvg ); // vUpd = dd - VggV; // } -// +// double sum_upd = sum_of_elements(vUpd); vUpd += v0; - + // MnAlgebraicSymMatrix V1 = v0 + vUpd; - double dcov = + double dcov = 0.5*(s0.Error().Dcovar() + sum_upd/sum_of_elements(vUpd)); - + return MinimumError(vUpd, dcov); } */ diff --git a/ThirdParty/RootMinimizers/src/Minuit2/FumiliBuilder.cxx b/ThirdParty/RootMinimizers/src/Minuit2/FumiliBuilder.cxx index 4d120c385d9a228b164c6f40f40d4875f4c46a85..73478b368f8db4555da9f0ff4d182b6bb1505a93 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/FumiliBuilder.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/FumiliBuilder.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -30,7 +30,7 @@ // //#define DEBUG 1 // #if defined(DEBUG) || defined(WARNINGMSG) -#include "Minuit2/MnPrint.h" +#include "Minuit2/MnPrint.h" //#endif @@ -45,65 +45,65 @@ namespace ROOT { double inner_product(const LAVector&, const LAVector&); FunctionMinimum FumiliBuilder::Minimum(const MnFcn& fcn, const GradientCalculator& gc, const MinimumSeed& seed, const MnStrategy& strategy, unsigned int maxfcn, double edmval) const { - // top level function to find minimum from a given initial seed + // top level function to find minimum from a given initial seed // iterate on a minimum search in case of first attempt is not successful - + edmval *= 0.0001; //edmval *= 0.1; // use small factor for Fumili - - + + #ifdef DEBUG std::cout<<"FumiliBuilder convergence when edm < "<<edmval<<std::endl; #endif - + if(seed.Parameters().Vec().size() == 0) { return FunctionMinimum(seed, fcn.Up()); } - - + + // double edm = Estimator().Estimate(seed.Gradient(), seed.Error()); double edm = seed.State().Edm(); - + FunctionMinimum min(seed, fcn.Up() ); - + if(edm < 0.) { #ifdef WARNINGMSG MN_INFO_MSG("FumiliBuilder: initial matrix not pos.def."); #endif return min; } - + std::vector<MinimumState> result; // result.reserve(1); result.reserve(8); - + result.push_back( seed.State() ); int printLevel = PrintLevel(); if (printLevel >1) { std::cout << "Fumili: start iterating until Edm is < " << edmval << std::endl; - MnPrint::PrintState(std::cout, seed.State(), "Fumili: Initial state "); + MnPrint::PrintState(std::cout, seed.State(), "Fumili: Initial state "); } if (TraceIter() ) TraceIteration(result.size()-1, result.back() ); - + // do actual iterations - - - // try first with a maxfxn = 50% of maxfcn + + + // try first with a maxfxn = 50% of maxfcn // Fumili in principle needs much less iterations int maxfcn_eff = int(0.5*maxfcn); int ipass = 0; double edmprev = 1; - - do { - - + + do { + + min = Minimum(fcn, gc, seed, result, maxfcn_eff, edmval); - // second time check for validity of function Minimum - if (ipass > 0) { + // second time check for validity of function Minimum + if (ipass > 0) { if(!min.IsValid()) { #ifdef WARNINGMSG MN_INFO_MSG("FumiliBuilder: FunctionMinimum is invalid."); @@ -111,7 +111,7 @@ FunctionMinimum FumiliBuilder::Minimum(const MnFcn& fcn, const GradientCalculato return min; } } - + // resulting edm of minimization edm = result.back().Edm(); @@ -119,9 +119,9 @@ FunctionMinimum FumiliBuilder::Minimum(const MnFcn& fcn, const GradientCalculato std::cout << "approximate edm is " << edm << std::endl; std::cout << "npass is " << ipass << std::endl; #endif - - // call always Hesse (error matrix from Fumili is never accurate since is approximate) - + + // call always Hesse (error matrix from Fumili is never accurate since is approximate) + #ifdef DEBUG std::cout << "FumiliBuilder will verify convergence and Error matrix. " << std::endl; std::cout << "dcov is = "<< min.Error().Dcovar() << std::endl; @@ -130,145 +130,145 @@ FunctionMinimum FumiliBuilder::Minimum(const MnFcn& fcn, const GradientCalculato // // recalculate the gradient using the numerical gradient calculator // Numerical2PGradientCalculator ngc(fcn, min.Seed().Trafo(), strategy); // FunctionGradient ng = ngc( min.State().Parameters() ); -// MinimumState tmp( min.State().Parameters(), min.State().Error(), ng, min.State().Edm(), min.State().NFcn() ); - +// MinimumState tmp( min.State().Parameters(), min.State().Error(), ng, min.State().Edm(), min.State().NFcn() ); + MinimumState st = MnHesse(strategy)(fcn, min.State(), min.Seed().Trafo(),maxfcn); result.push_back( st ); - if (printLevel > 1) { - MnPrint::PrintState(std::cout, st, "Fumili: After Hessian "); + if (printLevel > 1) { + MnPrint::PrintState(std::cout, st, "Fumili: After Hessian "); if (TraceIter() ) TraceIteration(result.size()-1, result.back() ); } - - // check edm + + // check edm edm = st.Edm(); #ifdef DEBUG std::cout << "edm after Hesse calculation " << edm << std::endl; std::cout << "state after Hessian calculation " << st << std::endl; #endif - - // break the loop if edm is NOT getting smaller - if (ipass > 0 && edm >= edmprev) { + + // break the loop if edm is NOT getting smaller + if (ipass > 0 && edm >= edmprev) { #ifdef WARNINGMSG MN_INFO_MSG("FumiliBuilder: Exit iterations, no improvements after Hesse "); - MN_INFO_VAL2("current edm is ", edm); + MN_INFO_VAL2("current edm is ", edm); MN_INFO_VAL2("previous value ",edmprev); #endif - break; - } - if (edm > edmval) { + break; + } + if (edm > edmval) { #ifdef DEBUG - std::cout << "FumiliBuilder: Tolerance is not sufficient - edm is " << edm << " requested " << edmval + std::cout << "FumiliBuilder: Tolerance is not sufficient - edm is " << edm << " requested " << edmval << " continue the minimization" << std::endl; #endif } - else { - // Case when edm < edmval after Heasse but min is flagged eith a bad edm: - // make then a new Function minimum since now edm is ok + else { + // Case when edm < edmval after Heasse but min is flagged eith a bad edm: + // make then a new Function minimum since now edm is ok if (min.IsAboveMaxEdm() ) { min = FunctionMinimum( min.Seed(), min.States(), min.Up() ); break; } - - } - + + } + // end loop on iterations - // ? need a maximum here (or max of function calls is enough ? ) - // continnue iteration (re-calculate function Minimum if edm IS NOT sufficient) + // ? need a maximum here (or max of function calls is enough ? ) + // continnue iteration (re-calculate function Minimum if edm IS NOT sufficient) // no need to check that hesse calculation is done (if isnot done edm is OK anyway) // count the pass to exit second time when function Minimum is invalid // increase by 20% maxfcn for doing some more tests if (ipass == 0) maxfcn_eff = maxfcn; ipass++; - edmprev = edm; - + edmprev = edm; + } while (edm > edmval ); - - - + + + // Add latest state (Hessian calculation) min.Add( result.back() ); - + return min; - + } FunctionMinimum FumiliBuilder::Minimum(const MnFcn& fcn, const GradientCalculator& gc, const MinimumSeed& seed, std::vector<MinimumState>& result, unsigned int maxfcn, double edmval) const { - // function performing the minimum searches using the FUMILI algorithm - // after the modification when I iterate on this functions, so it can be called many times, - // the seed is used here only to get precision and construct the returned FunctionMinimum object - - + // function performing the minimum searches using the FUMILI algorithm + // after the modification when I iterate on this functions, so it can be called many times, + // the seed is used here only to get precision and construct the returned FunctionMinimum object + + /* Three options were possible: - + 1) create two parallel and completely separate hierarchies, in which case - the FumiliMinimizer would NOT inherit from ModularFunctionMinimizer, + the FumiliMinimizer would NOT inherit from ModularFunctionMinimizer, FumiliBuilder would not inherit from MinimumBuilder etc - + 2) Use the inheritance (base classes of ModularFunctionMinimizer, - MinimumBuilder etc), but recreate the member functions Minimize() and - Minimum() respectively (naming them for example minimize2() and + MinimumBuilder etc), but recreate the member functions Minimize() and + Minimum() respectively (naming them for example minimize2() and minimum2()) so that they can take FumiliFCNBase as Parameter instead FCNBase (otherwise one wouldn't be able to call the Fumili-specific methods). - + 3) Cast in the daughter classes derived from ModularFunctionMinimizer, MinimumBuilder. - + The first two would mean to duplicate all the functionality already existent, which is a very bad practice and Error-prone. The third one is the most elegant and effective solution, where the only constraint is that the user - must know that he has to pass a subclass of FumiliFCNBase to the FumiliMinimizer + must know that they have to pass a subclass of FumiliFCNBase to the FumiliMinimizer and not just a subclass of FCNBase. BTW, the first two solutions would have meant to recreate also a parallel structure for MnFcn... **/ // const FumiliFCNBase* tmpfcn = dynamic_cast<const FumiliFCNBase*>(&(fcn.Fcn())); - + const MnMachinePrecision& prec = seed.Precision(); - + const MinimumState & initialState = result.back(); - + double edm = initialState.Edm(); - - + + #ifdef DEBUG - std::cout << "\n\nDEBUG FUMILI Builder \nInitial State: " - << " Parameter " << initialState.Vec() - << " Gradient " << initialState.Gradient().Vec() - << " Inv Hessian " << initialState.Error().InvHessian() - << " edm = " << initialState.Edm() - << " maxfcn = " << maxfcn - << " tolerance = " << edmval - << std::endl; + std::cout << "\n\nDEBUG FUMILI Builder \nInitial State: " + << " Parameter " << initialState.Vec() + << " Gradient " << initialState.Gradient().Vec() + << " Inv Hessian " << initialState.Error().InvHessian() + << " edm = " << initialState.Edm() + << " maxfcn = " << maxfcn + << " tolerance = " << edmval + << std::endl; #endif - - + + // iterate until edm is small enough or max # of iterations reached edm *= (1. + 3.*initialState.Error().Dcovar()); MnAlgebraicVector step(initialState.Gradient().Vec().size()); - + // initial lambda Value - double lambda = 0.001; - + double lambda = 0.001; + int printLevel = MnPrint::Level(); - do { - + do { + // const MinimumState& s0 = result.back(); MinimumState s0 = result.back(); - + step = -1.*s0.Error().InvHessian()*s0.Gradient().Vec(); - - + + #ifdef DEBUG - std::cout << "\n\n---> Iteration - " << result.size() - << "\nFval = " << s0.Fval() << " numOfCall = " << fcn.NumOfCalls() - << "\nInternal Parameter values " << s0.Vec() - << " Newton step " << step << std::endl; + std::cout << "\n\n---> Iteration - " << result.size() + << "\nFval = " << s0.Fval() << " numOfCall = " << fcn.NumOfCalls() + << "\nInternal Parameter values " << s0.Vec() + << " Newton step " << step << std::endl; #endif - + double gdel = inner_product(step, s0.Gradient().Grad()); if(gdel > 0.) { #ifdef WARNINGMSG @@ -287,68 +287,68 @@ FunctionMinimum FumiliBuilder::Minimum(const MnFcn& fcn, const GradientCalculato return FunctionMinimum(seed, result, fcn.Up()); } } - - + + // MnParabolaPoint pp = lsearch(fcn, s0.Parameters(), step, gdel, prec); - + // if(fabs(pp.Y() - s0.Fval()) < prec.Eps()) { // std::cout<<"FumiliBuilder: no improvement"<<std::endl; // break; //no improvement // } - - + + // MinimumParameters p(s0.Vec() + pp.X()*step, pp.Y()); - - // if taking a full step - + + // if taking a full step + // take a full step - + MinimumParameters p(s0.Vec() + step, fcn( s0.Vec() + step ) ); - + // check that taking the full step does not deteriorate minimum - // in that case do a line search + // in that case do a line search if ( p.Fval() >= s0.Fval() ) { - MnLineSearch lsearch; + MnLineSearch lsearch; MnParabolaPoint pp = lsearch(fcn, s0.Parameters(), step, gdel, prec); - + if(fabs(pp.Y() - s0.Fval()) < prec.Eps()) { //std::cout<<"FumiliBuilder: no improvement"<<std::endl; break; //no improvement } p = MinimumParameters(s0.Vec() + pp.X()*step, pp.Y() ); } - + #ifdef DEBUG - std::cout << "Before Gradient " << fcn.NumOfCalls() << std::endl; + std::cout << "Before Gradient " << fcn.NumOfCalls() << std::endl; #endif - + FunctionGradient g = gc(p, s0.Gradient()); - -#ifdef DEBUG - std::cout << "After Gradient " << fcn.NumOfCalls() << std::endl; + +#ifdef DEBUG + std::cout << "After Gradient " << fcn.NumOfCalls() << std::endl; #endif - - //FunctionGradient g = gc(s0.Parameters(), s0.Gradient()); - - + + //FunctionGradient g = gc(s0.Parameters(), s0.Gradient()); + + // move Error updator after Gradient since the Value is cached inside - + MinimumError e = ErrorUpdator().Update(s0, p, gc, lambda); - - + + edm = Estimator().Estimate(g, s0.Error()); - - + + #ifdef DEBUG - std::cout << "Updated new point: \n " - << " FVAL " << p.Fval() - << " Parameter " << p.Vec() - << " Gradient " << g.Vec() - << " InvHessian " << e.Matrix() - << " Hessian " << e.Hessian() + std::cout << "Updated new point: \n " + << " FVAL " << p.Fval() + << " Parameter " << p.Vec() + << " Gradient " << g.Vec() + << " InvHessian " << e.Matrix() + << " Hessian " << e.Hessian() << " edm = " << edm << std::endl << std::endl; #endif - + if(edm < 0.) { #ifdef WARNINGMSG MN_INFO_MSG("FumiliBuilder: matrix not pos.def., edm < 0"); @@ -361,44 +361,44 @@ FunctionMinimum FumiliBuilder::Minimum(const MnFcn& fcn, const GradientCalculato if (TraceIter() ) TraceIteration(result.size()-1, result.back() ); return FunctionMinimum(seed, result, fcn.Up()); } - } - - // check lambda according to step - if ( p.Fval() < s0.Fval() ) + } + + // check lambda according to step + if ( p.Fval() < s0.Fval() ) // fcn is decreasing along the step lambda *= 0.1; - else { + else { lambda *= 10; - // if close to minimum stop to avoid oscillations around minimum value + // if close to minimum stop to avoid oscillations around minimum value if ( edm < 0.1 ) break; } - + #ifdef DEBUG - std::cout << " finish iteration- " << result.size() << " lambda = " << lambda << " f1 = " << p.Fval() << " f0 = " << s0.Fval() << " num of calls = " << fcn.NumOfCalls() << " edm " << edm << std::endl; + std::cout << " finish iteration- " << result.size() << " lambda = " << lambda << " f1 = " << p.Fval() << " f0 = " << s0.Fval() << " num of calls = " << fcn.NumOfCalls() << " edm " << edm << std::endl; #endif - - result.push_back(MinimumState(p, e, g, edm, fcn.NumOfCalls())); + + result.push_back(MinimumState(p, e, g, edm, fcn.NumOfCalls())); if (TraceIter() ) TraceIteration(result.size()-1, result.back() ); if (printLevel > 1) { - MnPrint::PrintState(std::cout, result.back(), "Fumili: Iteration # ",result.size()); + MnPrint::PrintState(std::cout, result.back(), "Fumili: Iteration # ",result.size()); } - - + + edm *= (1. + 3.*e.Dcovar()); - - + + } while(edm > edmval && fcn.NumOfCalls() < maxfcn); - - - + + + if(fcn.NumOfCalls() >= maxfcn) { #ifdef WARNINGMSG MN_INFO_MSG("FumiliBuilder: call limit exceeded."); #endif return FunctionMinimum(seed, result, fcn.Up(), FunctionMinimum::MnReachedCallLimit()); } - + if(edm > edmval) { if(edm < fabs(prec.Eps2()*result.back().Fval())) { #ifdef WARNINGMSG @@ -417,14 +417,14 @@ FunctionMinimum FumiliBuilder::Minimum(const MnFcn& fcn, const GradientCalculato } } // std::cout<<"result.back().Error().Dcovar()= "<<result.back().Error().Dcovar()<<std::endl; - + #ifdef DEBUG - std::cout << "Exiting successfully FumiliBuilder \n" - << "NFCalls = " << fcn.NumOfCalls() - << "\nFval = " << result.back().Fval() - << "\nedm = " << edm << " requested = " << edmval << std::endl; + std::cout << "Exiting successfully FumiliBuilder \n" + << "NFCalls = " << fcn.NumOfCalls() + << "\nFval = " << result.back().Fval() + << "\nedm = " << edm << " requested = " << edmval << std::endl; #endif - + return FunctionMinimum(seed, result, fcn.Up()); } diff --git a/ThirdParty/RootMinimizers/src/Minuit2/FumiliErrorUpdator.cxx b/ThirdParty/RootMinimizers/src/Minuit2/FumiliErrorUpdator.cxx index d0b574eea9e1c1018bcca46a64ec1eaba3cc9fa3..277acd75d1b1a4096fde7f3ae0bce8411343bc32 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/FumiliErrorUpdator.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/FumiliErrorUpdator.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -21,7 +21,7 @@ #include <limits> #if defined(DEBUG) || defined(WARNINGMSG) -#include "Minuit2/MnPrint.h" +#include "Minuit2/MnPrint.h" #endif @@ -34,7 +34,7 @@ namespace Minuit2 { double sum_of_elements(const LASymMatrix&); -MinimumError FumiliErrorUpdator::Update(const MinimumState& s0, +MinimumError FumiliErrorUpdator::Update(const MinimumState& s0, const MinimumParameters& p1, const FunctionGradient& g1) const { // dummy methods to suppress unused variable warnings @@ -47,43 +47,43 @@ MinimumError FumiliErrorUpdator::Update(const MinimumState& s0, } -MinimumError FumiliErrorUpdator::Update(const MinimumState& s0, +MinimumError FumiliErrorUpdator::Update(const MinimumState& s0, const MinimumParameters& p1, - const GradientCalculator& gc , + const GradientCalculator& gc , double lambda) const { // calculate the error matrix using approximation of Fumili // use only first derivatives (see tutorial par. 5.1,5.2) // The Fumili Hessian is provided by the FumiliGRadientCalculator class // we apply also the Marquard lambda factor to increase weight of diagonal term // as suggester in Numerical Receipt for Marquard method - + // need to downcast to FumiliGradientCalculator - FumiliGradientCalculator * fgc = dynamic_cast< FumiliGradientCalculator *>( const_cast<GradientCalculator *>(&gc) ); - assert(fgc != 0); - - + FumiliGradientCalculator * fgc = dynamic_cast< FumiliGradientCalculator *>( const_cast<GradientCalculator *>(&gc) ); + assert(fgc != 0); + + // get Hessian from Gradient calculator - - MnAlgebraicSymMatrix h = fgc->Hessian(); - + + MnAlgebraicSymMatrix h = fgc->Hessian(); + int nvar = p1.Vec().size(); - - // apply Marquard lambda factor + + // apply Marquard lambda factor double eps = 8*std::numeric_limits<double>::min(); - for (int j = 0; j < nvar; j++) { + for (int j = 0; j < nvar; j++) { h(j,j) *= (1. + lambda); // if h(j,j) is zero what to do ? - if ( fabs( h(j,j) ) < eps ) { // should use DBL_MIN + if ( fabs( h(j,j) ) < eps ) { // should use DBL_MIN // put a cut off to avoid zero on diagonals - if ( lambda > 1) - h(j,j) = lambda*eps; - else - h(j,j) = eps; + if ( lambda > 1) + h(j,j) = lambda*eps; + else + h(j,j) = eps; } } - - - + + + int ifail = Invert(h); if(ifail != 0) { #ifdef WARNINGMSG @@ -93,19 +93,19 @@ MinimumError FumiliErrorUpdator::Update(const MinimumState& s0, h(i,i) = 1./h(i,i); } } - - + + const MnAlgebraicSymMatrix& v0 = s0.Error().InvHessian(); - + // calculate by how much did the covariance matrix changed - // (if it changed a lot since the last step, probably we + // (if it changed a lot since the last step, probably we // are not yet near the Minimum) - double dcov = 0.5*(s0.Error().Dcovar() + sum_of_elements(h-v0)/sum_of_elements(h)); - - - + double dcov = 0.5*(s0.Error().Dcovar() + sum_of_elements(h-v0)/sum_of_elements(h)); + + + return MinimumError(h, dcov); - + } diff --git a/ThirdParty/RootMinimizers/src/Minuit2/FumiliGradientCalculator.cxx b/ThirdParty/RootMinimizers/src/Minuit2/FumiliGradientCalculator.cxx index a30c0ada4d0585cea95ae0ec49a98cd6425e5bdb..1551c12e599837c8c93481e65cd6350d2b55b7c2 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/FumiliGradientCalculator.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/FumiliGradientCalculator.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -30,99 +30,99 @@ namespace ROOT { FunctionGradient FumiliGradientCalculator::operator()(const MinimumParameters& par) const { - + // Calculate gradient for Fumili using the gradient and Hessian provided by the FCN Fumili function - // applying the external to int trasformation. - + // applying the external to int trasformation. + int nvar = par.Vec().size(); std::vector<double> extParam = fTransformation( par.Vec() ); - // std::vector<double> deriv; - // deriv.reserve( nvar ); + // std::vector<double> deriv; + // deriv.reserve( nvar ); // for (int i = 0; i < nvar; ++i) { // unsigned int ext = fTransformation.ExtOfInt(i); - // if ( fTransformation.Parameter(ext).HasLimits()) + // if ( fTransformation.Parameter(ext).HasLimits()) // deriv.push_back( fTransformation.DInt2Ext( i, par.Vec()(i) ) ); - // else - // deriv.push_back(1.0); + // else + // deriv.push_back(1.0); // } - - // eval Gradient - FumiliFCNBase & fcn = const_cast<FumiliFCNBase &>(fFcn); - + + // eval Gradient + FumiliFCNBase & fcn = const_cast<FumiliFCNBase &>(fFcn); + fcn.EvaluateAll(extParam); - - + + MnAlgebraicVector v(nvar); MnAlgebraicSymMatrix h(nvar); - - - const std::vector<double> & fcn_gradient = fFcn.Gradient(); - assert( fcn_gradient.size() == extParam.size() ); - - - // for (int i = 0; i < nvar; ++i) { - // unsigned int iext = fTransformation.ExtOfInt(i); - // double ideriv = 1.0; - // if ( fTransformation.Parameter(iext).HasLimits()) + + + const std::vector<double> & fcn_gradient = fFcn.Gradient(); + assert( fcn_gradient.size() == extParam.size() ); + + + // for (int i = 0; i < nvar; ++i) { + // unsigned int iext = fTransformation.ExtOfInt(i); + // double ideriv = 1.0; + // if ( fTransformation.Parameter(iext).HasLimits()) // ideriv = fTransformation.DInt2Ext( i, par.Vec()(i) ) ; - - + + // // v(i) = fcn_gradient[iext]*deriv; // v(i) = ideriv*fcn_gradient[iext]; - - // for (int j = i; j < nvar; ++j) { + + // for (int j = i; j < nvar; ++j) { // unsigned int jext = fTransformation.ExtOfInt(j); - // double jderiv = 1.0; - // if ( fTransformation.Parameter(jext).HasLimits()) + // double jderiv = 1.0; + // if ( fTransformation.Parameter(jext).HasLimits()) // jderiv = fTransformation.DInt2Ext( j, par.Vec()(j) ) ; - - // // h(i,j) = deriv[i]*deriv[j]*fFcn.Hessian(iext,jext); - // h(i,j) = ideriv*jderiv*fFcn.Hessian(iext,jext); + + // // h(i,j) = deriv[i]*deriv[j]*fFcn.Hessian(iext,jext); + // h(i,j) = ideriv*jderiv*fFcn.Hessian(iext,jext); // } // } - - - // cache deriv and Index values . + + + // cache deriv and Index values . // in large Parameter limit then need to re-optimize and see if better not caching - - std::vector<double> deriv(nvar); - std::vector<unsigned int> extIndex(nvar); - for (int i = 0; i < nvar; ++i) { - extIndex[i] = fTransformation.ExtOfInt(i); + + std::vector<double> deriv(nvar); + std::vector<unsigned int> extIndex(nvar); + for (int i = 0; i < nvar; ++i) { + extIndex[i] = fTransformation.ExtOfInt(i); deriv[i] = 1; - if ( fTransformation.Parameter(extIndex[i]).HasLimits()) + if ( fTransformation.Parameter(extIndex[i]).HasLimits()) deriv[i] = fTransformation.DInt2Ext( i, par.Vec()(i) ) ; - + v(i) = fcn_gradient[extIndex[i]]*deriv[i]; - - for (int j = 0; j <= i; ++j) { - h(i,j) = deriv[i]*deriv[j]*fFcn.Hessian(extIndex[i],extIndex[j]); + + for (int j = 0; j <= i; ++j) { + h(i,j) = deriv[i]*deriv[j]*fFcn.Hessian(extIndex[i],extIndex[j]); } } - + #ifdef DEBUG - // compare with other Gradient - // // calculate Gradient using Minuit method - + // compare with other Gradient + // // calculate Gradient using Minuit method + Numerical2PGradientCalculator gc(MnUserFcn(fFcn,fTransformation), fTransformation, MnStrategy(1)); FunctionGradient g2 = gc(par); - + std::cout << "Fumili Gradient " << v << std::endl; std::cout << "Minuit Gradient " << g2.Vec() << std::endl; -#endif - +#endif + // store calculated Hessian - fHessian = h; - return FunctionGradient(v); + fHessian = h; + return FunctionGradient(v); } FunctionGradient FumiliGradientCalculator::operator()(const MinimumParameters& par, const FunctionGradient&) const -{ - // Needed for interface of base class. - return this->operator()(par); - +{ + // Needed for interface of base class. + return this->operator()(par); + } } // namespace Minuit2 diff --git a/ThirdParty/RootMinimizers/src/Minuit2/FumiliMinimizer.cxx b/ThirdParty/RootMinimizers/src/Minuit2/FumiliMinimizer.cxx index 28225d876f0b4d75d72d220fb512b75137368841..287a0cba141a730a518209b1d0df593aedc78bcb 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/FumiliMinimizer.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/FumiliMinimizer.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -32,71 +32,71 @@ namespace ROOT { namespace Minuit2 { -// for Fumili implement Minimize here because need downcast +// for Fumili implement Minimize here because need downcast + - FunctionMinimum FumiliMinimizer::Minimize(const FCNBase& fcn, const MnUserParameterState& st, const MnStrategy& strategy, unsigned int maxfcn, double toler) const { - // Minimize using Fumili. Create seed and Fumili gradient calculator. + // Minimize using Fumili. Create seed and Fumili gradient calculator. // The FCNBase passed must be a FumiliFCNBase type otherwise method will fail ! - + MnUserFcn mfcn(fcn, st.Trafo()); Numerical2PGradientCalculator gc(mfcn, st.Trafo(), strategy); - + unsigned int npar = st.VariableParameters(); if(maxfcn == 0) maxfcn = 200 + 100*npar + 5*npar*npar; //FUMILI needs much less function calls - maxfcn = int(0.1*maxfcn); - + maxfcn = int(0.1*maxfcn); + MinimumSeed mnseeds = SeedGenerator()(mfcn, gc, st, strategy); - - // downcast fcn - + + // downcast fcn + //std::cout << "FCN type " << typeid(&fcn).Name() << std::endl; - - FumiliFCNBase * fumiliFcn = dynamic_cast< FumiliFCNBase *>( const_cast<FCNBase *>(&fcn) ); - if ( !fumiliFcn ) { + + FumiliFCNBase * fumiliFcn = dynamic_cast< FumiliFCNBase *>( const_cast<FCNBase *>(&fcn) ); + if ( !fumiliFcn ) { MN_ERROR_MSG("FumiliMinimizer: Error : wrong FCN type. Try to use default minimizer"); return FunctionMinimum(mnseeds, fcn.Up() ); } - - + + FumiliGradientCalculator fgc(*fumiliFcn, st.Trafo(), npar); #ifdef DEBUG std::cout << "Minuit::Minimize using FumiliMinimizer" << std::endl; -#endif +#endif return ModularFunctionMinimizer::Minimize(mfcn, fgc, mnseeds, strategy, maxfcn, toler); } FunctionMinimum FumiliMinimizer::Minimize(const FCNGradientBase& fcn, const MnUserParameterState& st, const MnStrategy& strategy, unsigned int maxfcn, double toler) const { - // Minimize using Fumili. Case of interface is a FCNGradientBase. + // Minimize using Fumili. Case of interface is a FCNGradientBase. // Normally other method is used - probably this could be removed (t.b.i.) - + // need MnUserFcn MnUserFcn mfcn(fcn, st.Trafo() ); AnalyticalGradientCalculator gc(fcn, st.Trafo()); - + unsigned int npar = st.VariableParameters(); if(maxfcn == 0) maxfcn = 200 + 100*npar + 5*npar*npar; - + MinimumSeed mnseeds = SeedGenerator()(mfcn, gc, st, strategy); - - // downcast fcn - - FumiliFCNBase * fumiliFcn = dynamic_cast< FumiliFCNBase *>( const_cast<FCNGradientBase *>(&fcn) ); - if ( !fumiliFcn ) { + + // downcast fcn + + FumiliFCNBase * fumiliFcn = dynamic_cast< FumiliFCNBase *>( const_cast<FCNGradientBase *>(&fcn) ); + if ( !fumiliFcn ) { MN_ERROR_MSG("FumiliMinimizer: Error : wrong FCN type. Try to use default minimizer"); return FunctionMinimum(mnseeds, fcn.Up() ); } - - + + FumiliGradientCalculator fgc(*fumiliFcn, st.Trafo(), npar); #ifdef DEBUG std::cout << "Minuit::Minimize using FumiliMinimizer" << std::endl; #endif return ModularFunctionMinimizer::Minimize(mfcn, fgc, mnseeds, strategy, maxfcn, toler); - + } } // namespace Minuit2 diff --git a/ThirdParty/RootMinimizers/src/Minuit2/FumiliStandardChi2FCN.cxx b/ThirdParty/RootMinimizers/src/Minuit2/FumiliStandardChi2FCN.cxx index 08bd5ae50d2f6ed23356c2ed56e9bc05a70f0a9f..5730eac321470288b07ef998439c9567edbf23fb 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/FumiliStandardChi2FCN.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/FumiliStandardChi2FCN.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -22,30 +22,30 @@ namespace ROOT { std::vector<double> FumiliStandardChi2FCN::Elements(const std::vector<double>& par) const { // Calculate the f(i) contribution to the Chi2. Chi2 = Sum[f(i)**2] - + std::vector<double> result; double tmp1 = 0.0; unsigned int fPositionsSize = fPositions.size(); - - + + for(unsigned int i=0; i < fPositionsSize; i++) { - + const std::vector<double> & currentPosition = fPositions[i]; - + // The commented line is the object-oriented way to do it // but it is faster to do a single function call... //(*(this->getModelFunction())).SetParameters(par); tmp1 = (*(this->ModelFunction()))(par, currentPosition)- fMeasurements[i]; - + result.push_back(tmp1*fInvErrors[i] ); - - //std::cout << "element " << i << " " << (*(this->getModelFunction()))(par, currentPosition) << " " << fMeasurements[i] << " " << result[i] << std::endl; + + //std::cout << "element " << i << " " << (*(this->getModelFunction()))(par, currentPosition) << " " << fMeasurements[i] << " " << result[i] << std::endl; } - - - + + + return result; - + } @@ -53,71 +53,71 @@ std::vector<double> FumiliStandardChi2FCN::Elements(const std::vector<double>& p const std::vector<double> & FumiliStandardChi2FCN::GetMeasurement(int index) const { // Return the coordinate (position) values. return fPositions[index]; - + } int FumiliStandardChi2FCN::GetNumberOfMeasurements() const { // Return size return fPositions.size(); - + } -void FumiliStandardChi2FCN::EvaluateAll( const std::vector<double> & par) { +void FumiliStandardChi2FCN::EvaluateAll( const std::vector<double> & par) { // Evaluate chi2 value, gradient and hessian all in a single - // loop on the measurements - - int nmeas = GetNumberOfMeasurements(); + // loop on the measurements + + int nmeas = GetNumberOfMeasurements(); std::vector<double> & grad = Gradient(); std::vector<double> & h = Hessian(); int npar = par.size(); - double chi2 = 0; + double chi2 = 0; grad.resize(npar); h.resize( static_cast<unsigned int>(0.5 * npar* (npar + 1) ) ); // reset Elements grad.assign(npar, 0.0); h.assign(static_cast<unsigned int>(0.5 * npar* (npar + 1) ) , 0.0); - - + + const ParametricFunction & modelFunc = *ModelFunction(); - - for (int i = 0; i < nmeas; ++i) { - + + for (int i = 0; i < nmeas; ++i) { + // work for multi-dimensional points const std::vector<double> & currentPosition = fPositions[i]; modelFunc.SetParameters( currentPosition ); double invError = fInvErrors[i]; - double fval = modelFunc(par); - + double fval = modelFunc(par); + double element = ( fval - fMeasurements[i] )*invError; chi2 += element*element; - - // calc derivatives - + + // calc derivatives + // this method should return a reference std::vector<double> mfg = modelFunc.GetGradient(par); - + // grad is derivative of chi2 w.r.t to parameters - for (int j = 0; j < npar ; ++j) { - double dfj = invError * mfg[j]; - grad[j] += 2.0 * element * dfj; - - // in second derivative use Fumili approximation neglecting the term containing the + for (int j = 0; j < npar ; ++j) { + double dfj = invError * mfg[j]; + grad[j] += 2.0 * element * dfj; + + // in second derivative use Fumili approximation neglecting the term containing the // second derivatives of the model function - for (int k = j; k < npar; ++ k) { - int idx = j + k*(k+1)/2; - h[idx] += 2.0 * dfj * invError * mfg[k]; + for (int k = j; k < npar; ++ k) { + int idx = j + k*(k+1)/2; + h[idx] += 2.0 * dfj * invError * mfg[k]; } - - } // end param loop - - } // end points loop - + + } // end param loop + + } // end points loop + // set Value in base class - SetFCNValue( chi2); - + SetFCNValue( chi2); + } } // namespace Minuit2 diff --git a/ThirdParty/RootMinimizers/src/Minuit2/FumiliStandardMaximumLikelihoodFCN.cxx b/ThirdParty/RootMinimizers/src/Minuit2/FumiliStandardMaximumLikelihoodFCN.cxx index dd1022ad165fdc00d3d885167cdc6e36fb660434..e054096ac1e5a2cc456f269055d29a761b1991b3 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/FumiliStandardMaximumLikelihoodFCN.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/FumiliStandardMaximumLikelihoodFCN.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -22,31 +22,31 @@ namespace ROOT { //#include <iostream> std::vector<double> FumiliStandardMaximumLikelihoodFCN::Elements(const std::vector<double>& par) const { - + // calculate likelihood element f(i) = pdf(x(i)) std::vector<double> result; double tmp1 = 0.0; unsigned int fPositionsSize = fPositions.size(); - - + + for(unsigned int i=0; i < fPositionsSize; i++) { - + const std::vector<double> & currentPosition = fPositions[i]; - + // The commented line is the object-oriented way to do it // but it is faster to do a single function call... //(*(this->getModelFunction())).SetParameters(par); tmp1 = (*(this->ModelFunction()))(par, currentPosition); - - // std::cout << " i = " << i << " " << currentPosition[0] << " " << tmp1 << std::endl; - + + // std::cout << " i = " << i << " " << currentPosition[0] << " " << tmp1 << std::endl; + result.push_back(tmp1); - + } - - + + return result; - + } @@ -54,120 +54,120 @@ std::vector<double> FumiliStandardMaximumLikelihoodFCN::Elements(const std::vect const std::vector<double> & FumiliStandardMaximumLikelihoodFCN::GetMeasurement(int index) const { // Return x(i). return fPositions[index]; - + } int FumiliStandardMaximumLikelihoodFCN::GetNumberOfMeasurements() const { - // return size of positions (coordinates). + // return size of positions (coordinates). return fPositions.size(); - + } -void FumiliStandardMaximumLikelihoodFCN::EvaluateAll( const std::vector<double> & par) { - // Evaluate in one loop likelihood value, gradient and hessian - - static double minDouble = 8.0*DBL_MIN; - static double minDouble2 = std::sqrt(8.0*DBL_MIN); +void FumiliStandardMaximumLikelihoodFCN::EvaluateAll( const std::vector<double> & par) { + // Evaluate in one loop likelihood value, gradient and hessian + + static double minDouble = 8.0*DBL_MIN; + static double minDouble2 = std::sqrt(8.0*DBL_MIN); static double maxDouble2 = 1.0/minDouble2; - // loop on the measurements - - int nmeas = GetNumberOfMeasurements(); + // loop on the measurements + + int nmeas = GetNumberOfMeasurements(); std::vector<double> & grad = Gradient(); std::vector<double> & h = Hessian(); int npar = par.size(); - double logLikelihood = 0; + double logLikelihood = 0; grad.resize(npar); h.resize( static_cast<unsigned int>(0.5 * npar* (npar + 1) ) ); grad.assign(npar, 0.0); h.assign(static_cast<unsigned int>(0.5 * npar* (npar + 1) ) , 0.0); - + const ParametricFunction & modelFunc = *ModelFunction(); - - for (int i = 0; i < nmeas; ++i) { - + + for (int i = 0; i < nmeas; ++i) { + // work for one-dimensional points const std::vector<double> & currentPosition = fPositions[i]; modelFunc.SetParameters( currentPosition ); - double fval = modelFunc(par); + double fval = modelFunc(par); if (fval < minDouble ) fval = minDouble; // to avoid getting infinity and nan's - logLikelihood -= std::log( fval); + logLikelihood -= std::log( fval); double invFval = 1.0/fval; // this method should return a reference std::vector<double> mfg = modelFunc.GetGradient(par); - - // calc derivatives - - for (int j = 0; j < npar; ++j) { + + // calc derivatives + + for (int j = 0; j < npar; ++j) { if ( std::fabs(mfg[j]) < minDouble ) { // std::cout << "SMALL values: grad = " << mfg[j] << " " << minDouble << " f(x) = " << fval // << " params " << j << " p0 = " << par[0] << " p1 = " << par[1] << std::endl; - if (mfg[j] < 0) + if (mfg[j] < 0) mfg[j] = -minDouble; - else + else mfg[j] = minDouble; } - - double dfj = invFval * mfg[j]; + + double dfj = invFval * mfg[j]; // to avoid summing infinite and nan later when calculating the Hessian - if ( std::fabs(dfj) > maxDouble2 ) { - if (dfj > 0) - dfj = maxDouble2; - else + if ( std::fabs(dfj) > maxDouble2 ) { + if (dfj > 0) + dfj = maxDouble2; + else dfj = -maxDouble2; } - + grad[j] -= dfj; - // if ( ! ( dfj > 0) && ! ( dfj <= 0 ) ) + // if ( ! ( dfj > 0) && ! ( dfj <= 0 ) ) // std::cout << " nan : dfj = " << dfj << " fval = " << fval << " invF = " << invFval << " grad = " << mfg[j] << " par[j] = " << par[j] << std::endl; - - //std::cout << " x = " << currentPosition[0] << " par[j] = " << par[j] << " : dfj = " << dfj << " fval = " << fval << " invF = " << invFval << " grad = " << mfg[j] << " deriv = " << grad[j] << std::endl; - - - // in second derivative use Fumili approximation neglecting the term containing the + + //std::cout << " x = " << currentPosition[0] << " par[j] = " << par[j] << " : dfj = " << dfj << " fval = " << fval << " invF = " << invFval << " grad = " << mfg[j] << " deriv = " << grad[j] << std::endl; + + + // in second derivative use Fumili approximation neglecting the term containing the // second derivatives of the model function - for (int k = j; k < npar; ++ k) { - int idx = j + k*(k+1)/2; - if (std::fabs( mfg[k]) < minDouble ) { - if (mfg[k] < 0) + for (int k = j; k < npar; ++ k) { + int idx = j + k*(k+1)/2; + if (std::fabs( mfg[k]) < minDouble ) { + if (mfg[k] < 0) mfg[k] = -minDouble; - else + else mfg[k] = minDouble; } - - double dfk = invFval * mfg[k]; - // avoid that dfk*dfj are one small and one huge so I get a nan + + double dfk = invFval * mfg[k]; + // avoid that dfk*dfj are one small and one huge so I get a nan // to avoid summing infinite and nan later when calculating the Hessian - if ( std::fabs(dfk) > maxDouble2 ) { - if (dfk > 0) - dfk = maxDouble2; - else + if ( std::fabs(dfk) > maxDouble2 ) { + if (dfk > 0) + dfk = maxDouble2; + else dfk = -maxDouble2; } - - - h[idx] += dfj * dfk; + + + h[idx] += dfj * dfk; // if ( ( ! ( h[idx] > 0) && ! ( h[idx] <= 0 ) ) ) // std::cout << " nan : dfj = " << dfj << " fval = " << fval << " invF = " << invFval << " gradj = " << mfg[j] // << " dfk = " << dfk << " gradk = "<< mfg[k] << " hess_jk = " << h[idx] << " par[k] = " << par[k] << std::endl; } - - } // end param loop - - } // end points loop - + + } // end param loop + + } // end points loop + // std::cout <<"\nEVALUATED GRADIENT and HESSIAN " << std::endl; - // for (int j = 0; j < npar; ++j) { - // std::cout << " j = " << j << " grad = " << grad[j] << std::endl; - // for (int k = j; k < npar; ++k) { - // std::cout << " k = " << k << " hess = " << Hessian(j,k) << " " << h[ j + k*(k+1)/2] << std::endl; + // for (int j = 0; j < npar; ++j) { + // std::cout << " j = " << j << " grad = " << grad[j] << std::endl; + // for (int k = j; k < npar; ++k) { + // std::cout << " k = " << k << " hess = " << Hessian(j,k) << " " << h[ j + k*(k+1)/2] << std::endl; // } // } - + // set Value in base class - SetFCNValue( logLikelihood); - + SetFCNValue( logLikelihood); + } } // namespace Minuit2 diff --git a/ThirdParty/RootMinimizers/src/Minuit2/HessianGradientCalculator.cxx b/ThirdParty/RootMinimizers/src/Minuit2/HessianGradientCalculator.cxx index be7fef1e164a10286a8b8f97ec63661741357892..1e95037accbaf9aefaaa62446420cb323e96b70c 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/HessianGradientCalculator.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/HessianGradientCalculator.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -35,14 +35,14 @@ FunctionGradient HessianGradientCalculator::operator()(const MinimumParameters& // use initial gradient as starting point InitialGradientCalculator gc(fFcn, fTransformation, fStrategy); FunctionGradient gra = gc(par); - - return (*this)(par, gra); + + return (*this)(par, gra); } FunctionGradient HessianGradientCalculator::operator()(const MinimumParameters& par, const FunctionGradient& Gradient) const { // interface of the base class. Use DeltaGradient for op. std::pair<FunctionGradient, MnAlgebraicVector> mypair = DeltaGradient(par, Gradient); - + return mypair.first; } @@ -69,22 +69,22 @@ double HessianGradientCalculator::GradTolerance() const { std::pair<FunctionGradient, MnAlgebraicVector> HessianGradientCalculator::DeltaGradient(const MinimumParameters& par, const FunctionGradient& Gradient) const { // calculate gradient for Hessian assert(par.IsValid()); - + MnAlgebraicVector x = par.Vec(); MnAlgebraicVector grd = Gradient.Grad(); const MnAlgebraicVector& g2 = Gradient.G2(); //const MnAlgebraicVector& gstep = Gradient.Gstep(); // update also gradient step sizes MnAlgebraicVector gstep = Gradient.Gstep(); - + double fcnmin = par.Fval(); // std::cout<<"fval: "<<fcnmin<<std::endl; - + double dfmin = 4.*Precision().Eps2()*(fabs(fcnmin)+Fcn().Up()); - + unsigned int n = x.size(); MnAlgebraicVector dgrd(n); - + MPIProcess mpiproc(n,0); // initial starting values unsigned int startElementIndex = mpiproc.StartElementIndex(); @@ -115,19 +115,19 @@ std::pair<FunctionGradient, MnAlgebraicVector> HessianGradientCalculator::DeltaG grdnew = (fs1-fs2)/(2.*d); dgmin = Precision().Eps()*(fabs(fs1) + fabs(fs2))/d; //if(fabs(grdnew) < Precision().Eps()) break; - if (grdnew == 0) break; + if (grdnew == 0) break; double change = fabs((grdold-grdnew)/grdnew); if(change > chgold && j > 1) break; chgold = change; grd(i) = grdnew; //LM : update also the step sizes - gstep(i) = d; + gstep(i) = d; if(change < 0.05) break; if(fabs(grdold-grdnew) < dgmin) break; if(d < dmin) break; d *= 0.2; - } + } dgrd(i) = std::max(dgmin, fabs(grdold-grdnew)); @@ -136,11 +136,11 @@ std::pair<FunctionGradient, MnAlgebraicVector> HessianGradientCalculator::DeltaG #endif } - + mpiproc.SyncVector(grd); mpiproc.SyncVector(gstep); mpiproc.SyncVector(dgrd); - + return std::pair<FunctionGradient, MnAlgebraicVector>(FunctionGradient(grd, g2, gstep), dgrd); } diff --git a/ThirdParty/RootMinimizers/src/Minuit2/InitialGradientCalculator.cxx b/ThirdParty/RootMinimizers/src/Minuit2/InitialGradientCalculator.cxx index b40fabb81662aff50812155e3547ec38c111b483..3292e417f8e75bf8c6a3fd843b275d3a6c5759a9 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/InitialGradientCalculator.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/InitialGradientCalculator.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -17,10 +17,10 @@ #include <math.h> -//#define DEBUG +//#define DEBUG #if defined(DEBUG) || defined(WARNINGMSG) -#include "Minuit2/MnPrint.h" +#include "Minuit2/MnPrint.h" #endif @@ -31,37 +31,37 @@ namespace ROOT { FunctionGradient InitialGradientCalculator::operator()(const MinimumParameters& par) const { - // initial rough estimate of the gradient using the parameter step size - + // initial rough estimate of the gradient using the parameter step size + assert(par.IsValid()); - + unsigned int n = Trafo().VariableParameters(); assert(n == par.Vec().size()); #ifdef DEBUG std::cout << "Initial gradient calculator - params " << par.Vec() << std::endl; #endif - + MnAlgebraicVector gr(n), gr2(n), gst(n); - + for(unsigned int i = 0; i < n; i++) { unsigned int exOfIn = Trafo().ExtOfInt(i); - + double var = par.Vec()(i); double werr = Trafo().Parameter(exOfIn).Error(); - double sav = Trafo().Int2ext(i, var); + double sav = Trafo().Int2ext(i, var); double sav2 = sav + werr; if(Trafo().Parameter(exOfIn).HasLimits()) { if(Trafo().Parameter(exOfIn).HasUpperLimit() && - sav2 > Trafo().Parameter(exOfIn).UpperLimit()) + sav2 > Trafo().Parameter(exOfIn).UpperLimit()) sav2 = Trafo().Parameter(exOfIn).UpperLimit(); } double var2 = Trafo().Ext2int(exOfIn, sav2); double vplu = var2 - var; sav2 = sav - werr; if(Trafo().Parameter(exOfIn).HasLimits()) { - if(Trafo().Parameter(exOfIn).HasLowerLimit() && - sav2 < Trafo().Parameter(exOfIn).LowerLimit()) + if(Trafo().Parameter(exOfIn).HasLowerLimit() && + sav2 < Trafo().Parameter(exOfIn).LowerLimit()) sav2 = Trafo().Parameter(exOfIn).LowerLimit(); } var2 = Trafo().Ext2int(exOfIn, sav2); @@ -78,9 +78,15 @@ FunctionGradient InitialGradientCalculator::operator()(const MinimumParameters& gr(i) = grd; gr2(i) = g2; gst(i) = gstep; + +#ifdef DEBUG + std::cout << "computing initial gradient for parameter " << Trafo().Name(exOfIn) << " value = " << var + << " [ " << vmin << " , " << vplu << " ] " << "dirin " << dirin << " grd " << grd << " g2 " << g2 << std::endl; +#endif + } - - return FunctionGradient(gr, gr2, gst); + + return FunctionGradient(gr, gr2, gst); } FunctionGradient InitialGradientCalculator::operator()(const MinimumParameters& par, const FunctionGradient&) const { diff --git a/ThirdParty/RootMinimizers/src/Minuit2/LaEigenValues.cxx b/ThirdParty/RootMinimizers/src/Minuit2/LaEigenValues.cxx index cbaedbd619ab3526769375bb3dee6e657bc0d94f..576525602233bdb31301c78aadb13f29dda92212 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/LaEigenValues.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/LaEigenValues.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -20,23 +20,23 @@ int mneigen(double*, unsigned int, unsigned int, unsigned int, double*,double); LAVector eigenvalues(const LASymMatrix& mat) { // calculate eigenvalues of symmetric matrices using mneigen function (transalte from fortran Minuit) unsigned int nrow = mat.Nrow(); - + LAVector tmp(nrow*nrow); LAVector work(2*nrow); - + for(unsigned int i = 0; i < nrow; i++) for(unsigned int j = 0; j <= i; j++) { tmp(i + j*nrow) = mat(i,j); tmp(i*nrow + j) = mat(i,j); } - - int info = mneigen(tmp.Data(), nrow, nrow, work.size(), work.Data(), 1.e-6); - + + int info = mneigen(tmp.Data(), nrow, nrow, work.size(), work.Data(), 1.e-6); + (void)info; assert(info == 0); - + LAVector result(nrow); for(unsigned int i = 0; i < nrow; i++) result(i) = work(i); - + return result; } diff --git a/ThirdParty/RootMinimizers/src/Minuit2/LaInnerProduct.cxx b/ThirdParty/RootMinimizers/src/Minuit2/LaInnerProduct.cxx index 8b0079fc0c438f6d32c3a3e0c87acd96080abb00..76c159ca751162add2299aa7ba6684ca41e6e950 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/LaInnerProduct.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/LaInnerProduct.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * diff --git a/ThirdParty/RootMinimizers/src/Minuit2/LaInverse.cxx b/ThirdParty/RootMinimizers/src/Minuit2/LaInverse.cxx index b82c6d34bf1197deb6b8be60b2c249f3fe3538af..f21dfb2419c77606cefdf37c5b358629ceadd840 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/LaInverse.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/LaInverse.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -20,11 +20,11 @@ int mnvert(LASymMatrix& t); // symmetric matrix (positive definite only) int Invert(LASymMatrix& t) { - // function for inversion of symmetric matrices using mnvert function + // function for inversion of symmetric matrices using mnvert function // (from Fortran Minuit) - + int ifail = 0; - + if(t.size() == 1) { double tmp = t.Data()[0]; if(!(tmp > 0.)) ifail = 1; @@ -32,7 +32,7 @@ int Invert(LASymMatrix& t) { } else { ifail = mnvert(t); } - + return ifail; } diff --git a/ThirdParty/RootMinimizers/src/Minuit2/LaOuterProduct.cxx b/ThirdParty/RootMinimizers/src/Minuit2/LaOuterProduct.cxx index 1f91dd137f7b1fb4a1bd7b77c4b48bd6ada1a8da..584b46494ec313ae6931707c92d2fb05c9a0bc6a 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/LaOuterProduct.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/LaOuterProduct.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -29,7 +29,7 @@ LASymMatrix::LASymMatrix(const ABObj<sym, VectorOuterProduct<ABObj<vec, LAVector } LASymMatrix& LASymMatrix::operator=(const ABObj<sym, VectorOuterProduct<ABObj<vec, LAVector, double>, double>, double>& out) { - // assignment operator from expression based on outer product of symmetric matrices + // assignment operator from expression based on outer product of symmetric matrices // std::cout<<"LASymMatrix& LASymMatrix::operator=(const ABObj<sym, VectorOuterProduct<ABObj<vec, LAVector, double>, double>, double>& out)"<<std::endl; if(fSize == 0 && fData == 0) { fNRow = out.Obj().Obj().Obj().size(); diff --git a/ThirdParty/RootMinimizers/src/Minuit2/LaSumOfElements.cxx b/ThirdParty/RootMinimizers/src/Minuit2/LaSumOfElements.cxx index b9e48b002135017faf99dfc858b20dbef943e908..3c053247e329e399c3e15664a25d6ed834c588f1 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/LaSumOfElements.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/LaSumOfElements.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -15,16 +15,16 @@ namespace ROOT { namespace Minuit2 { -double mndasum(unsigned int, const double*, int); +double mndasum(unsigned int, const double*, int); double sum_of_elements(const LAVector& v) { - // calculate the absolute sum of the vector elements using mndasum + // calculate the absolute sum of the vector elements using mndasum // which is a translation from dasum from BLAS return mndasum(v.size(), v.Data(), 1); } double sum_of_elements(const LASymMatrix& m) { - // calculate the absolute sum of all the matrix elements using mndasum + // calculate the absolute sum of all the matrix elements using mndasum // which is a translation of dasum from BLAS return mndasum(m.size(), m.Data(), 1); } diff --git a/ThirdParty/RootMinimizers/src/Minuit2/LaVtMVSimilarity.cxx b/ThirdParty/RootMinimizers/src/Minuit2/LaVtMVSimilarity.cxx index a4077e699edb6956b22fe1195df59cc65fb8d4fd..098e15922ef713d72db3fd0f2f5e7d515f983c19 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/LaVtMVSimilarity.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/LaVtMVSimilarity.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -21,9 +21,9 @@ double mnddot(unsigned int, const double*, int, const double*, int); double similarity(const LAVector& avec, const LASymMatrix& mat) { // calculate the similarity vector-matrix product: V^T M V // use matrix product and then dot function (using mnddot) - + LAVector tmp = mat*avec; - + double value = mnddot(avec.size(), avec.Data(), 1, tmp.Data(), 1); return value; } diff --git a/ThirdParty/RootMinimizers/src/Minuit2/MPIProcess.cxx b/ThirdParty/RootMinimizers/src/Minuit2/MPIProcess.cxx index e1ff82cf6cad9335d61d4f5fe17d9b6b718f6b73..b96bbaaf502f156f779edaeb19c9f9b1d3a53670 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/MPIProcess.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/MPIProcess.cxx @@ -43,15 +43,15 @@ namespace Minuit2 { StartMPI(); - if (fgGlobalSize==fgCartDimension && + if (fgGlobalSize==fgCartDimension && fgCartSizeX!=fgCartDimension && fgCartSizeY!=fgCartDimension) { //declare the cartesian topology if (fgCommunicator==0 && fgIndexComm<0 && fgNewCart) { // first call, declare the topology - std::cout << "Info --> MPIProcess::MPIProcess: Declare cartesian Topology (" + std::cout << "Info --> MPIProcess::MPIProcess: Declare cartesian Topology (" << fgCartSizeX << "x" << fgCartSizeY << ")" << std::endl; - + int color = fgGlobalRank / fgCartSizeY; int key = fgGlobalRank % fgCartSizeY; @@ -67,7 +67,7 @@ namespace Minuit2 { if (fgIndexComm>1 || fgCommunicator==(&(MPI::COMM_WORLD))) { // Remember, no more than 2 dimensions in the topology! std::cerr << "Error --> MPIProcess::MPIProcess: Requiring more than 2 dimensions in the topology!" << std::endl; MPI::COMM_WORLD.Abort(-1); - } + } // requiring columns as first call. In this case use all nodes if (((unsigned int)fgIndexComm)<indexComm) @@ -114,7 +114,7 @@ namespace Minuit2 { std::cout << "Warning --> MPIProcess::MPIProcess: Requiring 2 nested MPI calls!" << std::endl; std::cout << "Warning --> MPIProcess::MPIProcess: Ignoring second call." << std::endl; fgIndecesComm[fgIndexComm] = (indexComm==0) ? 1 : 0; - } + } fgCommunicator = fgCommunicators[fgIndecesComm[fgIndexComm]]; @@ -130,7 +130,7 @@ namespace Minuit2 { fSize = 1; fRank = 0; } - + if (fSize>fNelements) { std::cerr << "Error --> MPIProcess::MPIProcess: more processors than elements!" << std::endl; @@ -147,19 +147,19 @@ namespace Minuit2 { MPIProcess::~MPIProcess() { // destructor -#ifdef MPIPROC +#ifdef MPIPROC fgCommunicator = 0; - fgIndexComm--; + fgIndexComm--; if (fgIndexComm==0) fgCommunicator = fgCommunicators[fgIndecesComm[fgIndexComm]]; - + #endif } bool MPIProcess::SyncVector(ROOT::Minuit2::MnAlgebraicVector &mnvector) { - + // In case of just one job, don't need sync, just go if (fSize<2) return false; @@ -169,7 +169,7 @@ namespace Minuit2 { std::cerr << "Error --> MPIProcess::SyncVector: no MPI syncronization is possible!" << std::endl; exit(-1); } - + #ifdef MPIPROC unsigned int numElements4ThisJob = NumElements4Job(fRank); unsigned int startElementIndex = StartElementIndex(); @@ -184,7 +184,7 @@ namespace Minuit2 { for (unsigned int i = 0; i<fNelements; i++) { mnvector(i) = dvector[i]; - } + } return true; @@ -196,15 +196,15 @@ namespace Minuit2 { #endif } - + bool MPIProcess::SyncSymMatrixOffDiagonal(ROOT::Minuit2::MnAlgebraicSymMatrix &mnmatrix) { - + // In case of just one job, don't need sync, just go if (fSize<2) return false; - + if (mnmatrix.size()-mnmatrix.Nrow()!=fNelements) { std::cerr << "Error --> MPIProcess::SyncSymMatrixOffDiagonal: # defined elements different from # requested elements!" << std::endl; std::cerr << "Error --> MPIProcess::SyncSymMatrixOffDiagonal: no MPI syncronization is possible!" << std::endl; @@ -229,7 +229,7 @@ namespace Minuit2 { int y = (i+offsetVect)%(nrow-1)+1; dvectorJob[i-startElementIndex] = mnmatrix(x,y); - + } double dvector[fNelements]; @@ -237,7 +237,7 @@ namespace Minuit2 { offsetVect = 0; for (unsigned int i = 0; i<fNelements; i++) { - + int x = (i+offsetVect)/(nrow-1); if ((i+offsetVect)%(nrow-1)==0) offsetVect += x; int y = (i+offsetVect)%(nrow-1)+1; @@ -270,11 +270,11 @@ namespace Minuit2 { } fgCommunicator->Allgatherv(ivector,svector,MPI::DOUBLE, - ovector,nconts,offsets,MPI::DOUBLE); - + ovector,nconts,offsets,MPI::DOUBLE); + } - bool MPIProcess::SetCartDimension(unsigned int dimX, unsigned int dimY) + bool MPIProcess::SetCartDimension(unsigned int dimX, unsigned int dimY) { if (fgCommunicator!=0 || fgIndexComm>=0) { std::cout << "Warning --> MPIProcess::SetCartDimension: MPIProcess already declared! Ignoring command..." << std::endl; @@ -294,7 +294,7 @@ namespace Minuit2 { } if (fgCartSizeX!=dimX || fgCartSizeY!=dimY) { - fgCartSizeX = dimX; fgCartSizeY = dimY; + fgCartSizeX = dimX; fgCartSizeY = dimY; fgCartDimension = fgCartSizeX * fgCartSizeY; fgNewCart = true; @@ -309,7 +309,7 @@ namespace Minuit2 { } bool MPIProcess::SetDoFirstMPICall(bool doFirstMPICall) - { + { StartMPI(); diff --git a/ThirdParty/RootMinimizers/src/Minuit2/MinimumBuilder.cxx b/ThirdParty/RootMinimizers/src/Minuit2/MinimumBuilder.cxx index 65dc5a45f4b28fa4e3925ce591a1c090f3e872d0..7da1308c38bca1e0359e256c09539b863e1a5b96 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/MinimumBuilder.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/MinimumBuilder.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -10,7 +10,7 @@ #include "Minuit2/MinimumBuilder.h" #if defined(DEBUG) || defined(WARNINGMSG) -#include "Minuit2/MnPrint.h" +#include "Minuit2/MnPrint.h" #endif @@ -18,10 +18,10 @@ namespace ROOT { namespace Minuit2 { - MinimumBuilder::MinimumBuilder() : - fPrintLevel(MnPrint::Level()), - fStorageLevel(1), - fTracer(0) + MinimumBuilder::MinimumBuilder() : + fPrintLevel(MnPrint::Level()), + fStorageLevel(1), + fTracer(0) {} diff --git a/ThirdParty/RootMinimizers/src/Minuit2/Minuit2Minimizer.cxx b/ThirdParty/RootMinimizers/src/Minuit2/Minuit2Minimizer.cxx index 0db9e1be44af378f45ac34446a361e407db2bc5a..43ee69607243d089306d9099171f0b68aa97644b 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/Minuit2Minimizer.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/Minuit2Minimizer.cxx @@ -36,11 +36,11 @@ #include "Minuit2/FumiliMinimizer.h" #include "Minuit2/MnParameterScan.h" #include "Minuit2/MnContours.h" -#include "Minuit2/MnTraceObject.h" +#include "Minuit2/MnTraceObject.h" #include "Minuit2/MinimumBuilder.h" -#include <cassert> -#include <iostream> +#include <cassert> +#include <iostream> #include <algorithm> #include <functional> @@ -49,92 +49,92 @@ #include "TMinuit2TraceObject.h" #endif -namespace ROOT { +namespace ROOT { -namespace Minuit2 { +namespace Minuit2 { - // functions needed to control siwthc off of Minuit2 printing level + // functions needed to control siwthc off of Minuit2 printing level #ifdef USE_ROOT_ERROR - int TurnOffPrintInfoLevel() { - // switch off Minuit2 printing of INFO message (cut off is 1001) - int prevErrorIgnoreLevel = gErrorIgnoreLevel; - if (prevErrorIgnoreLevel < 1001) { - gErrorIgnoreLevel = 1001; - return prevErrorIgnoreLevel; + int TurnOffPrintInfoLevel() { + // switch off Minuit2 printing of INFO message (cut off is 1001) + int prevErrorIgnoreLevel = gErrorIgnoreLevel; + if (prevErrorIgnoreLevel < 1001) { + gErrorIgnoreLevel = 1001; + return prevErrorIgnoreLevel; } - return -2; // no op in this case + return -2; // no op in this case } -void RestoreGlobalPrintLevel(int value) { - gErrorIgnoreLevel = value; +void RestoreGlobalPrintLevel(int value) { + gErrorIgnoreLevel = value; } #else // dummy functions - int TurnOffPrintInfoLevel() { return -1; } + int TurnOffPrintInfoLevel() { return -1; } int ControlPrintLevel( ) { return -1;} - void RestoreGlobalPrintLevel(int ) {} -#endif + void RestoreGlobalPrintLevel(int ) {} +#endif + - -Minuit2Minimizer::Minuit2Minimizer(ROOT::Minuit2::EMinimizerType type ) : +Minuit2Minimizer::Minuit2Minimizer(ROOT::Minuit2::EMinimizerType type ) : Minimizer(), fDim(0), fMinimizer(0), fMinuitFCN(0), - fMinimum(0) + fMinimum(0) { - // Default constructor implementation depending on minimizer type - SetMinimizerType(type); + // Default constructor implementation depending on minimizer type + SetMinimizerType(type); } -Minuit2Minimizer::Minuit2Minimizer(const char * type ) : +Minuit2Minimizer::Minuit2Minimizer(const char * type ) : Minimizer(), fDim(0), fMinimizer(0), fMinuitFCN(0), - fMinimum(0) -{ + fMinimum(0) +{ // constructor from a string std::string algoname(type); // tolower() is not an std function (Windows) - std::transform(algoname.begin(), algoname.end(), algoname.begin(), (int(*)(int)) tolower ); + std::transform(algoname.begin(), algoname.end(), algoname.begin(), (int(*)(int)) tolower ); - EMinimizerType algoType = kMigrad; - if (algoname == "simplex") algoType = kSimplex; - if (algoname == "minimize" ) algoType = kCombined; - if (algoname == "scan" ) algoType = kScan; + EMinimizerType algoType = kMigrad; + if (algoname == "simplex") algoType = kSimplex; + if (algoname == "minimize" ) algoType = kCombined; + if (algoname == "scan" ) algoType = kScan; if (algoname == "fumili" ) algoType = kFumili; - + SetMinimizerType(algoType); } void Minuit2Minimizer::SetMinimizerType(ROOT::Minuit2::EMinimizerType type) { - // Set minimizer algorithm type + // Set minimizer algorithm type fUseFumili = false; - switch (type) { - case ROOT::Minuit2::kMigrad: + switch (type) { + case ROOT::Minuit2::kMigrad: //std::cout << "Minuit2Minimizer: minimize using MIGRAD " << std::endl; SetMinimizer( new ROOT::Minuit2::VariableMetricMinimizer() ); return; - case ROOT::Minuit2::kSimplex: + case ROOT::Minuit2::kSimplex: //std::cout << "Minuit2Minimizer: minimize using SIMPLEX " << std::endl; SetMinimizer( new ROOT::Minuit2::SimplexMinimizer() ); return; - case ROOT::Minuit2::kCombined: + case ROOT::Minuit2::kCombined: SetMinimizer( new ROOT::Minuit2::CombinedMinimizer() ); return; - case ROOT::Minuit2::kScan: + case ROOT::Minuit2::kScan: SetMinimizer( new ROOT::Minuit2::ScanMinimizer() ); return; - case ROOT::Minuit2::kFumili: + case ROOT::Minuit2::kFumili: SetMinimizer( new ROOT::Minuit2::FumiliMinimizer() ); fUseFumili = true; return; - default: + default: //migrad minimizer SetMinimizer( new ROOT::Minuit2::VariableMetricMinimizer() ); @@ -142,21 +142,21 @@ void Minuit2Minimizer::SetMinimizerType(ROOT::Minuit2::EMinimizerType type) { } -Minuit2Minimizer::~Minuit2Minimizer() +Minuit2Minimizer::~Minuit2Minimizer() { // Destructor implementation. - if (fMinimizer) delete fMinimizer; - if (fMinuitFCN) delete fMinuitFCN; - if (fMinimum) delete fMinimum; + if (fMinimizer) delete fMinimizer; + if (fMinuitFCN) delete fMinuitFCN; + if (fMinimum) delete fMinimum; } -Minuit2Minimizer::Minuit2Minimizer(const Minuit2Minimizer &) : +Minuit2Minimizer::Minuit2Minimizer(const Minuit2Minimizer &) : ROOT::Math::Minimizer() { // Implementation of copy constructor. } -Minuit2Minimizer & Minuit2Minimizer::operator = (const Minuit2Minimizer &rhs) +Minuit2Minimizer & Minuit2Minimizer::operator = (const Minuit2Minimizer &rhs) { // Implementation of assignment operator. if (this == &rhs) return *this; // time saving self-test @@ -164,45 +164,45 @@ Minuit2Minimizer & Minuit2Minimizer::operator = (const Minuit2Minimizer &rhs) } -void Minuit2Minimizer::Clear() { +void Minuit2Minimizer::Clear() { // delete the state in case of consecutive minimizations fState = MnUserParameterState(); // clear also the function minimum - if (fMinimum) delete fMinimum; + if (fMinimum) delete fMinimum; fMinimum = 0; } -// set variables +// set variables -bool Minuit2Minimizer::SetVariable(unsigned int ivar, const std::string & name, double val, double step) { - // set a free variable. +bool Minuit2Minimizer::SetVariable(unsigned int ivar, const std::string & name, double val, double step) { + // set a free variable. // Add the variable if not existing otherwise set value if exists already // this is implemented in MnUserParameterState::Add - // if index is wrong (i.e. variable already exists but with a different index return false) but + // if index is wrong (i.e. variable already exists but with a different index return false) but // value is set for corresponding variable name // std::cout << " add parameter " << name << " " << val << " step " << step << std::endl; - if (step <= 0) { + if (step <= 0) { std::string txtmsg = "Parameter " + name + " has zero or invalid step size - consider it as constant "; MN_INFO_MSG2("Minuit2Minimizer::SetVariable",txtmsg); fState.Add(name.c_str(), val); } - else - fState.Add(name.c_str(), val, step); + else + fState.Add(name.c_str(), val, step); - unsigned int minuit2Index = fState.Index(name.c_str() ); + unsigned int minuit2Index = fState.Index(name.c_str() ); if ( minuit2Index != ivar) { std::string txtmsg("Wrong index used for the variable " + name); - MN_INFO_MSG2("Minuit2Minimizer::SetVariable",txtmsg); - MN_INFO_VAL2("Minuit2Minimizer::SetVariable",minuit2Index); + MN_INFO_MSG2("Minuit2Minimizer::SetVariable",txtmsg); + MN_INFO_VAL2("Minuit2Minimizer::SetVariable",minuit2Index); ivar = minuit2Index; return false; } fState.RemoveLimits(ivar); - return true; + return true; } bool Minuit2Minimizer::SetLowerLimitedVariable(unsigned int ivar , const std::string & name , double val , double step , double lower ) { @@ -230,125 +230,125 @@ bool Minuit2Minimizer::SetLimitedVariable(unsigned int ivar , const std::string bool Minuit2Minimizer::SetFixedVariable(unsigned int ivar , const std::string & name , double val ) { // add a fixed variable - // need a step size otherwise treated as a constant - // use 10% + // need a step size otherwise treated as a constant + // use 10% double step = ( val != 0) ? 0.1 * std::abs(val) : 0.1; - if (!SetVariable(ivar, name, val, step ) ) { - ivar = fState.Index(name.c_str() ); + if (!SetVariable(ivar, name, val, step ) ) { + ivar = fState.Index(name.c_str() ); } fState.Fix(ivar); return true; } -std::string Minuit2Minimizer::VariableName(unsigned int ivar) const { +std::string Minuit2Minimizer::VariableName(unsigned int ivar) const { // return the variable name if (ivar >= fState.MinuitParameters().size() ) return std::string(); return fState.GetName(ivar); } -int Minuit2Minimizer::VariableIndex(const std::string & name) const { +int Minuit2Minimizer::VariableIndex(const std::string & name) const { // return the variable index // check if variable exist return fState.Trafo().FindIndex(name); } -bool Minuit2Minimizer::SetVariableValue(unsigned int ivar, double val) { +bool Minuit2Minimizer::SetVariableValue(unsigned int ivar, double val) { // set value for variable ivar (only for existing parameters) - if (ivar >= fState.MinuitParameters().size() ) return false; + if (ivar >= fState.MinuitParameters().size() ) return false; fState.SetValue(ivar, val); - return true; + return true; } -bool Minuit2Minimizer::SetVariableValues(const double * x) { +bool Minuit2Minimizer::SetVariableValues(const double * x) { // set value for variable ivar (only for existing parameters) - unsigned int n = fState.MinuitParameters().size(); - if (n== 0) return false; - for (unsigned int ivar = 0; ivar < n; ++ivar) + unsigned int n = fState.MinuitParameters().size(); + if (n== 0) return false; + for (unsigned int ivar = 0; ivar < n; ++ivar) fState.SetValue(ivar, x[ivar]); - return true; + return true; } -bool Minuit2Minimizer::SetVariableStepSize(unsigned int ivar, double step) { +bool Minuit2Minimizer::SetVariableStepSize(unsigned int ivar, double step) { // set the step-size of an existing variable // parameter must exist or return false - if (ivar >= fState.MinuitParameters().size() ) return false; + if (ivar >= fState.MinuitParameters().size() ) return false; fState.SetError(ivar, step); - return true; + return true; } -bool Minuit2Minimizer::SetVariableLowerLimit(unsigned int ivar, double lower) { +bool Minuit2Minimizer::SetVariableLowerLimit(unsigned int ivar, double lower) { // set the limits of an existing variable // parameter must exist or return false - if (ivar >= fState.MinuitParameters().size() ) return false; + if (ivar >= fState.MinuitParameters().size() ) return false; fState.SetLowerLimit(ivar, lower); - return true; + return true; } -bool Minuit2Minimizer::SetVariableUpperLimit(unsigned int ivar, double upper ) { +bool Minuit2Minimizer::SetVariableUpperLimit(unsigned int ivar, double upper ) { // set the limits of an existing variable // parameter must exist or return false - if (ivar >= fState.MinuitParameters().size() ) return false; + if (ivar >= fState.MinuitParameters().size() ) return false; fState.SetUpperLimit(ivar, upper); - return true; + return true; } -bool Minuit2Minimizer::SetVariableLimits(unsigned int ivar, double lower, double upper) { +bool Minuit2Minimizer::SetVariableLimits(unsigned int ivar, double lower, double upper) { // set the limits of an existing variable // parameter must exist or return false - if (ivar >= fState.MinuitParameters().size() ) return false; + if (ivar >= fState.MinuitParameters().size() ) return false; fState.SetLimits(ivar, lower,upper); - return true; + return true; } -bool Minuit2Minimizer::FixVariable(unsigned int ivar) { +bool Minuit2Minimizer::FixVariable(unsigned int ivar) { // Fix an existing variable - if (ivar >= fState.MinuitParameters().size() ) return false; + if (ivar >= fState.MinuitParameters().size() ) return false; fState.Fix(ivar); - return true; + return true; } -bool Minuit2Minimizer::ReleaseVariable(unsigned int ivar) { +bool Minuit2Minimizer::ReleaseVariable(unsigned int ivar) { // Release an existing variable - if (ivar >= fState.MinuitParameters().size() ) return false; + if (ivar >= fState.MinuitParameters().size() ) return false; fState.Release(ivar); - return true; + return true; } -bool Minuit2Minimizer::IsFixedVariable(unsigned int ivar) const { +bool Minuit2Minimizer::IsFixedVariable(unsigned int ivar) const { // query if variable is fixed if (ivar >= fState.MinuitParameters().size() ) { - MN_ERROR_MSG2("Minuit2Minimizer","wrong variable index"); - return false; + MN_ERROR_MSG2("Minuit2Minimizer","wrong variable index"); + return false; } return (fState.Parameter(ivar).IsFixed() || fState.Parameter(ivar).IsConst() ); -} +} -bool Minuit2Minimizer::GetVariableSettings(unsigned int ivar, ROOT::Fit::ParameterSettings & varObj) const { +bool Minuit2Minimizer::GetVariableSettings(unsigned int ivar, ROOT::Fit::ParameterSettings & varObj) const { // retrieve variable settings (all set info on the variable) if (ivar >= fState.MinuitParameters().size() ) { - MN_ERROR_MSG2("Minuit2Minimizer","wrong variable index"); - return false; + MN_ERROR_MSG2("Minuit2Minimizer","wrong variable index"); + return false; } - const MinuitParameter & par = fState.Parameter(ivar); + const MinuitParameter & par = fState.Parameter(ivar); varObj.Set( par.Name(), par.Value(), par.Error() ); if (par.HasLowerLimit() ) varObj.SetLowerLimit(par.LowerLimit() ); else if (par.HasUpperLimit() ) varObj.SetUpperLimit(par.UpperLimit() ); else if (par.HasLimits() ) varObj.SetLimits(par.LowerLimit(), par.UpperLimit() ); - if (par.IsConst() || par.IsFixed() ) varObj.Fix(); - return true; + if (par.IsConst() || par.IsFixed() ) varObj.Fix(); + return true; } - -void Minuit2Minimizer::SetFunction(const ROOT::Math::IMultiGenFunction & func) { + +void Minuit2Minimizer::SetFunction(const ROOT::Math::IMultiGenFunction & func) { // set function to be minimized if (fMinuitFCN) delete fMinuitFCN; - fDim = func.NDim(); + fDim = func.NDim(); if (!fUseFumili) { fMinuitFCN = new ROOT::Minuit2::FCNAdapter<ROOT::Math::IMultiGenFunction> (func, ErrorDef() ); } - else { + else { // for Fumili the fit method function interface is required const ROOT::Math::FitMethodFunction * fcnfunc = dynamic_cast<const ROOT::Math::FitMethodFunction *>(&func); if (!fcnfunc) { @@ -359,14 +359,14 @@ void Minuit2Minimizer::SetFunction(const ROOT::Math::IMultiGenFunction & func) } } -void Minuit2Minimizer::SetFunction(const ROOT::Math::IMultiGradFunction & func) { +void Minuit2Minimizer::SetFunction(const ROOT::Math::IMultiGradFunction & func) { // set function to be minimized - fDim = func.NDim(); + fDim = func.NDim(); if (fMinuitFCN) delete fMinuitFCN; - if (!fUseFumili) { + if (!fUseFumili) { fMinuitFCN = new ROOT::Minuit2::FCNGradAdapter<ROOT::Math::IMultiGradFunction> (func, ErrorDef() ); } - else { + else { // for Fumili the fit method function interface is required const ROOT::Math::FitMethodGradFunction * fcnfunc = dynamic_cast<const ROOT::Math::FitMethodGradFunction*>(&func); if (!fcnfunc) { @@ -376,38 +376,38 @@ void Minuit2Minimizer::SetFunction(const ROOT::Math::IMultiGradFunction & func) fMinuitFCN = new ROOT::Minuit2::FumiliFCNAdapter<ROOT::Math::FitMethodGradFunction> (*fcnfunc, fDim, ErrorDef() ); } } - -bool Minuit2Minimizer::Minimize() { + +bool Minuit2Minimizer::Minimize() { // perform the minimization - // store a copy of FunctionMinimum - if (!fMinuitFCN) { + // store a copy of FunctionMinimum + if (!fMinuitFCN) { MN_ERROR_MSG2("Minuit2Minimizer::Minimize","FCN function has not been set"); - return false; + return false; } assert(GetMinimizer() != 0 ); // delete result of previous minimization - if (fMinimum) delete fMinimum; + if (fMinimum) delete fMinimum; fMinimum = 0; - int maxfcn = MaxFunctionCalls(); + int maxfcn = MaxFunctionCalls(); double tol = Tolerance(); - int strategyLevel = Strategy(); + int strategyLevel = Strategy(); fMinuitFCN->SetErrorDef(ErrorDef() ); int printLevel = PrintLevel(); - if (printLevel >=1) { + if (printLevel >=1) { // print the real number of maxfcn used (defined in ModularFuncitonMinimizer) - int maxfcn_used = maxfcn; - if (maxfcn_used == 0) { + int maxfcn_used = maxfcn; + if (maxfcn_used == 0) { int nvar = fState.VariableParameters(); maxfcn_used = 200 + 100*nvar + 5*nvar*nvar; - } - std::cout << "Minuit2Minimizer: Minimize with max-calls " << maxfcn_used - << " convergence for edm < " << tol << " strategy " - << strategyLevel << std::endl; + } + std::cout << "Minuit2Minimizer: Minimize with max-calls " << maxfcn_used + << " convergence for edm < " << tol << " strategy " + << strategyLevel << std::endl; } // internal minuit messages @@ -415,7 +415,7 @@ bool Minuit2Minimizer::Minimize() { fMinimizer->Builder().SetPrintLevel(printLevel); // switch off Minuit2 printing - int prev_level = (printLevel <= 0 ) ? TurnOffPrintInfoLevel() : -2; + int prev_level = (printLevel <= 0 ) ? TurnOffPrintInfoLevel() : -2; // set the precision if needed if (Precision() > 0) fState.SetPrecision(Precision()); @@ -423,7 +423,7 @@ bool Minuit2Minimizer::Minimize() { // set strategy and add extra options if needed ROOT::Minuit2::MnStrategy strategy(strategyLevel); ROOT::Math::IOptions * minuit2Opt = ROOT::Math::MinimizerOptions::FindDefault("Minuit2"); - if (minuit2Opt) { + if (minuit2Opt) { // set extra strategy options int nGradCycles = strategy.GradientNCycles(); int nHessCycles = strategy.HessianNCycles(); @@ -443,7 +443,7 @@ bool Minuit2Minimizer::Minimize() { minuit2Opt->GetValue("HessianStepTolerance",hessStepTol); minuit2Opt->GetValue("HessianG2Tolerance",hessG2Tol); - strategy.SetGradientNCycles(nGradCycles); + strategy.SetGradientNCycles(nGradCycles); strategy.SetHessianNCycles(nHessCycles); strategy.SetHessianGradientNCycles(nHessGradCycles); @@ -452,22 +452,22 @@ bool Minuit2Minimizer::Minimize() { strategy.SetHessianStepTolerance(hessStepTol); strategy.SetHessianG2Tolerance(hessStepTol); - if (printLevel > 0) { + if (printLevel > 0) { std::cout << "Minuit2Minimizer::Minuit - Changing default strategy options" << std::endl; minuit2Opt->Print(); } - int storageLevel = 1; + int storageLevel = 1; bool ret = minuit2Opt->GetValue("StorageLevel",storageLevel); if (ret) SetStorageLevel(storageLevel); - + } // set a minimizer tracer object (default for printlevel=10, from gROOT for printLevel=11) // use some special print levels MnTraceObject * traceObj = 0; -#ifdef USE_ROOT_ERROR - if (printLevel == 10 && gROOT) { +#ifdef USE_ROOT_ERROR + if (printLevel == 10 && gROOT) { TObject * obj = gROOT->FindObject("Minuit2TraceObject"); traceObj = dynamic_cast<ROOT::Minuit2::MnTraceObject*>(obj); if (traceObj) { @@ -475,7 +475,7 @@ bool Minuit2Minimizer::Minimize() { gROOT->Remove(obj); } } - if (printLevel == 20 || printLevel == 30 || printLevel == 40 || (printLevel >= 20000 && printLevel < 30000) ) { + if (printLevel == 20 || printLevel == 30 || printLevel == 40 || (printLevel >= 20000 && printLevel < 30000) ) { int parNumber = printLevel-20000; if (printLevel == 20) parNumber = -1; if (printLevel == 30) parNumber = -2; @@ -484,56 +484,56 @@ bool Minuit2Minimizer::Minimize() { } #endif if (printLevel == 100 || (printLevel >= 10000 && printLevel < 20000)) { - int parNumber = printLevel-10000; + int parNumber = printLevel-10000; traceObj = new MnTraceObject(parNumber); } - if (traceObj) { + if (traceObj) { traceObj->Init(fState); SetTraceObject(*traceObj); } - - const ROOT::Minuit2::FCNGradientBase * gradFCN = dynamic_cast<const ROOT::Minuit2::FCNGradientBase *>( fMinuitFCN ); + + const ROOT::Minuit2::FCNGradientBase * gradFCN = dynamic_cast<const ROOT::Minuit2::FCNGradientBase *>( fMinuitFCN ); if ( gradFCN != 0) { // use gradient //SetPrintLevel(3); ROOT::Minuit2::FunctionMinimum min = GetMinimizer()->Minimize(*gradFCN, fState, strategy, maxfcn, tol); - fMinimum = new ROOT::Minuit2::FunctionMinimum (min); + fMinimum = new ROOT::Minuit2::FunctionMinimum (min); } else { ROOT::Minuit2::FunctionMinimum min = GetMinimizer()->Minimize(*GetFCN(), fState, strategy, maxfcn, tol); - fMinimum = new ROOT::Minuit2::FunctionMinimum (min); + fMinimum = new ROOT::Minuit2::FunctionMinimum (min); } - // check if Hesse needs to be run + // check if Hesse needs to be run if (fMinimum->IsValid() && IsValidError() && fMinimum->State().Error().Dcovar() != 0 ) { // run Hesse (Hesse will add results in the last state of fMinimum ROOT::Minuit2::MnHesse hesse(strategy ); - hesse( *fMinuitFCN, *fMinimum, maxfcn); + hesse( *fMinuitFCN, *fMinimum, maxfcn); } // -2 is the highest low invalid value for gErrorIgnoreLevel if (prev_level > -2) RestoreGlobalPrintLevel(prev_level); - - fState = fMinimum->UserState(); + + fState = fMinimum->UserState(); bool ok = ExamineMinimum(*fMinimum); - //fMinimum = 0; + //fMinimum = 0; // delete trace object if it was constructed if (traceObj) { delete traceObj; } - return ok; + return ok; } -bool Minuit2Minimizer::ExamineMinimum(const ROOT::Minuit2::FunctionMinimum & min) { - /// study the function minimum - - // debug ( print all the states) - int debugLevel = PrintLevel(); - if (debugLevel >= 3) { - +bool Minuit2Minimizer::ExamineMinimum(const ROOT::Minuit2::FunctionMinimum & min) { + /// study the function minimum + + // debug ( print all the states) + int debugLevel = PrintLevel(); + if (debugLevel >= 3) { + const std::vector<ROOT::Minuit2::MinimumState>& iterationStates = min.States(); std::cout << "Number of iterations " << iterationStates.size() << std::endl; for (unsigned int i = 0; i < iterationStates.size(); ++i) { - //std::cout << iterationStates[i] << std::endl; + //std::cout << iterationStates[i] << std::endl; const ROOT::Minuit2::MinimumState & st = iterationStates[i]; std::cout << "----------> Iteration " << i << std::endl; int pr = std::cout.precision(12); @@ -541,7 +541,7 @@ bool Minuit2Minimizer::ExamineMinimum(const ROOT::Minuit2::FunctionMinimum & mi std::cout.precision(pr); std::cout << " Error matrix change = " << st.Error().Dcovar() << std::endl; std::cout << " Parameters : "; - // need to transform from internal to external + // need to transform from internal to external for (int j = 0; j < st.size() ; ++j) std::cout << " p" << j << " = " << fState.Int2ext( j, st.Vec()(j) ); std::cout << std::endl; } @@ -549,41 +549,41 @@ bool Minuit2Minimizer::ExamineMinimum(const ROOT::Minuit2::FunctionMinimum & mi fStatus = 0; std::string txt; - if (min.HasMadePosDefCovar() ) { + if (min.HasMadePosDefCovar() ) { txt = "Covar was made pos def"; - fStatus = 1; + fStatus = 1; } - if (min.HesseFailed() ) { + if (min.HesseFailed() ) { txt = "Hesse is not valid"; - fStatus = 2; + fStatus = 2; } - if (min.IsAboveMaxEdm() ) { - txt = "Edm is above max"; - fStatus = 3; + if (min.IsAboveMaxEdm() ) { + txt = "Edm is above max"; + fStatus = 3; } - if (min.HasReachedCallLimit() ) { + if (min.HasReachedCallLimit() ) { txt = "Reached call limit"; fStatus = 4; } - + bool validMinimum = min.IsValid(); - if (validMinimum) { + if (validMinimum) { // print a warning message in case something is not ok if (fStatus != 0 && debugLevel > 0) MN_INFO_MSG2("Minuit2Minimizer::Minimize",txt); } - else { + else { // minimum is not valid when state is not valid and edm is over max or has passed call limits - if (fStatus == 0) { + if (fStatus == 0) { // this should not happen - txt = "unknown failure"; + txt = "unknown failure"; fStatus = 5; } std::string msg = "Minimization did NOT converge, " + txt; - MN_INFO_MSG2("Minuit2Minimizer::Minimize",msg); + MN_INFO_MSG2("Minuit2Minimizer::Minimize",msg); } - if (debugLevel >= 1) PrintResults(); + if (debugLevel >= 1) PrintResults(); return validMinimum; } @@ -593,48 +593,48 @@ void Minuit2Minimizer::PrintResults() { if (!fMinimum) return; if (fMinimum->IsValid() ) { // valid minimum - std::cout << "Minuit2Minimizer : Valid minimum - status = " << fStatus << std::endl; + std::cout << "Minuit2Minimizer : Valid minimum - status = " << fStatus << std::endl; int pr = std::cout.precision(18); std::cout << "FVAL = " << fState.Fval() << std::endl; std::cout << "Edm = " << fState.Edm() << std::endl; std::cout.precision(pr); std::cout << "Nfcn = " << fState.NFcn() << std::endl; for (unsigned int i = 0; i < fState.MinuitParameters().size(); ++i) { - const MinuitParameter & par = fState.Parameter(i); + const MinuitParameter & par = fState.Parameter(i); std::cout << par.Name() << "\t = " << par.Value() << "\t "; if (par.IsFixed() ) std::cout << "(fixed)" << std::endl; else if (par.IsConst() ) std::cout << "(const)" << std::endl; - else if (par.HasLimits() ) - std::cout << "+/- " << par.Error() << "\t(limited)"<< std::endl; - else - std::cout << "+/- " << par.Error() << std::endl; + else if (par.HasLimits() ) + std::cout << "+/- " << par.Error() << "\t(limited)"<< std::endl; + else + std::cout << "+/- " << par.Error() << std::endl; } } - else { - std::cout << "Minuit2Minimizer : Invalid Minimum - status = " << fStatus << std::endl; + else { + std::cout << "Minuit2Minimizer : Invalid Minimum - status = " << fStatus << std::endl; std::cout << "FVAL = " << fState.Fval() << std::endl; std::cout << "Edm = " << fState.Edm() << std::endl; std::cout << "Nfcn = " << fState.NFcn() << std::endl; } } -const double * Minuit2Minimizer::X() const { - // return values at minimum +const double * Minuit2Minimizer::X() const { + // return values at minimum const std::vector<MinuitParameter> & paramsObj = fState.MinuitParameters(); if (paramsObj.size() == 0) return 0; assert(fDim == paramsObj.size()); // be careful for multiple calls of this function. I will redo an allocation here // only when size of vectors has changed (e.g. after a new minimization) if (fValues.size() != fDim) fValues.resize(fDim); - for (unsigned int i = 0; i < fDim; ++i) { + for (unsigned int i = 0; i < fDim; ++i) { fValues[i] = paramsObj[i].Value(); } - return &fValues.front(); + return &fValues.front(); } -const double * Minuit2Minimizer::Errors() const { +const double * Minuit2Minimizer::Errors() const { // return error at minimum (set to zero for fixed and constant params) const std::vector<MinuitParameter> & paramsObj = fState.MinuitParameters(); if (paramsObj.size() == 0) return 0; @@ -642,49 +642,49 @@ const double * Minuit2Minimizer::Errors() const { // be careful for multiple calls of this function. I will redo an allocation here // only when size of vectors has changed (e.g. after a new minimization) if (fErrors.size() != fDim) fErrors.resize( fDim ); - for (unsigned int i = 0; i < fDim; ++i) { - const MinuitParameter & par = paramsObj[i]; - if (par.IsFixed() || par.IsConst() ) - fErrors[i] = 0; - else + for (unsigned int i = 0; i < fDim; ++i) { + const MinuitParameter & par = paramsObj[i]; + if (par.IsFixed() || par.IsConst() ) + fErrors[i] = 0; + else fErrors[i] = par.Error(); } - return &fErrors.front(); + return &fErrors.front(); } -double Minuit2Minimizer::CovMatrix(unsigned int i, unsigned int j) const { +double Minuit2Minimizer::CovMatrix(unsigned int i, unsigned int j) const { // get value of covariance matrices (transform from external to internal indices) - if ( i >= fDim || i >= fDim) return 0; + if ( i >= fDim || i >= fDim) return 0; if ( !fState.HasCovariance() ) return 0; // no info available when minimization has failed - if (fState.Parameter(i).IsFixed() || fState.Parameter(i).IsConst() ) return 0; - if (fState.Parameter(j).IsFixed() || fState.Parameter(j).IsConst() ) return 0; - unsigned int k = fState.IntOfExt(i); - unsigned int l = fState.IntOfExt(j); - return fState.Covariance()(k,l); + if (fState.Parameter(i).IsFixed() || fState.Parameter(i).IsConst() ) return 0; + if (fState.Parameter(j).IsFixed() || fState.Parameter(j).IsConst() ) return 0; + unsigned int k = fState.IntOfExt(i); + unsigned int l = fState.IntOfExt(j); + return fState.Covariance()(k,l); } -bool Minuit2Minimizer::GetCovMatrix(double * cov) const { - // get value of covariance matrices +bool Minuit2Minimizer::GetCovMatrix(double * cov) const { + // get value of covariance matrices if ( !fState.HasCovariance() ) return false; // no info available when minimization has failed for (unsigned int i = 0; i < fDim; ++i) { if (fState.Parameter(i).IsFixed() || fState.Parameter(i).IsConst() ) { - for (unsigned int j = 0; j < fDim; ++j) { cov[i*fDim + j] = 0; } - } - else + for (unsigned int j = 0; j < fDim; ++j) { cov[i*fDim + j] = 0; } + } + else { - unsigned int l = fState.IntOfExt(i); - for (unsigned int j = 0; j < fDim; ++j) { + unsigned int l = fState.IntOfExt(i); + for (unsigned int j = 0; j < fDim; ++j) { // could probably speed up this loop (if needed) int k = i*fDim + j; - if (fState.Parameter(j).IsFixed() || fState.Parameter(j).IsConst() ) - cov[k] = 0; + if (fState.Parameter(j).IsFixed() || fState.Parameter(j).IsConst() ) + cov[k] = 0; else { // need to transform from external to internal indices) // for taking care of the removed fixed row/columns in the Minuit2 representation - unsigned int m = fState.IntOfExt(j); - cov[k] = fState.Covariance()(l,m); + unsigned int m = fState.IntOfExt(j); + cov[k] = fState.Covariance()(l,m); } } } @@ -692,26 +692,26 @@ bool Minuit2Minimizer::GetCovMatrix(double * cov) const { return true; } -bool Minuit2Minimizer::GetHessianMatrix(double * hess) const { +bool Minuit2Minimizer::GetHessianMatrix(double * hess) const { // get value of Hessian matrix // this is the second derivative matrices if ( !fState.HasCovariance() ) return false; // no info available when minimization has failed for (unsigned int i = 0; i < fDim; ++i) { if (fState.Parameter(i).IsFixed() || fState.Parameter(i).IsConst() ) { - for (unsigned int j = 0; j < fDim; ++j) { hess[i*fDim + j] = 0; } - } - else { - unsigned int l = fState.IntOfExt(i); - for (unsigned int j = 0; j < fDim; ++j) { + for (unsigned int j = 0; j < fDim; ++j) { hess[i*fDim + j] = 0; } + } + else { + unsigned int l = fState.IntOfExt(i); + for (unsigned int j = 0; j < fDim; ++j) { // could probably speed up this loop (if needed) int k = i*fDim + j; - if (fState.Parameter(j).IsFixed() || fState.Parameter(j).IsConst() ) - hess[k] = 0; - else { + if (fState.Parameter(j).IsFixed() || fState.Parameter(j).IsConst() ) + hess[k] = 0; + else { // need to transform from external to internal indices) // for taking care of the removed fixed row/columns in the Minuit2 representation - unsigned int m = fState.IntOfExt(j); - hess[k] = fState.Hessian()(l,m); + unsigned int m = fState.IntOfExt(j); + hess[k] = fState.Hessian()(l,m); } } } @@ -721,76 +721,76 @@ bool Minuit2Minimizer::GetHessianMatrix(double * hess) const { } -double Minuit2Minimizer::Correlation(unsigned int i, unsigned int j) const { - // get correlation between parameter i and j - if ( i >= fDim || i >= fDim) return 0; +double Minuit2Minimizer::Correlation(unsigned int i, unsigned int j) const { + // get correlation between parameter i and j + if ( i >= fDim || i >= fDim) return 0; if ( !fState.HasCovariance() ) return 0; // no info available when minimization has failed - if (fState.Parameter(i).IsFixed() || fState.Parameter(i).IsConst() ) return 0; - if (fState.Parameter(j).IsFixed() || fState.Parameter(j).IsConst() ) return 0; - unsigned int k = fState.IntOfExt(i); - unsigned int l = fState.IntOfExt(j); - double cij = fState.IntCovariance()(k,l); + if (fState.Parameter(i).IsFixed() || fState.Parameter(i).IsConst() ) return 0; + if (fState.Parameter(j).IsFixed() || fState.Parameter(j).IsConst() ) return 0; + unsigned int k = fState.IntOfExt(i); + unsigned int l = fState.IntOfExt(j); + double cij = fState.IntCovariance()(k,l); double tmp = std::sqrt( std::abs ( fState.IntCovariance()(k,k) * fState.IntCovariance()(l,l) ) ); - if (tmp > 0 ) return cij/tmp; - return 0; + if (tmp > 0 ) return cij/tmp; + return 0; } -double Minuit2Minimizer::GlobalCC(unsigned int i) const { - // get global correlation coefficient for the parameter i. This is a number between zero and one which gives - // the correlation between the i-th parameter and that linear combination of all other parameters which +double Minuit2Minimizer::GlobalCC(unsigned int i) const { + // get global correlation coefficient for the parameter i. This is a number between zero and one which gives + // the correlation between the i-th parameter and that linear combination of all other parameters which // is most strongly correlated with i. - if ( i >= fDim || i >= fDim) return 0; + if ( i >= fDim || i >= fDim) return 0; // no info available when minimization has failed or has some problems - if ( !fState.HasGlobalCC() ) return 0; - if (fState.Parameter(i).IsFixed() || fState.Parameter(i).IsConst() ) return 0; - unsigned int k = fState.IntOfExt(i); - return fState.GlobalCC().GlobalCC()[k]; + if ( !fState.HasGlobalCC() ) return 0; + if (fState.Parameter(i).IsFixed() || fState.Parameter(i).IsConst() ) return 0; + unsigned int k = fState.IntOfExt(i); + return fState.GlobalCC().GlobalCC()[k]; } -bool Minuit2Minimizer::GetMinosError(unsigned int i, double & errLow, double & errUp, int runopt) { +bool Minuit2Minimizer::GetMinosError(unsigned int i, double & errLow, double & errUp, int runopt) { // return the minos error for parameter i // if a minimum does not exist an error is returned // runopt is a flag which specifies if only lower or upper error needs to be run // if runopt = 0 both, = 1 only lower, + 2 only upper errors - errLow = 0; errUp = 0; + errLow = 0; errUp = 0; bool runLower = runopt != 2; bool runUpper = runopt != 1; assert( fMinuitFCN ); - // need to know if parameter is const or fixed - if ( fState.Parameter(i).IsConst() || fState.Parameter(i).IsFixed() ) { - return false; + // need to know if parameter is const or fixed + if ( fState.Parameter(i).IsConst() || fState.Parameter(i).IsFixed() ) { + return false; } - int debugLevel = PrintLevel(); + int debugLevel = PrintLevel(); // internal minuit messages MnPrint::SetLevel( debugLevel ); - // to run minos I need function minimum class + // to run minos I need function minimum class // redo minimization from current state -// ROOT::Minuit2::FunctionMinimum min = +// ROOT::Minuit2::FunctionMinimum min = // GetMinimizer()->Minimize(*GetFCN(),fState, ROOT::Minuit2::MnStrategy(strategy), MaxFunctionCalls(), Tolerance()); // fState = min.UserState(); - if (fMinimum == 0) { + if (fMinimum == 0) { MN_ERROR_MSG("Minuit2Minimizer::GetMinosErrors: failed - no function minimum existing"); return false; } - - if (!fMinimum->IsValid() ) { + + if (!fMinimum->IsValid() ) { MN_ERROR_MSG("Minuit2Minimizer::MINOS failed due to invalid function minimum"); return false; } fMinuitFCN->SetErrorDef(ErrorDef() ); // if error def has been changed update it in FunctionMinimum - if (ErrorDef() != fMinimum->Up() ) + if (ErrorDef() != fMinimum->Up() ) fMinimum->SetErrorDef(ErrorDef() ); // switch off Minuit2 printing - int prev_level = (PrintLevel() <= 0 ) ? TurnOffPrintInfoLevel() : -2; + int prev_level = (PrintLevel() <= 0 ) ? TurnOffPrintInfoLevel() : -2; // set the precision if needed if (Precision() > 0) fState.SetPrecision(Precision()); @@ -798,119 +798,122 @@ bool Minuit2Minimizer::GetMinosError(unsigned int i, double & errLow, double & e ROOT::Minuit2::MnMinos minos( *fMinuitFCN, *fMinimum); - // run MnCross + // run MnCross MnCross low; MnCross up; - int maxfcn = MaxFunctionCalls(); + int maxfcn = MaxFunctionCalls(); double tol = Tolerance(); const char * par_name = fState.Name(i); // now input tolerance for migrad calls inside Minos (MnFunctionCross) - // before it was fixed to 0.05 + // before it was fixed to 0.05 // cut off too small tolerance (they are not needed) tol = std::max(tol, 0.01); - - if (PrintLevel() >=1) { + + if (PrintLevel() >=1) { // print the real number of maxfcn used (defined in MnMinos) - int maxfcn_used = maxfcn; - if (maxfcn_used == 0) { + int maxfcn_used = maxfcn; + if (maxfcn_used == 0) { int nvar = fState.VariableParameters(); maxfcn_used = 2*(nvar+1)*(200 + 100*nvar + 5*nvar*nvar); } std::cout << "Minuit2Minimizer::GetMinosError for parameter " << i << " " << par_name - << " using max-calls " << maxfcn_used << ", tolerance " << tol << std::endl; + << " using max-calls " << maxfcn_used << ", tolerance " << tol << std::endl; } if (runLower) low = minos.Loval(i,maxfcn,tol); if (runUpper) up = minos.Upval(i,maxfcn,tol); - + ROOT::Minuit2::MinosError me(i, fMinimum->UserState().Value(i),low, up); if (prev_level > -2) RestoreGlobalPrintLevel(prev_level); - // debug result of Minos + // debug result of Minos // print error message in Minos - + // Note that the only invalid condition can happen when the (npar-1) minimization fails + // The error is also invalid when the maximum number of calls is reached or a new function minimum is found + // in case of the parameter at the limit the error is not ivalid. + // When the error is invalid the returned error is the Hessian error. if (debugLevel >= 1) { - if (runLower) { - if (!me.LowerValid() ) - std::cout << "Minos: Invalid lower error for parameter " << par_name << std::endl; - if(me.AtLowerLimit()) + if (runLower) { + if (!me.LowerValid() ) + std::cout << "Minos: Invalid lower error for parameter " << par_name << std::endl; + if(me.AtLowerLimit()) std::cout << "Minos: Parameter : " << par_name << " is at Lower limit."<<std::endl; if(me.AtLowerMaxFcn()) - std::cout << "Minos: Maximum number of function calls exceeded when running for lower error" <<std::endl; + std::cout << "Minos: Maximum number of function calls exceeded when running for lower error" <<std::endl; if(me.LowerNewMin() ) - std::cout << "Minos: New Minimum found while running Minos for lower error" <<std::endl; + std::cout << "Minos: New Minimum found while running Minos for lower error" <<std::endl; - if (debugLevel > 1) std::cout << "Minos: Lower error for parameter " << par_name << " : " << me.Lower() << std::endl; + if (debugLevel > 1) std::cout << "Minos: Lower error for parameter " << par_name << " : " << me.Lower() << std::endl; } - if (runUpper) { - if (!me.UpperValid() ) - std::cout << "Minos: Invalid upper error for parameter " << par_name << std::endl; - if(me.AtUpperLimit()) + if (runUpper) { + if (!me.UpperValid() ) + std::cout << "Minos: Invalid upper error for parameter " << par_name << std::endl; + if(me.AtUpperLimit()) std::cout << "Minos: Parameter " << par_name << " is at Upper limit."<<std::endl; if(me.AtUpperMaxFcn()) - std::cout << "Minos: Maximum number of function calls exceeded when running for upper error" <<std::endl; + std::cout << "Minos: Maximum number of function calls exceeded when running for upper error" <<std::endl; if(me.UpperNewMin() ) - std::cout << "Minos: New Minimum found while running Minos for upper error" <<std::endl; + std::cout << "Minos: New Minimum found while running Minos for upper error" <<std::endl; if (debugLevel > 1) std::cout << "Minos: Upper error for parameter " << par_name << " : " << me.Upper() << std::endl; } - + } - bool lowerInvalid = (runLower && !me.LowerValid() ); + bool lowerInvalid = (runLower && !me.LowerValid() ); bool upperInvalid = (runUpper && !me.UpperValid() ); - int mstatus = 0; - if (lowerInvalid || upperInvalid ) { - // set status accroding to bit - // bit 1: lower invalid Minos errors + int mstatus = 0; + if (lowerInvalid || upperInvalid ) { + // set status accroding to bit + // bit 1: lower invalid Minos errors // bit 2: uper invalid Minos error // bit 3: invalid because max FCN // bit 4 : invalid because a new minimum has been found - if (lowerInvalid) { + if (lowerInvalid) { mstatus |= 1; - if (me.AtLowerMaxFcn() ) mstatus |= 4; - if (me.LowerNewMin() ) mstatus |= 8; + if (me.AtLowerMaxFcn() ) mstatus |= 4; + if (me.LowerNewMin() ) mstatus |= 8; } - if(upperInvalid) { + if(upperInvalid) { mstatus |= 3; - if (me.AtUpperMaxFcn() ) mstatus |= 4; - if (me.UpperNewMin() ) mstatus |= 8; + if (me.AtUpperMaxFcn() ) mstatus |= 4; + if (me.UpperNewMin() ) mstatus |= 8; } - //std::cout << "Error running Minos for parameter " << i << std::endl; - fStatus += 10*mstatus; + //std::cout << "Error running Minos for parameter " << i << std::endl; + fStatus += 10*mstatus; } - + errLow = me.Lower(); errUp = me.Upper(); - bool isValid = (runLower && me.LowerValid() ) || (runUpper && me.UpperValid() ); - return isValid; -} + bool isValid = (runLower && me.LowerValid() ) || (runUpper && me.UpperValid() ); + return isValid; +} -bool Minuit2Minimizer::Scan(unsigned int ipar, unsigned int & nstep, double * x, double * y, double xmin, double xmax) { +bool Minuit2Minimizer::Scan(unsigned int ipar, unsigned int & nstep, double * x, double * y, double xmin, double xmax) { // scan a parameter (variable) around the minimum value - // the parameters must have been set before + // the parameters must have been set before // if xmin=0 && xmax == 0 by default scan around 2 sigma of the error // if the errors are also zero then scan from min and max of parameter range - if (!fMinuitFCN) { + if (!fMinuitFCN) { MN_ERROR_MSG2("Minuit2Minimizer::Scan"," Function must be set before using Scan"); return false; } - - if ( ipar > fState.MinuitParameters().size() ) { + + if ( ipar > fState.MinuitParameters().size() ) { MN_ERROR_MSG2("Minuit2Minimizer::Scan"," Invalid number. Minimizer variables must be set before using Scan"); return false; } // switch off Minuit2 printing - int prev_level = (PrintLevel() <= 0 ) ? TurnOffPrintInfoLevel() : -2; + int prev_level = (PrintLevel() <= 0 ) ? TurnOffPrintInfoLevel() : -2; MnPrint::SetLevel( PrintLevel() ); @@ -919,102 +922,111 @@ bool Minuit2Minimizer::Scan(unsigned int ipar, unsigned int & nstep, double * x, if (Precision() > 0) fState.SetPrecision(Precision()); MnParameterScan scan( *fMinuitFCN, fState.Parameters() ); - double amin = scan.Fval(); // fcn value of the function before scan + double amin = scan.Fval(); // fcn value of the function before scan // first value is param value std::vector<std::pair<double, double> > result = scan(ipar, nstep-1, xmin, xmax); if (prev_level > -2) RestoreGlobalPrintLevel(prev_level); - if (result.size() != nstep) { + if (result.size() != nstep) { MN_ERROR_MSG2("Minuit2Minimizer::Scan"," Invalid result from MnParameterScan"); - return false; + return false; } // sort also the returned points in x std::sort(result.begin(), result.end() ); - for (unsigned int i = 0; i < nstep; ++i ) { - x[i] = result[i].first; - y[i] = result[i].second; + for (unsigned int i = 0; i < nstep; ++i ) { + x[i] = result[i].first; + y[i] = result[i].second; } - // what to do if a new minimum has been found ? + // what to do if a new minimum has been found ? // use that as new minimum - if (scan.Fval() < amin ) { - if (PrintLevel() > 0) MN_INFO_MSG2("Minuit2Minimizer::Scan","A new minimum has been found"); + if (scan.Fval() < amin ) { + MN_INFO_MSG2("Minuit2Minimizer::Scan","A new minimum has been found"); fState.SetValue(ipar, scan.Parameters().Value(ipar) ); - + } - return true; + return true; } bool Minuit2Minimizer::Contour(unsigned int ipar, unsigned int jpar, unsigned int & npoints, double * x, double * y) { // contour plot for parameter i and j // need a valid FunctionMinimum otherwise exits - if (fMinimum == 0) { + if (fMinimum == 0) { MN_ERROR_MSG2("Minuit2Minimizer::Contour"," no function minimum existing. Must minimize function before"); return false; } - if (!fMinimum->IsValid() ) { + if (!fMinimum->IsValid() ) { MN_ERROR_MSG2("Minuit2Minimizer::Contour","Invalid function minimum"); return false; } - assert(fMinuitFCN); + assert(fMinuitFCN); fMinuitFCN->SetErrorDef(ErrorDef() ); // if error def has been changed update it in FunctionMinimum - if (ErrorDef() != fMinimum->Up() ) + if (ErrorDef() != fMinimum->Up() ) { fMinimum->SetErrorDef(ErrorDef() ); + } + + if ( PrintLevel() >= 1 ) + MN_INFO_VAL2("Minuit2Minimizer::Contour - computing contours - ",ErrorDef()); // switch off Minuit2 printing (for level of 0,1) - int prev_level = (PrintLevel() <= 1 ) ? TurnOffPrintInfoLevel() : -2; + int prev_level = (PrintLevel() <= 1 ) ? TurnOffPrintInfoLevel() : -2; - MnPrint::SetLevel( PrintLevel() ); + // decrease print-level to have too many messages + MnPrint::SetLevel( PrintLevel() -1 ); // set the precision if needed if (Precision() > 0) fState.SetPrecision(Precision()); - // eventually one should specify tolerance in contours - MnContours contour(*fMinuitFCN, *fMinimum, Strategy() ); - + // eventually one should specify tolerance in contours + MnContours contour(*fMinuitFCN, *fMinimum, Strategy() ); + if (prev_level > -2) RestoreGlobalPrintLevel(prev_level); + // compute the contour std::vector<std::pair<double,double> > result = contour(ipar,jpar, npoints); - if (result.size() != npoints) { + if (result.size() != npoints) { MN_ERROR_MSG2("Minuit2Minimizer::Contour"," Invalid result from MnContours"); - return false; + return false; } - for (unsigned int i = 0; i < npoints; ++i ) { - x[i] = result[i].first; - y[i] = result[i].second; + for (unsigned int i = 0; i < npoints; ++i ) { + x[i] = result[i].first; + y[i] = result[i].second; } + // restore print level + MnPrint::SetLevel( PrintLevel() ); + return true; - + } -bool Minuit2Minimizer::Hesse( ) { +bool Minuit2Minimizer::Hesse( ) { // find Hessian (full second derivative calculations) // the contained state will be updated with the Hessian result - // in case a function minimum exists and is valid the result will be + // in case a function minimum exists and is valid the result will be // appended in the function minimum - if (!fMinuitFCN) { + if (!fMinuitFCN) { MN_ERROR_MSG2("Minuit2Minimizer::Hesse","FCN function has not been set"); - return false; + return false; } int strategy = Strategy(); - int maxfcn = MaxFunctionCalls(); + int maxfcn = MaxFunctionCalls(); // switch off Minuit2 printing - int prev_level = (PrintLevel() <= 0 ) ? TurnOffPrintInfoLevel() : -2; + int prev_level = (PrintLevel() <= 0 ) ? TurnOffPrintInfoLevel() : -2; MnPrint::SetLevel( PrintLevel() ); @@ -1023,65 +1035,87 @@ bool Minuit2Minimizer::Hesse( ) { ROOT::Minuit2::MnHesse hesse( strategy ); + // case when function minimum exists - if (fMinimum ) { + if (fMinimum ) { + + // if (PrintLevel() >= 3) { + // std::cout << "Minuit2Minimizer::Hesse - State before running Hesse " << std::endl; + // std::cout << fState << std::endl; + // } + // run hesse and function minimum will be updated with Hesse result - hesse( *fMinuitFCN, *fMinimum, maxfcn ); - fState = fMinimum->UserState(); + hesse( *fMinuitFCN, *fMinimum, maxfcn ); + // update user state + fState = fMinimum->UserState(); } - else { + else { // run Hesse on point stored in current state (independent of function minimum validity) - // (x == 0) - fState = hesse( *fMinuitFCN, fState, maxfcn); + // (x == 0) + fState = hesse( *fMinuitFCN, fState, maxfcn); } if (prev_level > -2) RestoreGlobalPrintLevel(prev_level); - if (PrintLevel() >= 3) { - std::cout << "State returned from Hesse " << std::endl; - std::cout << fState << std::endl; + if (PrintLevel() >= 3) { + std::cout << "Minuit2Minimizer::Hesse - State returned from Hesse " << std::endl; + std::cout << fState << std::endl; } - if (!fState.HasCovariance() ) { + int covStatus = fState.CovarianceStatus(); + std::string covStatusType = "not valid"; + if (covStatus == 1) covStatusType = "approximate"; + if (covStatus == 2) covStatusType = "full but made positive defined"; + if (covStatus == 3) covStatusType = "accurate"; + + if (!fState.HasCovariance() ) { // if false means error is not valid and this is due to a failure in Hesse - if (PrintLevel() > 0) MN_INFO_MSG2("Minuit2Minimizer::Hesse","Hesse failed "); - // update minimizer error status + // update minimizer error status int hstatus = 4; // information on error state can be retrieved only if fMinimum is available - if (fMinimum) { + if (fMinimum) { if (fMinimum->Error().HesseFailed() ) hstatus = 1; if (fMinimum->Error().InvertFailed() ) hstatus = 2; else if (!(fMinimum->Error().IsPosDef()) ) hstatus = 3; } - fStatus += 100*hstatus; - return false; + if (PrintLevel() > 0) { + std::string msg = "Hesse failed - matrix is " + covStatusType; + MN_INFO_MSG2("Minuit2Minimizer::Hesse",msg); + MN_INFO_VAL2("MInuit2Minimizer::Hesse",hstatus); + } + fStatus += 100*hstatus; + return false; + } + if (PrintLevel() > 0) { + std::string msg = "Hesse is valid - matrix is " + covStatusType; + MN_INFO_MSG2("Minuit2Minimizer::Hesse",msg); } - return true; + return true; } -int Minuit2Minimizer::CovMatrixStatus() const { - // return status of covariance matrix - //-1 - not available (inversion failed or Hesse failed) +int Minuit2Minimizer::CovMatrixStatus() const { + // return status of covariance matrix + //-1 - not available (inversion failed or Hesse failed) // 0 - available but not positive defined // 1 - covariance only approximate - // 2 full matrix but forced pos def - // 3 full accurate matrix + // 2 full matrix but forced pos def + // 3 full accurate matrix if (fMinimum) { - // case a function minimum is available - if (fMinimum->HasAccurateCovar() ) return 3; - else if (fMinimum->HasMadePosDefCovar() ) return 2; - else if (fMinimum->HasValidCovariance() ) return 1; - else if (fMinimum->HasCovariance() ) return 0; + // case a function minimum is available + if (fMinimum->HasAccurateCovar() ) return 3; + else if (fMinimum->HasMadePosDefCovar() ) return 2; + else if (fMinimum->HasValidCovariance() ) return 1; + else if (fMinimum->HasCovariance() ) return 0; return -1; } - else { + else { // case fMinimum is not available - use state information return fState.CovarianceStatus(); } - return 0; + return 0; } void Minuit2Minimizer::SetTraceObject(MnTraceObject & obj) { @@ -1090,12 +1124,12 @@ void Minuit2Minimizer::SetTraceObject(MnTraceObject & obj) { fMinimizer->Builder().SetTraceObject(obj); } -void Minuit2Minimizer::SetStorageLevel(int level) { +void Minuit2Minimizer::SetStorageLevel(int level) { // set storage level if (!fMinimizer) return; fMinimizer->Builder().SetStorageLevel(level); } - + } // end namespace Minuit2 } // end namespace ROOT diff --git a/ThirdParty/RootMinimizers/src/Minuit2/MnApplication.cxx b/ThirdParty/RootMinimizers/src/Minuit2/MnApplication.cxx index 0bf48609b32bc407110e316f6e9861de07f08d27..5e502b33a12d1e1bdf9051ede5a5f372180816d1 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/MnApplication.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/MnApplication.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -14,7 +14,7 @@ #ifdef DEBUG -#include "Minuit2/MnPrint.h" +#include "Minuit2/MnPrint.h" #endif namespace ROOT { @@ -23,25 +23,25 @@ namespace ROOT { // constructor from non-gradient functions -MnApplication::MnApplication(const FCNBase& fcn, const MnUserParameterState& state, const MnStrategy& stra, unsigned int nfcn) : - fFCN(fcn), fState(state), fStrategy(stra), fNumCall(nfcn), fUseGrad(false) +MnApplication::MnApplication(const FCNBase& fcn, const MnUserParameterState& state, const MnStrategy& stra, unsigned int nfcn) : + fFCN(fcn), fState(state), fStrategy(stra), fNumCall(nfcn), fUseGrad(false) {} // constructor from functions -MnApplication::MnApplication(const FCNGradientBase& fcn, const MnUserParameterState& state, const MnStrategy& stra, unsigned int nfcn) : - fFCN(fcn), fState(state), fStrategy(stra), fNumCall(nfcn), fUseGrad(true) +MnApplication::MnApplication(const FCNGradientBase& fcn, const MnUserParameterState& state, const MnStrategy& stra, unsigned int nfcn) : + fFCN(fcn), fState(state), fStrategy(stra), fNumCall(nfcn), fUseGrad(true) {} FunctionMinimum MnApplication::operator()(unsigned int maxfcn, double toler) { - // constructor from macfcn calls and tolerance - + // constructor from macfcn calls and tolerance + assert(fState.IsValid()); unsigned int npar = VariableParameters(); // assert(npar > 0); if(maxfcn == 0) maxfcn = 200 + 100*npar + 5*npar*npar; - const FCNBase * fcn = &(Fcnbase()); + const FCNBase * fcn = &(Fcnbase()); if (fUseGrad) { // case of Gradient FCN implemented via the FCNGradientBase interface const FCNGradientBase * gfcn = dynamic_cast<const FCNGradientBase *>(fcn); @@ -52,7 +52,7 @@ FunctionMinimum MnApplication::operator()(unsigned int maxfcn, double toler) { fState = min.UserState(); return min; } - else { + else { // no gradient FunctionMinimum min = Minimizer().Minimize( *fcn, fState, fStrategy, maxfcn, toler); fNumCall += min.NFcn(); @@ -60,7 +60,7 @@ FunctionMinimum MnApplication::operator()(unsigned int maxfcn, double toler) { #ifdef DEBUG // std::cout << "Initial MIGRAD state is " << MnUserParameterState( min.States()[0], min.Up(), min.Seed().Trafo() ) << std::endl; - std::cout << "State resulting from Migrad. Total Function calls " << fNumCall << fState << std::endl; + std::cout << "State resulting from Migrad. Total Function calls " << fNumCall << fState << std::endl; const std::vector<ROOT::Minuit2::MinimumState>& iterationStates = min.States(); std::cout << "Number of iterations " << iterationStates.size() << std::endl; for (unsigned int i = 0; i < iterationStates.size(); ++i) { @@ -68,13 +68,13 @@ FunctionMinimum MnApplication::operator()(unsigned int maxfcn, double toler) { const ROOT::Minuit2::MinimumState & st = iterationStates[i]; std::cout << "----------> Iteration " << i << std::endl; int pr = std::cout.precision(18); - std::cout << " FVAL = " << st.Fval() + std::cout << " FVAL = " << st.Fval() << " Edm = " << st.Edm() << " Nfcn = " << st.NFcn() << std::endl; std::cout.precision(pr); - std::cout << " Error matrix change = " << st.Error().Dcovar() + std::cout << " Error matrix change = " << st.Error().Dcovar() << std::endl; std::cout << " Internal parameters : "; - for (int j = 0; j < st.size() ; ++j) + for (int j = 0; j < st.size() ; ++j) std::cout << " p" << j << " = " << st.Vec()(j); std::cout << std::endl; } @@ -93,7 +93,7 @@ const std::vector<MinuitParameter>& MnApplication::MinuitParameters() const { //access to parameters (row-wise) return fState.MinuitParameters(); } -//access to parameters and errors in column-wise representation +//access to parameters and errors in column-wise representation std::vector<double> MnApplication::Params() const {return fState.Params();} std::vector<double> MnApplication::Errors() const {return fState.Errors();} @@ -110,7 +110,7 @@ void MnApplication::Add(const char* name, double val, double err) { } void MnApplication::Add(const char* name, double val, double err, double low, double up) { - //add limited Parameter + //add limited Parameter fState.Add(name, val, err, low, up); } @@ -123,7 +123,7 @@ void MnApplication::Add(const char* name, double val) { void MnApplication::Fix(unsigned int i) {fState.Fix(i);} void MnApplication::Release(unsigned int i) {fState.Release(i);} void MnApplication::SetValue(unsigned int i, double val) { - // set value for parameter i + // set value for parameter i fState.SetValue(i, val); } void MnApplication::SetError(unsigned int i, double val) { @@ -175,7 +175,7 @@ unsigned int MnApplication::IntOfExt(unsigned int ext) const { // get internal index for external parameter with index ext return fState.IntOfExt(ext); } -unsigned int MnApplication::ExtOfInt(unsigned int internal) const { +unsigned int MnApplication::ExtOfInt(unsigned int internal) const { // get external index for internal parameter with index internal return fState.ExtOfInt(internal); } diff --git a/ThirdParty/RootMinimizers/src/Minuit2/MnContours.cxx b/ThirdParty/RootMinimizers/src/Minuit2/MnContours.cxx index 95fe3d77729951b50ca2ed9b97dc662fe7d45c9b..8386da2614ed28b5bf2de754dd510f369e211be9 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/MnContours.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/MnContours.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -17,7 +17,7 @@ #include "Minuit2/MinosError.h" #include "Minuit2/ContoursError.h" -#include "Minuit2/MnPrint.h" +#include "Minuit2/MnPrint.h" @@ -26,7 +26,7 @@ namespace ROOT { namespace Minuit2 { -void PrintContourPoint(const std::pair<double,double> & point) { +void PrintContourPoint(const std::pair<double,double> & point) { std::cout << "\t x = " << point.first << " y = " << point.second << std::endl; } @@ -42,21 +42,21 @@ ContoursError MnContours::Contour(unsigned int px, unsigned int py, unsigned int assert(npoints > 3); unsigned int maxcalls = 100*(npoints+5)*(fMinimum.UserState().VariableParameters()+1); unsigned int nfcn = 0; - + std::vector<std::pair<double,double> > result; result.reserve(npoints); std::vector<MnUserParameterState> states; - // double edmmax = 0.5*0.05*fFCN.Up()*1.e-3; + // double edmmax = 0.5*0.05*fFCN.Up()*1.e-3; + + //double toler = 0.05; + double toler = 0.1; // use same defaut value as in Minos - //double toler = 0.05; - double toler = 0.1; // use same defaut value as in Minos - //get first four points // std::cout<<"MnContours: get first 4 params."<<std::endl; MnMinos minos(fFCN, fMinimum, fStrategy); - + double valx = fMinimum.UserState().Value(px); double valy = fMinimum.UserState().Value(py); - + MinosError mex = minos.Minos(px); nfcn += mex.NFcn(); if(!mex.IsValid()) { @@ -64,7 +64,7 @@ ContoursError MnContours::Contour(unsigned int px, unsigned int py, unsigned int return ContoursError(px, py, result, mex, mex, nfcn); } std::pair<double,double> ex = mex(); - + MinosError mey = minos.Minos(py); nfcn += mey.NFcn(); if(!mey.IsValid()) { @@ -72,9 +72,9 @@ ContoursError MnContours::Contour(unsigned int px, unsigned int py, unsigned int return ContoursError(px, py, result, mex, mey, nfcn); } std::pair<double,double> ey = mey(); - + MnMigrad migrad(fFCN, fMinimum.UserState(), MnStrategy(std::max(0, int(fStrategy.Strategy()-1)))); - + migrad.Fix(px); migrad.SetValue(px, valx + ex.second); FunctionMinimum exy_up = migrad(); @@ -83,7 +83,7 @@ ContoursError MnContours::Contour(unsigned int px, unsigned int py, unsigned int MN_ERROR_VAL2("MnContours: unable to find Upper y Value for x Parameter",px); return ContoursError(px, py, result, mex, mey, nfcn); } - + migrad.SetValue(px, valx + ex.first); FunctionMinimum exy_lo = migrad(); nfcn += exy_lo.NFcn(); @@ -91,8 +91,8 @@ ContoursError MnContours::Contour(unsigned int px, unsigned int py, unsigned int MN_ERROR_VAL2("MnContours: unable to find Lower y Value for x Parameter",px); return ContoursError(px, py, result, mex, mey, nfcn); } - - + + MnMigrad migrad1(fFCN, fMinimum.UserState(), MnStrategy(std::max(0, int(fStrategy.Strategy()-1)))); migrad1.Fix(py); migrad1.SetValue(py, valy + ey.second); @@ -102,7 +102,7 @@ ContoursError MnContours::Contour(unsigned int px, unsigned int py, unsigned int MN_ERROR_VAL2("MnContours: unable to find Upper x Value for y Parameter",py); return ContoursError(px, py, result, mex, mey, nfcn); } - + migrad1.SetValue(py, valy + ey.first); FunctionMinimum eyx_lo = migrad1(); nfcn += eyx_lo.NFcn(); @@ -110,18 +110,18 @@ ContoursError MnContours::Contour(unsigned int px, unsigned int py, unsigned int MN_ERROR_VAL2("MnContours: unable to find Lower x Value for y Parameter",py); return ContoursError(px, py, result, mex, mey, nfcn); } - + double scalx = 1./(ex.second - ex.first); double scaly = 1./(ey.second - ey.first); - + result.push_back(std::pair<double,double>(valx + ex.first, exy_lo.UserState().Value(py))); result.push_back(std::pair<double,double>(eyx_lo.UserState().Value(px), valy + ey.first)); result.push_back(std::pair<double,double>(valx + ex.second, exy_up.UserState().Value(py))); result.push_back(std::pair<double,double>(eyx_up.UserState().Value(px), valy + ey.second)); - + MnUserParameterState upar = fMinimum.UserState(); - + // std::cout<<"MnContours: first 4 params finished."<<std::endl; int printLevel = MnPrint::Level(); @@ -131,25 +131,25 @@ ContoursError MnContours::Contour(unsigned int px, unsigned int py, unsigned int std::cout << "\t Parameter y is " << upar.Name(py) << std::endl; } - if (printLevel > 0) { + if (printLevel > 0) { for (unsigned int i = 0; i < 4; ++i) - PrintContourPoint(result[i] ); + PrintContourPoint(result[i] ); } - + upar.Fix(px); upar.Fix(py); - + std::vector<unsigned int> par(2); par[0] = px; par[1] = py; MnFunctionCross cross(fFCN, upar, fMinimum.Fval(), fStrategy); - + for(unsigned int i = 4; i < npoints; i++) { - + std::vector<std::pair<double,double> >::iterator idist1 = result.end()-1; std::vector<std::pair<double,double> >::iterator idist2 = result.begin(); double dx = idist1->first - (idist2)->first; double dy = idist1->second - (idist2)->second; double bigdis = scalx*scalx*dx*dx + scaly*scaly*dy*dy; - + for(std::vector<std::pair<double,double> >::iterator ipair = result.begin(); ipair != result.end()-1; ipair++) { double distx = ipair->first - (ipair+1)->first; double disty = ipair->second - (ipair+1)->second; @@ -160,18 +160,18 @@ ContoursError MnContours::Contour(unsigned int px, unsigned int py, unsigned int idist2 = ipair+1; } } - + double a1 = 0.5; double a2 = 0.5; double sca = 1.; - + L300: - + if(nfcn > maxcalls) { MN_ERROR_MSG("MnContours: maximum number of function calls exhausted."); return ContoursError(px, py, result, mex, mey, nfcn); } - + double xmidcr = a1*idist1->first + a2*(idist2)->first; double ymidcr = a1*idist1->second + a2*(idist2)->second; double xdir = (idist2)->second - idist1->second; @@ -181,7 +181,7 @@ L300: double ydircr = ydir/scalfac; std::vector<double> pmid(2); pmid[0] = xmidcr; pmid[1] = ymidcr; std::vector<double> pdir(2); pdir[0] = xdircr; pdir[1] = ydircr; - + MnCross opt = cross(par, pmid, pdir, toler, maxcalls); nfcn += opt.NFcn(); if(!opt.IsValid()) { @@ -198,7 +198,7 @@ L300: goto L300; } double aopt = opt.Value(); - if(idist2 == result.begin()) { + if(idist2 == result.begin()) { result.push_back(std::pair<double,double>(xmidcr+(aopt)*xdircr, ymidcr + (aopt)*ydircr)); if (printLevel > 0) PrintContourPoint( result.back() ); } @@ -206,8 +206,8 @@ L300: result.insert(idist2, std::pair<double,double>(xmidcr+(aopt)*xdircr, ymidcr + (aopt)*ydircr)); if (printLevel > 0) PrintContourPoint( *idist2 ); } - } - if (printLevel >0) + } + if (printLevel >0) std::cout << "MnContour: Number of contour points = " << result.size() << std::endl; return ContoursError(px, py, result, mex, mey, nfcn); diff --git a/ThirdParty/RootMinimizers/src/Minuit2/MnCovarianceSqueeze.cxx b/ThirdParty/RootMinimizers/src/Minuit2/MnCovarianceSqueeze.cxx index fbef0de4f5f2dfd74ca662c18ea9f97b31660e02..16dbe05bea9df560f133f8beaf061f9cf3dcef9c 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/MnCovarianceSqueeze.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/MnCovarianceSqueeze.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -12,7 +12,7 @@ #include "Minuit2/MinimumError.h" #if defined(DEBUG) || defined(WARNINGMSG) -#include "Minuit2/MnPrint.h" +#include "Minuit2/MnPrint.h" #endif @@ -22,21 +22,21 @@ namespace ROOT { MnUserCovariance MnCovarianceSqueeze::operator()(const MnUserCovariance& cov, unsigned int n) const { - // squeeze MnUserCovariance class - // MnUserCovariance contasins the error matrix. Need to invert first to get the hessian, then + // squeeze MnUserCovariance class + // MnUserCovariance contasins the error matrix. Need to invert first to get the hessian, then // after having squuezed the hessian, need to invert again to get the new error matrix assert(cov.Nrow() > 0); assert(n < cov.Nrow()); - + MnAlgebraicSymMatrix hess(cov.Nrow()); for(unsigned int i = 0; i < cov.Nrow(); i++) { for(unsigned int j = i; j < cov.Nrow(); j++) { hess(i,j) = cov(i,j); } } - + int ifail = Invert(hess); - + if(ifail != 0) { #ifdef WARNINGMSG MN_INFO_MSG("MnUserCovariance inversion failed; return diagonal matrix;"); @@ -49,9 +49,9 @@ MnUserCovariance MnCovarianceSqueeze::operator()(const MnUserCovariance& cov, un } return result; } - + MnAlgebraicSymMatrix squeezed = (*this)(hess, n); - + ifail = Invert(squeezed); if(ifail != 0) { #ifdef WARNINGMSG @@ -63,13 +63,13 @@ MnUserCovariance MnCovarianceSqueeze::operator()(const MnUserCovariance& cov, un } return result; } - + return MnUserCovariance(std::vector<double>(squeezed.Data(), squeezed.Data() + squeezed.size()), squeezed.Nrow()); } MinimumError MnCovarianceSqueeze::operator()(const MinimumError& err, unsigned int n) const { // squueze the minimum error class - // Remove index-row on the Hessian matrix and the get the new correct error matrix + // Remove index-row on the Hessian matrix and the get the new correct error matrix // (inverse of new Hessian) MnAlgebraicSymMatrix hess = err.Hessian(); MnAlgebraicSymMatrix squeezed = (*this)(hess, n); @@ -84,7 +84,7 @@ MinimumError MnCovarianceSqueeze::operator()(const MinimumError& err, unsigned i } return MinimumError(tmp, MinimumError::MnInvertFailed()); } - + return MinimumError(squeezed, err.Dcovar()); } @@ -92,7 +92,7 @@ MnAlgebraicSymMatrix MnCovarianceSqueeze::operator()(const MnAlgebraicSymMatrix& // squueze a symmetrix matrix (remove entire row and column n) assert(hess.Nrow() > 0); assert(n < hess.Nrow()); - + MnAlgebraicSymMatrix hs(hess.Nrow() - 1); for(unsigned int i = 0, j = 0; i < hess.Nrow(); i++) { if(i == n) continue; @@ -103,7 +103,7 @@ MnAlgebraicSymMatrix MnCovarianceSqueeze::operator()(const MnAlgebraicSymMatrix& } j++; } - + return hs; } diff --git a/ThirdParty/RootMinimizers/src/Minuit2/MnEigen.cxx b/ThirdParty/RootMinimizers/src/Minuit2/MnEigen.cxx index 04cfc5acf034354d5a158813348cdf77e45bf618..ba96a4a893e35e53e24b1ba3dc684c0c36b5b92c 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/MnEigen.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/MnEigen.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -20,14 +20,14 @@ LAVector eigenvalues(const LASymMatrix&); std::vector<double> MnEigen::operator()(const MnUserCovariance& covar) const { // wrapper to calculate eigenvalues of the covariance matrix using mneigen function - + LASymMatrix cov(covar.Nrow()); for(unsigned int i = 0; i < covar.Nrow(); i++) for(unsigned int j = i; j < covar.Nrow(); j++) cov(i,j) = covar(i,j); - + LAVector eigen = eigenvalues(cov); - + std::vector<double> result(eigen.Data(), eigen.Data()+covar.Nrow()); return result; } diff --git a/ThirdParty/RootMinimizers/src/Minuit2/MnFcn.cxx b/ThirdParty/RootMinimizers/src/Minuit2/MnFcn.cxx index 9b7230b7b03f1a030191b141e3ae7be526e0f00c..394975ae185519752466c88d27e87f83ec02231f 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/MnFcn.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/MnFcn.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * diff --git a/ThirdParty/RootMinimizers/src/Minuit2/MnFumiliMinimize.cxx b/ThirdParty/RootMinimizers/src/Minuit2/MnFumiliMinimize.cxx index b77e4a0d192c863cc5713e06d4c532d02b2e0ba9..027304ce41e092c931e425a4b5f47c98ee78c879 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/MnFumiliMinimize.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/MnFumiliMinimize.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -22,7 +22,7 @@ namespace ROOT { FunctionMinimum MnFumiliMinimize::operator()(unsigned int maxfcn, double toler) { // minimize using Fumili // need to reimplement otherwise base class method is done - + assert(fState.IsValid()); unsigned int npar = VariableParameters(); // assert(npar > 0); diff --git a/ThirdParty/RootMinimizers/src/Minuit2/MnFunctionCross.cxx b/ThirdParty/RootMinimizers/src/Minuit2/MnFunctionCross.cxx index 3c89ad9001309135dbee3e17a79feaf42869318e..e2fc65f87f10f49d1578da287a125a7066e5e56e 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/MnFunctionCross.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/MnFunctionCross.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -18,7 +18,7 @@ #include "Minuit2/MnMachinePrecision.h" //#define DEBUG -#include "Minuit2/MnPrint.h" +#include "Minuit2/MnPrint.h" namespace ROOT { @@ -27,15 +27,15 @@ namespace ROOT { -MnCross MnFunctionCross::operator()(const std::vector<unsigned int>& par, const std::vector<double>& pmid, +MnCross MnFunctionCross::operator()(const std::vector<unsigned int>& par, const std::vector<double>& pmid, const std::vector<double>& pdir, double tlr, unsigned int maxcalls) const { - // evaluate crossing point where function is equal to MIN + UP, + // evaluate crossing point where function is equal to MIN + UP, // with direction pdir from values pmid // tlr indicate tolerance and maxcalls maximum number of calls - + // double edmmax = 0.5*0.001*toler*fFCN.Up(); - - + + unsigned int npar = par.size(); unsigned int nfcn = 0; const MnMachinePrecision& prec = fState.Precision(); @@ -43,11 +43,11 @@ MnCross MnFunctionCross::operator()(const std::vector<unsigned int>& par, const double mgr_tlr = 0.5 * tlr; // to be consistent with F77 version (for default values of tlr which is 0.1) // other olerance values are fixed at 0.01 tlr = 0.01; - // convergence when F is within tlf of aim and next prediction - // of aopt is within tla of previous value of aopt + // convergence when F is within tlf of aim and next prediction + // of aopt is within tla of previous value of aopt double up = fFCN.Up(); - // for finding the point : - double tlf = tlr*up; + // for finding the point : + double tlf = tlr*up; double tla = tlr; unsigned int maxitr = 15; unsigned int ipt = 0; @@ -62,18 +62,18 @@ MnCross MnFunctionCross::operator()(const std::vector<unsigned int>& par, const #ifdef DEBUG - std::cout<<"MnFunctionCross for parameter "<<par.front()<< "fmin = " << aminsv + std::cout<<"MnFunctionCross for parameter "<<par.front()<< "fmin = " << aminsv << " contur value aim = (fmin + up) = " << aim << std::endl; #endif - + // find the largest allowed aulim double aulim = 100.; for(unsigned int i = 0; i < par.size(); i++) { unsigned int kex = par[i]; if(fState.Parameter(kex).HasLimits()) { - double zmid = pmid[i]; + double zmid = pmid[i]; double zdir = pdir[i]; if(fabs(zdir) < fState.Precision().Eps()) continue; // double zlim = 0.; @@ -91,44 +91,44 @@ MnCross MnFunctionCross::operator()(const std::vector<unsigned int>& par, const #ifdef DEBUG std::cout<<"Largest allowed aulim "<< aulim << std::endl; #endif - + if(aulim < aopt+tla) limset = true; - + MnMigrad migrad(fFCN, fState, MnStrategy(std::max(0, int(fStrategy.Strategy()-1)))); - + for(unsigned int i = 0; i < npar; i++) { #ifdef DEBUG - std::cout << "MnFunctionCross: Set value for " << par[i] << " to " << pmid[i] << std::endl; + std::cout << "MnFunctionCross: Set value for " << par[i] << " to " << pmid[i] << std::endl; #endif migrad.SetValue(par[i], pmid[i]); - if (printLevel > 1) { - std::cout << "MnFunctionCross: parameter " << i << " set to " << pmid[i] << std::endl; + if (printLevel > 1) { + std::cout << "MnFunctionCross: parameter " << i << " set to " << pmid[i] << std::endl; } } // find minimum with respect all the other parameters (n- npar) (npar are the fixed ones) - + FunctionMinimum min0 = migrad(maxcalls, mgr_tlr); nfcn += min0.NFcn(); #ifdef DEBUG - std::cout << "MnFunctionCross: after Migrad on n-1 minimum is " << min0 << std::endl; + std::cout << "MnFunctionCross: after Migrad on n-1 minimum is " << min0 << std::endl; #endif - - if(min0.HasReachedCallLimit()) + + if(min0.HasReachedCallLimit()) return MnCross(min0.UserState(), nfcn, MnCross::CrossFcnLimit()); if(!min0.IsValid()) return MnCross(fState, nfcn); - if(limset == true && min0.Fval() < aim) + if(limset == true && min0.Fval() < aim) return MnCross(min0.UserState(), nfcn, MnCross::CrossParLimit()); - + ipt++; alsb[0] = 0.; flsb[0] = min0.Fval(); flsb[0] = std::max(flsb[0], aminsv + 0.1*up); aopt = sqrt(up/(flsb[0]-aminsv)) - 1.; if(fabs(flsb[0] - aim) < tlf) return MnCross(aopt, min0.UserState(), nfcn); - + if(aopt > 1.) aopt = 1.; if(aopt < -0.5) aopt = -0.5; limset = false; @@ -139,56 +139,56 @@ MnCross MnFunctionCross::operator()(const std::vector<unsigned int>& par, const #ifdef DEBUG std::cout << "MnFunctionCross: flsb[0] = " << flsb[0] << " aopt = " << aopt << std::endl; #endif - + for(unsigned int i = 0; i < npar; i++) { #ifdef DEBUG - std::cout << "MnFunctionCross: Set new value for " << par[i] << " from " << pmid[i] << " to " << pmid[i] + (aopt)*pdir[i] << " aopt = " << aopt << std::endl; + std::cout << "MnFunctionCross: Set new value for " << par[i] << " from " << pmid[i] << " to " << pmid[i] + (aopt)*pdir[i] << " aopt = " << aopt << std::endl; #endif migrad.SetValue(par[i], pmid[i] + (aopt)*pdir[i]); - if (printLevel > 1) { - std::cout << "MnFunctionCross: parameter " << i << " set to " << pmid[i] + (aopt)*pdir[i] << std::endl; + if (printLevel > 1) { + std::cout << "MnFunctionCross: parameter " << i << " set to " << pmid[i] + (aopt)*pdir[i] << std::endl; } } - + FunctionMinimum min1 = migrad(maxcalls, mgr_tlr); nfcn += min1.NFcn(); #ifdef DEBUG - std::cout << "MnFunctionCross: after Migrad on n-1 minimum is " << min1 << std::endl; + std::cout << "MnFunctionCross: after Migrad on n-1 minimum is " << min1 << std::endl; #endif - - if(min1.HasReachedCallLimit()) + + if(min1.HasReachedCallLimit()) return MnCross(min1.UserState(), nfcn, MnCross::CrossFcnLimit()); if(!min1.IsValid()) return MnCross(fState, nfcn); - if(limset == true && min1.Fval() < aim) + if(limset == true && min1.Fval() < aim) return MnCross(min1.UserState(), nfcn, MnCross::CrossParLimit()); - + ipt++; alsb[1] = aopt; flsb[1] = min1.Fval(); double dfda = (flsb[1] - flsb[0])/(alsb[1] - alsb[0]); #ifdef DEBUG - std::cout << "aopt = " << aopt << " min1Val = " << flsb[1] << " dfda = " << dfda << std::endl; -#endif + std::cout << "aopt = " << aopt << " min1Val = " << flsb[1] << " dfda = " << dfda << std::endl; +#endif + - L300: if(dfda < 0.) { // looking for slope of the right sign #ifdef DEBUG std::cout << "MnFunctionCross: dfda < 0 - iterate from " << ipt << " to max of " << maxitr << std::endl; #endif - // iterate (max times is maxitr) incrementing aopt + // iterate (max times is maxitr) incrementing aopt unsigned int maxlk = maxitr - ipt; for(unsigned int it = 0; it < maxlk; it++) { alsb[0] = alsb[1]; flsb[0] = flsb[1]; // LM: Add + 1, looking at Fortran code it starts from 1 ( see bug #8396) - aopt = alsb[0] + 0.2*(it+1); + aopt = alsb[0] + 0.2*(it+1); limset = false; if(aopt > aulim) { aopt = aulim; @@ -196,11 +196,11 @@ L300: } for(unsigned int i = 0; i < npar; i++) { #ifdef DEBUG - std::cout << "MnFunctionCross: Set new value for " << par[i] << " to " << pmid[i] + (aopt)*pdir[i] << " aopt = " << aopt << std::endl; + std::cout << "MnFunctionCross: Set new value for " << par[i] << " to " << pmid[i] + (aopt)*pdir[i] << " aopt = " << aopt << std::endl; #endif migrad.SetValue(par[i], pmid[i] + (aopt)*pdir[i]); - if (printLevel > 1) { - std::cout << "MnFunctionCross: parameter " << i << " set to " << pmid[i] + (aopt)*pdir[i] << std::endl; + if (printLevel > 1) { + std::cout << "MnFunctionCross: parameter " << i << " set to " << pmid[i] + (aopt)*pdir[i] << std::endl; } } @@ -208,14 +208,14 @@ L300: nfcn += min1.NFcn(); #ifdef DEBUG - std::cout << "MnFunctionCross: after Migrad on n-1 minimum is " << min1 << std::endl; + std::cout << "MnFunctionCross: after Migrad on n-1 minimum is " << min1 << std::endl; std::cout << "nfcn = " << nfcn << std::endl; #endif - - if(min1.HasReachedCallLimit()) + + if(min1.HasReachedCallLimit()) return MnCross(min1.UserState(), nfcn, MnCross::CrossFcnLimit()); if(!min1.IsValid()) return MnCross(fState, nfcn); - if(limset == true && min1.Fval() < aim) + if(limset == true && min1.Fval() < aim) return MnCross(min1.UserState(), nfcn, MnCross::CrossParLimit()); ipt++; alsb[1] = aopt; @@ -224,18 +224,18 @@ L300: // if(dfda > 0.) goto L460; #ifdef DEBUG - std::cout << "aopt = " << aopt << " min1Val = " << flsb[1] << " dfda = " << dfda << std::endl; -#endif + std::cout << "aopt = " << aopt << " min1Val = " << flsb[1] << " dfda = " << dfda << std::endl; +#endif if(dfda > 0.) break; - } + } if(ipt > maxitr) return MnCross(fState, nfcn); } //if(dfda < 0.) - + L460: - // dfda > 0: we have two points with the right slope - + // dfda > 0: we have two points with the right slope + aopt = alsb[1] + (aim-flsb[1])/dfda; #ifdef DEBUG @@ -252,20 +252,20 @@ L460: if(aopt < bmin) aopt = bmin; double bmax = std::max(alsb[0], alsb[1]) + 1.; if(aopt > bmax) aopt = bmax; - + limset = false; if(aopt > aulim) { aopt = aulim; limset = true; } - + for(unsigned int i = 0; i < npar; i++) { #ifdef DEBUG - std::cout << "MnFunctionCross: Set new value for " << par[i] << " from " << pmid[i] << " to " << pmid[i] + (aopt)*pdir[i] << " aopt = " << aopt << std::endl; + std::cout << "MnFunctionCross: Set new value for " << par[i] << " from " << pmid[i] << " to " << pmid[i] + (aopt)*pdir[i] << " aopt = " << aopt << std::endl; #endif migrad.SetValue(par[i], pmid[i] + (aopt)*pdir[i]); - if (printLevel > 1) { - std::cout << "MnFunctionCross: parameter " << i << " set to " << pmid[i] + (aopt)*pdir[i] << std::endl; + if (printLevel > 1) { + std::cout << "MnFunctionCross: parameter " << i << " set to " << pmid[i] + (aopt)*pdir[i] << std::endl; } } @@ -273,16 +273,16 @@ L460: nfcn += min2.NFcn(); #ifdef DEBUG - std::cout << "MnFunctionCross: after Migrad on n-1 minimum is " << min2 << std::endl; + std::cout << "MnFunctionCross: after Migrad on n-1 minimum is " << min2 << std::endl; std::cout << "nfcn = " << nfcn << std::endl; #endif - - if(min2.HasReachedCallLimit()) + + if(min2.HasReachedCallLimit()) return MnCross(min2.UserState(), nfcn, MnCross::CrossFcnLimit()); if(!min2.IsValid()) return MnCross(fState, nfcn); - if(limset == true && min2.Fval() < aim) + if(limset == true && min2.Fval() < aim) return MnCross(min2.UserState(), nfcn, MnCross::CrossParLimit()); - + ipt++; alsb[2] = aopt; flsb[2] = min2.Fval(); @@ -294,7 +294,7 @@ L460: unsigned int ibest = 2; unsigned int iworst = 0; unsigned int noless = 0; - + for(unsigned int i = 0; i < 3; i++) { double ecart = fabs(flsb[i] - aim); if(ecart > ecarmx) { @@ -307,62 +307,62 @@ L460: } if(flsb[i] < aim) noless++; } - + #ifdef DEBUG - std::cout << "MnFunctionCross: have three points : nless < aim = " << noless << " ibest = " << ibest << " iworst = " << iworst << std::endl; + std::cout << "MnFunctionCross: have three points : nless < aim = " << noless << " ibest = " << ibest << " iworst = " << iworst << std::endl; #endif //std::cout<<"480"<<std::endl; - - // at least one on each side of AIM (contour), fit a parabola + + // at least one on each side of AIM (contour), fit a parabola if(noless == 1 || noless == 2) goto L500; // if all three are above AIM, third point must be the closest to AIM, return it if(noless == 0 && ibest != 2) return MnCross(fState, nfcn); - // if all three below and third is not best then the slope has again gone negative, + // if all three below and third is not best then the slope has again gone negative, // re-iterate and look for positive slope if(noless == 3 && ibest != 2) { alsb[1] = alsb[2]; flsb[1] = flsb[2]; #ifdef DEBUG - std::cout << "MnFunctionCross: all three points below - look again fir positive slope " << std::endl; + std::cout << "MnFunctionCross: all three points below - look again fir positive slope " << std::endl; #endif goto L300; } // in other case new straight line thru first two points - + flsb[iworst] = flsb[2]; alsb[iworst] = alsb[2]; dfda = (flsb[1] - flsb[0])/(alsb[1] - alsb[0]); #ifdef DEBUG - std::cout << "MnFunctionCross: new straight line using point 1-2 - dfda = " << dfda << std::endl; + std::cout << "MnFunctionCross: new straight line using point 1-2 - dfda = " << dfda << std::endl; #endif goto L460; - + L500: - + do { - // do parabola fit + // do parabola fit MnParabola parbol = MnParabolaFactory()(MnParabolaPoint(alsb[0], flsb[0]), MnParabolaPoint(alsb[1], flsb[1]), MnParabolaPoint(alsb[2], flsb[2])); // aopt = parbol.X_pos(aim); //std::cout<<"alsb1,2,3= "<<alsb[0]<<", "<<alsb[1]<<", "<<alsb[2]<<std::endl; //std::cout<<"flsb1,2,3= "<<flsb[0]<<", "<<flsb[1]<<", "<<flsb[2]<<std::endl; #ifdef DEBUG - std::cout << "MnFunctionCross: parabola fit: iteration " << ipt << std::endl; + std::cout << "MnFunctionCross: parabola fit: iteration " << ipt << std::endl; #endif - + double coeff1 = parbol.C(); - double coeff2 = parbol.B(); - double coeff3 = parbol.A(); + double coeff2 = parbol.B(); + double coeff3 = parbol.A(); double determ = coeff2*coeff2 - 4.*coeff3*(coeff1 - aim); #ifdef DEBUG - std::cout << "MnFunctionCross: parabola fit: a = " << coeff3 << " b = " - << coeff2 << " c = " << coeff1 << " determ = " << determ << std::endl; + std::cout << "MnFunctionCross: parabola fit: a = " << coeff3 << " b = " + << coeff2 << " c = " << coeff1 << " determ = " << determ << std::endl; #endif - // curvature is negative - if(determ < prec.Eps()) return MnCross(fState, nfcn); + // curvature is negative + if(determ < prec.Eps()) return MnCross(fState, nfcn); double rt = sqrt(determ); double x1 = (-coeff2 + rt)/(2.*coeff3); double x2 = (-coeff2 - rt)/(2.*coeff3); @@ -370,10 +370,10 @@ L500: double s2 = coeff2 + 2.*x2*coeff3; #ifdef DEBUG - std::cout << "MnFunctionCross: parabola fit: x1 = " << x1 << " x2 = " - << x2 << " s1 = " << s1 << " s2 = " << s2 << std::endl; + std::cout << "MnFunctionCross: parabola fit: x1 = " << x1 << " x2 = " + << x2 << " s1 = " << s1 << " s2 = " << s2 << std::endl; #endif - + #ifdef WARNINGMSG if(s1*s2 > 0.) MN_INFO_MSG("MnFunctionCross problem 1"); #endif @@ -385,8 +385,8 @@ L500: slope = s2; } #ifdef DEBUG - std::cout << "MnFunctionCross: parabola fit: aopt = " << aopt << " slope = " - << slope << std::endl; + std::cout << "MnFunctionCross: parabola fit: aopt = " << aopt << " slope = " + << slope << std::endl; #endif // ask if converged @@ -394,17 +394,17 @@ L500: if(fabs(aopt) > 1.) tla = tlr*fabs(aopt); #ifdef DEBUG - std::cout << "MnFunctionCross: Delta(aopt) = " << fabs(aopt - alsb[ibest]) << " tla = " - << tla << "Delta(F) = " << fabs(flsb[ibest] - aim) << " tlf = " << tlf << std::endl; + std::cout << "MnFunctionCross: Delta(aopt) = " << fabs(aopt - alsb[ibest]) << " tla = " + << tla << "Delta(F) = " << fabs(flsb[ibest] - aim) << " tlf = " << tlf << std::endl; #endif - if(fabs(aopt - alsb[ibest]) < tla && fabs(flsb[ibest] - aim) < tlf) + if(fabs(aopt - alsb[ibest]) < tla && fabs(flsb[ibest] - aim) < tlf) return MnCross(aopt, min2.UserState(), nfcn); - - // if(ipt > maxitr) return MnCross(); - - // see if proposed point is in acceptable zone between L and R + + // if(ipt > maxitr) return MnCross(); + + // see if proposed point is in acceptable zone between L and R // first find ileft, iright, iout and ibest unsigned int ileft = 3; @@ -436,16 +436,16 @@ L500: } #ifdef DEBUG - std::cout << "MnFunctionCross: ileft = " << ileft << " iright = " - << iright << " iout = " << iout << " ibest = " << ibest << std::endl; + std::cout << "MnFunctionCross: ileft = " << ileft << " iright = " + << iright << " iout = " << iout << " ibest = " << ibest << std::endl; #endif - // avoid keeping a bad point nest time around + // avoid keeping a bad point nest time around - if(ecarmx > 10.*fabs(flsb[iout] - aim)) + if(ecarmx > 10.*fabs(flsb[iout] - aim)) aopt = 0.5*(aopt + 0.5*(alsb[iright] + alsb[ileft])); - // knowing ileft and iright, get acceptable window + // knowing ileft and iright, get acceptable window double smalla = 0.1*tla; if(slope*smalla > tlf) smalla = tlf/slope; double aleft = alsb[ileft] + smalla; @@ -455,46 +455,46 @@ L500: if(aopt < aleft) aopt = aleft; if(aopt > aright) aopt = aright; if(aleft > aright) aopt = 0.5*(aleft + aright); - + // see if proposed point outside limits (should be impossible) limset = false; if(aopt > aulim) { aopt = aulim; limset = true; } - + // evaluate at new point aopt for(unsigned int i = 0; i < npar; i++) { #ifdef DEBUG - std::cout << "MnFunctionCross: Set new value for " << par[i] << " from " << pmid[i] << " to " << pmid[i] + (aopt)*pdir[i] << " aopt = " << aopt << std::endl; -#endif + std::cout << "MnFunctionCross: Set new value for " << par[i] << " from " << pmid[i] << " to " << pmid[i] + (aopt)*pdir[i] << " aopt = " << aopt << std::endl; +#endif migrad.SetValue(par[i], pmid[i] + (aopt)*pdir[i]); - if (printLevel > 1) { - std::cout << "MnFunctionCross: parameter " << i << " set to " << pmid[i] + (aopt)*pdir[i] << std::endl; + if (printLevel > 1) { + std::cout << "MnFunctionCross: parameter " << i << " set to " << pmid[i] + (aopt)*pdir[i] << std::endl; } } min2 = migrad(maxcalls, mgr_tlr); nfcn += min2.NFcn(); #ifdef DEBUG - std::cout << "MnFunctionCross: after Migrad on n-1 minimum is " << min2 << std::endl; + std::cout << "MnFunctionCross: after Migrad on n-1 minimum is " << min2 << std::endl; std::cout << "nfcn = " << nfcn << std::endl; #endif - - if(min2.HasReachedCallLimit()) + + if(min2.HasReachedCallLimit()) return MnCross(min2.UserState(), nfcn, MnCross::CrossFcnLimit()); if(!min2.IsValid()) return MnCross(fState, nfcn); - if(limset == true && min2.Fval() < aim) + if(limset == true && min2.Fval() < aim) return MnCross(min2.UserState(), nfcn, MnCross::CrossParLimit()); - + ipt++; // replace odd point with new one (which is the best of three) alsb[iout] = aopt; flsb[iout] = min2.Fval(); ibest = iout; } while(ipt < maxitr); - + // goto L500; - + return MnCross(fState, nfcn); } diff --git a/ThirdParty/RootMinimizers/src/Minuit2/MnGlobalCorrelationCoeff.cxx b/ThirdParty/RootMinimizers/src/Minuit2/MnGlobalCorrelationCoeff.cxx index fd3ff83834b816d8e2aadfd49cdb3100a7c7b59f..d4adc77ecfb95244a66ade8133e1ba2da49b8e6f 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/MnGlobalCorrelationCoeff.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/MnGlobalCorrelationCoeff.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -11,7 +11,7 @@ #include <cmath> #if defined(DEBUG) || defined(WARNINGMSG) -#include "Minuit2/MnPrint.h" +#include "Minuit2/MnPrint.h" #endif @@ -21,8 +21,8 @@ namespace ROOT { MnGlobalCorrelationCoeff::MnGlobalCorrelationCoeff(const MnAlgebraicSymMatrix& cov) : fGlobalCC(std::vector<double>()), fValid(true) { - // constructor: calculate global correlation given a symmetric matrix - + // constructor: calculate global correlation given a symmetric matrix + MnAlgebraicSymMatrix inv(cov); int ifail = Invert(inv); if(ifail != 0) { @@ -31,9 +31,9 @@ MnGlobalCorrelationCoeff::MnGlobalCorrelationCoeff(const MnAlgebraicSymMatrix& c #endif fValid = false; } else { - - unsigned int n = cov.Nrow(); - fGlobalCC.reserve(n); + + unsigned int n = cov.Nrow(); + fGlobalCC.reserve(n); for(unsigned int i = 0; i < n; i++) { double denom = inv(i,i)*cov(i,i); if(denom < 1. && denom > 0.) fGlobalCC.push_back(0.); diff --git a/ThirdParty/RootMinimizers/src/Minuit2/MnHesse.cxx b/ThirdParty/RootMinimizers/src/Minuit2/MnHesse.cxx index b39b3b3a8e2a37f691a60e7e2a94fa9952091963..81eb12bef0eddb222dfe03b4a976f079ce3ed76f 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/MnHesse.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/MnHesse.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -24,6 +24,9 @@ #if defined(DEBUG) || defined(WARNINGMSG) #include "Minuit2/MnPrint.h" #endif +#if defined(DEBUG) && !defined(WARNINGMSG) +#define WARNINGMSG +#endif #include "Minuit2/MPIProcess.h" @@ -32,7 +35,7 @@ namespace ROOT { namespace Minuit2 { -MnUserParameterState MnHesse::operator()(const FCNBase& fcn, const std::vector<double>& par, const std::vector<double>& err, unsigned int maxcalls) const { +MnUserParameterState MnHesse::operator()(const FCNBase& fcn, const std::vector<double>& par, const std::vector<double>& err, unsigned int maxcalls) const { // interface from vector of params and errors return (*this)(fcn, MnUserParameterState(par, err), maxcalls); } @@ -58,7 +61,7 @@ MnUserParameterState MnHesse::operator()(const FCNBase& fcn, const MnUserParamet } MnUserParameterState MnHesse::operator()(const FCNBase& fcn, const MnUserParameterState& state, unsigned int maxcalls) const { - // interface from MnUserParameterState + // interface from MnUserParameterState // create a new Minimum state and use that interface unsigned int n = state.VariableParameters(); MnUserFcn mfcn(fcn, state.Trafo(),state.NFcn()); @@ -69,33 +72,33 @@ MnUserParameterState MnHesse::operator()(const FCNBase& fcn, const MnUserParamet MinimumParameters par(x, amin); FunctionGradient gra = gc(par); MinimumState tmp = (*this)(mfcn, MinimumState(par, MinimumError(MnAlgebraicSymMatrix(n), 1.), gra, state.Edm(), state.NFcn()), state.Trafo(), maxcalls); - + return MnUserParameterState(tmp, fcn.Up(), state.Trafo()); } void MnHesse::operator()(const FCNBase& fcn, FunctionMinimum& min, unsigned int maxcalls) const { - // interface from FunctionMinimum to be used after minimization + // interface from FunctionMinimum to be used after minimization // use last state from the minimization without the need to re-create a new state // do not reset function calls and keep updating them MnUserFcn mfcn(fcn, min.UserState().Trafo(),min.NFcn()); - MinimumState st = (*this)( mfcn, min.State(), min.UserState().Trafo(), maxcalls); - min.Add(st); + MinimumState st = (*this)( mfcn, min.State(), min.UserState().Trafo(), maxcalls); + min.Add(st); } MinimumState MnHesse::operator()(const MnFcn& mfcn, const MinimumState& st, const MnUserTransformation& trafo, unsigned int maxcalls) const { // internal interface from MinimumState and MnUserTransformation // Function who does the real Hessian calculations - + const MnMachinePrecision& prec = trafo.Precision(); // make sure starting at the right place double amin = mfcn(st.Vec()); double aimsag = sqrt(prec.Eps2())*(fabs(amin)+mfcn.Up()); - + // diagonal Elements first - + unsigned int n = st.Parameters().Vec().size(); if(maxcalls == 0) maxcalls = 200 + 100*n + 5*n*n; - + MnAlgebraicSymMatrix vhmat(n); MnAlgebraicVector g2 = st.Gradient().G2(); MnAlgebraicVector gst = st.Gradient().Gstep(); @@ -113,8 +116,8 @@ MinimumState MnHesse::operator()(const MnFcn& mfcn, const MinimumState& st, cons dirin = tmp.Gstep(); g2 = tmp.G2(); } - - MnAlgebraicVector x = st.Parameters().Vec(); + + MnAlgebraicVector x = st.Parameters().Vec(); #ifdef DEBUG std::cout << "\nMnHesse " << std::endl; @@ -126,9 +129,9 @@ MinimumState MnHesse::operator()(const MnFcn& mfcn, const MinimumState& st, cons std::cout << " Gradient is analytical " << st.Gradient().IsAnalytical() << std::endl; #endif - + for(unsigned int i = 0; i < n; i++) { - + double xtf = x(i); double dmin = 8.*prec.Eps2()*(fabs(xtf) + prec.Eps2()); double d = fabs(gst(i)); @@ -138,7 +141,7 @@ MinimumState MnHesse::operator()(const MnFcn& mfcn, const MinimumState& st, cons std::cout << "\nDerivative parameter " << i << " d = " << d << " dmin = " << dmin << std::endl; #endif - + for(unsigned int icyc = 0; icyc < Ncycles(); icyc++) { double sag = 0.; double fs1 = 0.; @@ -152,7 +155,7 @@ MinimumState MnHesse::operator()(const MnFcn& mfcn, const MinimumState& st, cons sag = 0.5*(fs1+fs2-2.*amin); #ifdef DEBUG - std::cout << "cycle " << icyc << " mul " << multpy << "\t sag = " << sag << " d = " << d << std::endl; + std::cout << "cycle " << icyc << " mul " << multpy << "\t sag = " << sag << " d = " << d << std::endl; #endif // Now as F77 Minuit - check taht sag is not zero if (sag != 0) goto L30; // break @@ -164,27 +167,27 @@ MinimumState MnHesse::operator()(const MnFcn& mfcn, const MinimumState& st, cons } d *= 10.; } - -L26: + +L26: #ifdef WARNINGMSG // get parameter name for i // (need separate scope for avoiding compl error when declaring name) - { + { const char * name = trafo.Name( trafo.ExtOfInt(i)); MN_INFO_VAL2("MnHesse: 2nd derivative zero for Parameter ", name); MN_INFO_MSG("MnHesse fails and will return diagonal matrix "); } #endif - + for(unsigned int j = 0; j < n; j++) { double tmp = g2(j) < prec.Eps2() ? 1. : 1./g2(j); vhmat(j,j) = tmp < prec.Eps2() ? 1. : tmp; } - + return MinimumState(st.Parameters(), MinimumError(vhmat, MinimumError::MnHesseFailed()), st.Gradient(), st.Edm(), mfcn.NumOfCalls()); - -L30: + +L30: double g2bfor = g2(i); g2(i) = 2.*sag/(d*d); grd(i) = (fs1-fs2)/(2.*d); @@ -197,50 +200,50 @@ L30: if(d < dmin) d = dmin; #ifdef DEBUG - std::cout << "\t g1 = " << grd(i) << " g2 = " << g2(i) << " step = " << gst(i) << " d = " << d + std::cout << "\t g1 = " << grd(i) << " g2 = " << g2(i) << " step = " << gst(i) << " d = " << d << " diffd = " << fabs(d-dlast)/d << " diffg2 = " << fabs(g2(i)-g2bfor)/g2(i) << std::endl; #endif - + // see if converged if(fabs((d-dlast)/d) < Tolerstp()) break; - if(fabs((g2(i)-g2bfor)/g2(i)) < TolerG2()) break; + if(fabs((g2(i)-g2bfor)/g2(i)) < TolerG2()) break; d = std::min(d, 10.*dlast); - d = std::max(d, 0.1*dlast); + d = std::max(d, 0.1*dlast); } vhmat(i,i) = g2(i); if(mfcn.NumOfCalls() > maxcalls) { - + #ifdef WARNINGMSG //std::cout<<"maxcalls " << maxcalls << " " << mfcn.NumOfCalls() << " " << st.NFcn() << std::endl; - MN_INFO_MSG("MnHesse: maximum number of allowed function calls exhausted."); + MN_INFO_MSG("MnHesse: maximum number of allowed function calls exhausted."); MN_INFO_MSG("MnHesse fails and will return diagonal matrix "); #endif - + for(unsigned int j = 0; j < n; j++) { double tmp = g2(j) < prec.Eps2() ? 1. : 1./g2(j); vhmat(j,j) = tmp < prec.Eps2() ? 1. : tmp; } - + return MinimumState(st.Parameters(), MinimumError(vhmat, MinimumError::MnHesseFailed()), st.Gradient(), st.Edm(), mfcn.NumOfCalls()); } - + } #ifdef DEBUG - std::cout << "\n Second derivatives " << g2 << std::endl; -#endif - + std::cout << "\n Second derivatives " << g2 << std::endl; +#endif + if(fStrategy.Strategy() > 0) { // refine first derivative HessianGradientCalculator hgc(mfcn, trafo, fStrategy); FunctionGradient gr = hgc(st.Parameters(), FunctionGradient(grd, g2, gst)); - // update gradient and step values + // update gradient and step values grd = gr.Grad(); gst = gr.Gstep(); } - - //off-diagonal Elements + + //off-diagonal Elements // initial starting values MPIProcess mpiprocOffDiagonal(n*(n-1)/2,0); unsigned int startParIndexOffDiagonal = mpiprocOffDiagonal.StartElementIndex(); @@ -259,20 +262,20 @@ L30: if ((i+1)==j || in==startParIndexOffDiagonal) x(i) += dirin(i); - + x(j) += dirin(j); - + double fs1 = mfcn(x); double elem = (fs1 + amin - yy(i) - yy(j))/(dirin(i)*dirin(j)); vhmat(i,j) = elem; - + x(j) -= dirin(j); - + if (j%(n-1)==0 || in==endParIndexOffDiagonal-1) x(i) -= dirin(i); - + } - + mpiprocOffDiagonal.SyncSymMatrixOffDiagonal(vhmat); //verify if matrix pos-def (still 2nd derivative) @@ -296,24 +299,24 @@ L30: int ifail = Invert(vhmat); if(ifail != 0) { - + #ifdef WARNINGMSG MN_INFO_MSG("MnHesse: matrix inversion fails!"); MN_INFO_MSG("MnHesse fails and will return diagonal matrix."); #endif - + MnAlgebraicSymMatrix tmpsym(vhmat.Nrow()); for(unsigned int j = 0; j < n; j++) { double tmp = g2(j) < prec.Eps2() ? 1. : 1./g2(j); tmpsym(j,j) = tmp < prec.Eps2() ? 1. : tmp; } - + return MinimumState(st.Parameters(), MinimumError(tmpsym, MinimumError::MnInvertFailed()), st.Gradient(), st.Edm(), mfcn.NumOfCalls()); } - + FunctionGradient gr(grd, g2, gst); VariableMetricEDMEstimator estim; - + // if matrix is made pos def returns anyway edm if(tmpErr.IsMadePosDef()) { MinimumError err(vhmat, MinimumError::MnMadePosDef() ); @@ -323,36 +326,36 @@ L30: #endif return MinimumState(st.Parameters(), err, gr, edm, mfcn.NumOfCalls()); } - + //calculate edm for good errors MinimumError err(vhmat, 0.); double edm = estim.Estimate(gr, err); #ifdef DEBUG - std::cout << "\nNew state from MnHesse " << std::endl; - std::cout << "Gradient " << grd << std::endl; - std::cout << "Second Deriv " << g2 << std::endl; - std::cout << "Gradient step " << gst << std::endl; - std::cout << "Error " << vhmat << std::endl; - std::cout << "edm " << edm << std::endl; + std::cout << "\nHesse is ACCURATE. New state from MnHesse " << std::endl; + std::cout << "Gradient " << grd << std::endl; + std::cout << "Second Deriv " << g2 << std::endl; + std::cout << "Gradient step " << gst << std::endl; + std::cout << "Error " << vhmat << std::endl; + std::cout << "edm " << edm << std::endl; #endif - + return MinimumState(st.Parameters(), err, gr, edm, mfcn.NumOfCalls()); } /* MinimumError MnHesse::Hessian(const MnFcn& mfcn, const MinimumState& st, const MnUserTransformation& trafo) const { - + const MnMachinePrecision& prec = trafo.Precision(); // make sure starting at the right place double amin = mfcn(st.Vec()); // if(fabs(amin - st.Fval()) > prec.Eps2()) std::cout<<"function Value differs from amin by "<<amin - st.Fval()<<std::endl; - + double aimsag = sqrt(prec.Eps2())*(fabs(amin)+mfcn.Up()); - + // diagonal Elements first - + unsigned int n = st.Parameters().Vec().size(); MnAlgebraicSymMatrix vhmat(n); MnAlgebraicVector g2 = st.Gradient().G2(); @@ -360,10 +363,10 @@ L30: MnAlgebraicVector grd = st.Gradient().Grad(); MnAlgebraicVector dirin = st.Gradient().Gstep(); MnAlgebraicVector yy(n); - MnAlgebraicVector x = st.Parameters().Vec(); - + MnAlgebraicVector x = st.Parameters().Vec(); + for(unsigned int i = 0; i < n; i++) { - + double xtf = x(i); double dmin = 8.*prec.Eps2()*fabs(xtf); double d = fabs(gst(i)); @@ -411,17 +414,17 @@ L30: d = sqrt(2.*aimsag/fabs(g2(i))); if(trafo.Parameter(i).HasLimits()) d = std::min(0.5, d); if(d < dmin) d = dmin; - + // see if converged if(fabs((d-dlast)/d) < Tolerstp()) break; - if(fabs((g2(i)-g2bfor)/g2(i)) < TolerG2()) break; + if(fabs((g2(i)-g2bfor)/g2(i)) < TolerG2()) break; d = std::min(d, 10.*dlast); d = std::max(d, 0.1*dlast); } vhmat(i,i) = g2(i); } - - //off-diagonal Elements + + //off-diagonal Elements for(unsigned int i = 0; i < n; i++) { x(i) += dirin(i); for(unsigned int j = i+1; j < n; j++) { @@ -433,7 +436,7 @@ L30: } x(i) -= dirin(i); } - + return MinimumError(vhmat, 0.); } */ diff --git a/ThirdParty/RootMinimizers/src/Minuit2/MnLineSearch.cxx b/ThirdParty/RootMinimizers/src/Minuit2/MnLineSearch.cxx index 4f69b901d1ef4f00ace5fec24fbae6013f90fe90..06b11ae8e61233b0bde8abe62321a2d8914ed965 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/MnLineSearch.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/MnLineSearch.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -17,8 +17,8 @@ #include "Minuit2/LaSum.h" #include <iostream> -#include <algorithm> #include "Minuit2/MnPrint.h" +#include <algorithm> #ifdef USE_OTHER_LS @@ -40,14 +40,14 @@ namespace ROOT { /** Perform a line search from position defined by the vector st along the direction step, where the length of vector step gives the expected position of Minimum. - fcn is Value of function at the starting position , - gdel (if non-zero) is df/dx along step at st. + fcn is Value of function at the starting position , + gdel (if non-zero) is df/dx along step at st. Return a parabola point containing Minimum x position and y (function Value) - - add a falg to control the debug + - add a falg to control the debug */ MnParabolaPoint MnLineSearch::operator()(const MnFcn& fcn, const MinimumParameters& st, const MnAlgebraicVector& step, double gdel, const MnMachinePrecision& prec, bool debug) const { - + //*-*-*-*-*-*-*-*-*-*Perform a line search from position st along step *-*-*-*-*-*-*-* //*-* ========================================= //*-* SLAMBG and ALPHA control the maximum individual steps allowed. @@ -58,14 +58,14 @@ MnParabolaPoint MnLineSearch::operator()(const MnFcn& fcn, const MinimumParamete //*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- #ifdef DEBUG - debug = true; + debug = true; #endif if (debug) { std::cout<<"gdel= "<<gdel<<std::endl; std::cout<<"step= "<<step<<std::endl; } - + double overal = 1000.; double undral = -100.; double toler = 0.05; @@ -74,8 +74,8 @@ MnParabolaPoint MnLineSearch::operator()(const MnFcn& fcn, const MinimumParamete double alpha = 2.; int maxiter = 12; // start as in Fortran from 1 and count all the time we evaluate the function - int niter = 1; - + int niter = 1; + for(unsigned int i = 0; i < step.size(); i++) { if(step(i) == 0 ) continue; double ratio = fabs(st.Vec()(i)/step(i)); @@ -84,13 +84,13 @@ MnParabolaPoint MnLineSearch::operator()(const MnFcn& fcn, const MinimumParamete } if(fabs(slamin) < prec.Eps()) slamin = prec.Eps(); slamin *= prec.Eps2(); - + double f0 = st.Fval(); double f1 = fcn(st.Vec()+step); niter++; double fvmin = st.Fval(); double xvmin = 0.; - + if(f1 < f0) { fvmin = f1; xvmin = 1.; @@ -99,18 +99,18 @@ MnParabolaPoint MnLineSearch::operator()(const MnFcn& fcn, const MinimumParamete double slamax = slambg; double flast = f1; double slam = 1.; - + bool iterate = false; MnParabolaPoint p0(0., f0); MnParabolaPoint p1(slam, flast); double f2 = 0.; // quadratic interpolation using the two points p0,p1 and the slope at p0 - do { - // cut toler8 as function goes up + do { + // cut toler8 as function goes up iterate = false; //MnParabola pb = MnParabolaFactory()(p0, gdel, p1); - if (debug) { + if (debug) { // std::cout<<"pb.Min() = "<<pb.Min()<<std::endl; std::cout<<"flast, f0= "<<flast<<", "<<f0<<std::endl; std::cout<<"flast-f0= "<<flast-f0<<std::endl; @@ -130,38 +130,38 @@ MnParabolaPoint MnLineSearch::operator()(const MnFcn& fcn, const MinimumParamete } else { denom = -0.1*gdel; slam = 1.; - } + } if (debug) std::cout<<"new slam= "<<slam<<std::endl; -#ifdef TRY_OPPOSIT_DIR +#ifdef TRY_OPPOSIT_DIR // if is less than zero indicates maximum position. Use then slamax or x = x0 - 2slam + 1 - bool slamIsNeg = false; + bool slamIsNeg = false; double slamNeg = 0; #endif - if(slam < 0.) { + if(slam < 0.) { if (debug) std::cout<<"slam is negative- set to " << slamax << std::endl; #ifdef TRY_OPPOSITE_DIR - slamNeg = 2*slam -1; + slamNeg = 2*slam -1; slamIsNeg = true; if (debug) std::cout<<"slam is negative- compare values between "<< slamNeg << " and " << slamax << std::endl; #endif slam = slamax; } // std::cout<<"slam= "<<slam<<std::endl; - if(slam > slamax) { + if(slam > slamax) { slam = slamax; if (debug) std::cout << "slam larger than mac value - set to " << slamax << std::endl; } - if(slam < toler8) { + if(slam < toler8) { if (debug) std::cout << "slam too small - set to " << toler8 << std::endl; slam = toler8; } // std::cout<<"slam= "<<slam<<std::endl; if(slam < slamin) { - if (debug) std::cout << "slam smaller than " << slamin << " return " << std::endl; + if (debug) std::cout << "slam smaller than " << slamin << " return " << std::endl; // std::cout<<"f1, f2= "<<p0.Y()<<", "<<p1.Y()<<std::endl; // std::cout<<"x1, x2= "<<p0.X()<<", "<<p1.X()<<std::endl; // std::cout<<"x, f= "<<xvmin<<", "<<fvmin<<std::endl; @@ -174,7 +174,7 @@ MnParabolaPoint MnLineSearch::operator()(const MnFcn& fcn, const MinimumParamete return MnParabolaPoint(xvmin, fvmin); } if(fabs(slam - 1.) < toler8) slam = 1. + toler8; - + // if(fabs(gdel) < prec.Eps2() && fabs(denom) < prec.Eps2()) // slam = 1000.; // MnAlgebraicVector tmp = step; @@ -182,15 +182,15 @@ MnParabolaPoint MnLineSearch::operator()(const MnFcn& fcn, const MinimumParamete // f2 = fcn(st.Vec()+tmp); f2 = fcn(st.Vec() + slam*step); - niter++; // do as in Minuit (count all func evalu) + niter++; // do as in Minuit (count all func evalu) #ifdef TRY_OPPOSITE_DIR - if (slamIsNeg) { + if (slamIsNeg) { // try alternative in the opposite direction double f2alt = fcn(st.Vec() + slamNeg*step); - if (f2alt < f2) { - slam = slamNeg; - f2 = f2alt; + if (f2alt < f2) { + slam = slamNeg; + f2 = f2alt; undral += slam; } } @@ -200,7 +200,7 @@ MnParabolaPoint MnLineSearch::operator()(const MnFcn& fcn, const MinimumParamete xvmin = slam; } // LM : correct a bug using precision - if (fabs( p0.Y() - fvmin) < fabs(fvmin)*prec.Eps() ) { + if (fabs( p0.Y() - fvmin) < fabs(fvmin)*prec.Eps() ) { // if(p0.Y()-prec.Eps() < fvmin && fvmin < p0.Y()+prec.Eps()) { iterate = true; flast = f2; @@ -213,23 +213,23 @@ MnParabolaPoint MnLineSearch::operator()(const MnFcn& fcn, const MinimumParamete } while(iterate && niter < maxiter); if(niter >= maxiter) { // exhausted max number of iterations - return MnParabolaPoint(xvmin, fvmin); + return MnParabolaPoint(xvmin, fvmin); } - + if (debug){ std::cout<<"after initial 2-point iter: "<<std::endl; std::cout<<"x0, x1, x2= "<<p0.X()<<", "<<p1.X()<<", "<<slam<<std::endl; std::cout<<"f0, f1, f2= "<<p0.Y()<<", "<<p1.Y()<<", "<<f2<<std::endl; } - + MnParabolaPoint p2(slam, f2); - + // do now the quadratic interpolation with 3 points do { slamax = std::max(slamax, alpha*fabs(xvmin)); MnParabola pb = MnParabolaFactory()(p0, p1, p2); - if (debug) { - std::cout << "\nLS Iteration " << niter << std::endl; + if (debug) { + std::cout << "\nLS Iteration " << niter << std::endl; std::cout<<"x0, x1, x2= "<<p0.X()<<", "<<p1.X()<<", "<<p2.X() <<std::endl; std::cout<<"f0, f1, f2= "<<p0.Y()<<", "<<p1.Y()<<", "<<p2.Y() <<std::endl; std::cout << "slamax = " << slamax << std::endl; @@ -253,44 +253,44 @@ MnParabolaPoint MnLineSearch::operator()(const MnFcn& fcn, const MinimumParamete if(slam < undral) slam = undral; } - if (debug) { + if (debug) { std::cout<<" slam= "<<slam<< " undral " << undral << " overal " << overal << std::endl; } - + double f3 = 0.; do { - if (debug) std::cout << " iterate on f3- slam " << niter << " slam = " << slam << " xvmin " << xvmin << std::endl; + if (debug) std::cout << " iterate on f3- slam " << niter << " slam = " << slam << " xvmin " << xvmin << std::endl; iterate = false; double toler9 = std::max(toler8, fabs(toler8*slam)); - // min. of parabola at one point - if(fabs(p0.X() - slam) < toler9 || - fabs(p1.X() - slam) < toler9 || + // min. of parabola at one point + if(fabs(p0.X() - slam) < toler9 || + fabs(p1.X() - slam) < toler9 || fabs(p2.X() - slam) < toler9) { // std::cout<<"f1, f2, f3= "<<p0.Y()<<", "<<p1.Y()<<", "<<p2.Y()<<std::endl; // std::cout<<"x1, x2, x3= "<<p0.X()<<", "<<p1.X()<<", "<<p2.X()<<std::endl; // std::cout<<"x, f= "<<xvmin<<", "<<fvmin<<std::endl; return MnParabolaPoint(xvmin, fvmin); } - + // take the step // MnAlgebraicVector tmp = step; // tmp *= slam; f3 = fcn(st.Vec() + slam*step); - if (debug) { + if (debug) { std::cout<<"f3= "<<f3<<std::endl; std::cout<<"f3-p(2-0).Y()= "<<f3-p2.Y()<<" "<<f3-p1.Y()<<" "<<f3-p0.Y()<<std::endl; } // if latest point worse than all three previous, cut step if(f3 > p0.Y() && f3 > p1.Y() && f3 > p2.Y()) { - if (debug) { + if (debug) { std::cout<<"f3 worse than all three previous"<<std::endl; } if(slam > xvmin) overal = std::min(overal, slam-toler8); if(slam < xvmin) undral = std::max(undral, slam+toler8); slam = 0.5*(slam + xvmin); - if (debug) { + if (debug) { std::cout<<"new slam= "<<slam<<std::endl; } iterate = true; @@ -299,9 +299,9 @@ MnParabolaPoint MnLineSearch::operator()(const MnFcn& fcn, const MinimumParamete } while(iterate && niter < maxiter); if(niter >= maxiter) { // exhausted max number of iterations - return MnParabolaPoint(xvmin, fvmin); + return MnParabolaPoint(xvmin, fvmin); } - + // find worst previous point out of three and replace MnParabolaPoint p3(slam, f3); if(p0.Y() > p1.Y() && p0.Y() > p2.Y()) p0 = p3; @@ -315,11 +315,11 @@ MnParabolaPoint MnLineSearch::operator()(const MnFcn& fcn, const MinimumParamete if(slam > xvmin) overal = std::min(overal, slam-toler8); if(slam < xvmin) undral = std::max(undral, slam+toler8); } - + niter++; } while(niter < maxiter); - - if (debug) { + + if (debug) { std::cout<<"f1, f2= "<<p0.Y()<<", "<<p1.Y()<<std::endl; std::cout<<"x1, x2= "<<p0.X()<<", "<<p1.X()<<std::endl; std::cout<<"x, f= "<<xvmin<<", "<<fvmin<<std::endl; @@ -343,7 +343,7 @@ MnParabolaPoint MnLineSearch::CubicSearch(const MnFcn& fcn, const MinimumParamet std::cout<<"g2del= "<<g2del<<std::endl; std::cout<<"step= "<<step<<std::endl; } - + // change ot large values double overal = 100.; double undral = -100.; @@ -351,7 +351,7 @@ MnParabolaPoint MnLineSearch::CubicSearch(const MnFcn& fcn, const MinimumParamet double slamin = 0.; double slambg = 5.; double alpha = 2.; - + for(unsigned int i = 0; i < step.size(); i++) { if(step(i) == 0 ) continue; double ratio = fabs(st.Vec()(i)/step(i)); @@ -360,13 +360,13 @@ MnParabolaPoint MnLineSearch::CubicSearch(const MnFcn& fcn, const MinimumParamet } if(fabs(slamin) < prec.Eps()) slamin = prec.Eps(); slamin *= prec.Eps2(); - + double f0 = st.Fval(); double f1 = fcn(st.Vec()+step); double fvmin = st.Fval(); double xvmin = 0.; if (debug) std::cout << "f0 " << f0 << " f1 " << f1 << std::endl; - + if(f1 < f0) { fvmin = f1; xvmin = 1.; @@ -375,19 +375,19 @@ MnParabolaPoint MnLineSearch::CubicSearch(const MnFcn& fcn, const MinimumParamet double slamax = slambg; double flast = f1; double slam = 1.; - + // MnParabolaPoint p0(0., f0); // MnParabolaPoint p1(slam, flast); ROOT::Math::SMatrix<double, 3> cubicMatrix; ROOT::Math::SVector<double, 3> cubicCoeff; // cubic coefficients to be found ROOT::Math::SVector<double, 3> bVec; // cubic coefficients to be found - double x0 = 0; + double x0 = 0; // cubic interpolation using the two points p0,p1 and the slope at p0 and the second derivative at p0 - // cut toler8 as function goes up - double x1 = slam; + // cut toler8 as function goes up + double x1 = slam; cubicMatrix(0,0) = (x0*x0*x0 - x1*x1*x1)/3.; cubicMatrix(0,1) = (x0*x0 - x1*x1)/2.; cubicMatrix(0,2) = (x0 - x1); @@ -398,168 +398,168 @@ MnParabolaPoint MnLineSearch::CubicSearch(const MnFcn& fcn, const MinimumParamet cubicMatrix(2,1) = 1; cubicMatrix(2,2) = 0; - bVec(0) = f0-f1; - bVec(1) = gdel; - bVec(2) = g2del; - - //if (debug) std::cout << "Matrix:\n " << cubicMatrix << std::endl; - if (debug) std::cout << "Vec:\n " << bVec << std::endl; - + bVec(0) = f0-f1; + bVec(1) = gdel; + bVec(2) = g2del; + + //if (debug) std::cout << "Matrix:\n " << cubicMatrix << std::endl; + if (debug) std::cout << "Vec:\n " << bVec << std::endl; + // find the minimum need to invert the matrix - if (!cubicMatrix.Invert() ) { + if (!cubicMatrix.Invert() ) { std::cout << "Inversion failed - return " << std::endl; return MnParabolaPoint(xvmin, fvmin); } - - cubicCoeff = cubicMatrix * bVec; - if (debug) std::cout << "Cubic:\n " << cubicCoeff << std::endl; - - - double ddd = cubicCoeff(1)*cubicCoeff(1)-4*cubicCoeff(0)*cubicCoeff(2); // b**2 - 4ac + + cubicCoeff = cubicMatrix * bVec; + if (debug) std::cout << "Cubic:\n " << cubicCoeff << std::endl; + + + double ddd = cubicCoeff(1)*cubicCoeff(1)-4*cubicCoeff(0)*cubicCoeff(2); // b**2 - 4ac double slam1, slam2 = 0; // slam1 should be minimum and slam2 the maximum - if (cubicCoeff(0) > 0) { - slam1 = (- cubicCoeff(1) - std::sqrt(ddd) ) / ( 2. * cubicCoeff(0) ); - slam2 = (- cubicCoeff(1) + std::sqrt(ddd) ) / ( 2. * cubicCoeff(0) ); + if (cubicCoeff(0) > 0) { + slam1 = (- cubicCoeff(1) - std::sqrt(ddd) ) / ( 2. * cubicCoeff(0) ); + slam2 = (- cubicCoeff(1) + std::sqrt(ddd) ) / ( 2. * cubicCoeff(0) ); } - else if (cubicCoeff(0) < 0) { - slam1 = (- cubicCoeff(1) + std::sqrt(ddd) ) / ( 2. * cubicCoeff(0) ); - slam2 = (- cubicCoeff(1) - std::sqrt(ddd) ) / ( 2. * cubicCoeff(0) ); + else if (cubicCoeff(0) < 0) { + slam1 = (- cubicCoeff(1) + std::sqrt(ddd) ) / ( 2. * cubicCoeff(0) ); + slam2 = (- cubicCoeff(1) - std::sqrt(ddd) ) / ( 2. * cubicCoeff(0) ); } else { // case == 0 (-b/c) - slam1 = - gdel/g2del; - slam2 = slam1; + slam1 = - gdel/g2del; + slam2 = slam1; } - - std::cout << "slam1 & slam 2 " << slam1 << " " << slam2 << std::endl; - + + std::cout << "slam1 & slam 2 " << slam1 << " " << slam2 << std::endl; + // this should be the minimum otherwise inversion failed and I should do something else if (slam2 < undral) slam2 = undral; if (slam2 > overal) slam2 = overal; - - // I am stack somewhere - take a large step - if (std::fabs(slam2) < toler) slam2 = ( slam2 >=0 ) ? slamax : -slamax; + // I am stack somewhere - take a large step + if (std::fabs(slam2) < toler) slam2 = ( slam2 >=0 ) ? slamax : -slamax; + + + std::cout << "try with slam 2 " << slam2 << std::endl; - std::cout << "try with slam 2 " << slam2 << std::endl; - - double f2 = fcn(st.Vec()+slam2*step); + double f2 = fcn(st.Vec()+slam2*step); - std::cout << "try with slam 2 " << slam2 << " f2 " << f2 << std::endl; + std::cout << "try with slam 2 " << slam2 << " f2 " << f2 << std::endl; - double fp; - // use this as new minimum + double fp; + // use this as new minimum //bool noImpr = false; - if (f2 < fvmin) { - slam = slam2; - xvmin = slam; - fvmin = f2; + if (f2 < fvmin) { + slam = slam2; + xvmin = slam; + fvmin = f2; fp = fvmin; - } else { + } else { // try with slam2 if it is better - + if (slam1 < undral) slam1 = undral; if (slam1 > overal) slam1 = overal; - - if (std::fabs(slam1) < toler) slam1 = ( slam1 >=0 ) ? -slamax : slamax; - - double f3 = fcn(st.Vec()+slam1*step); - std::cout << "try with slam 1 " << slam1 << " f3 " << f3 << std::endl; - - if (f3 < fvmin) { - slam = slam1; + if (std::fabs(slam1) < toler) slam1 = ( slam1 >=0 ) ? -slamax : slamax; + + double f3 = fcn(st.Vec()+slam1*step); + + std::cout << "try with slam 1 " << slam1 << " f3 " << f3 << std::endl; + + if (f3 < fvmin) { + slam = slam1; fp = fvmin; - xvmin = slam; - fvmin = f3; - } else { + xvmin = slam; + fvmin = f3; + } else { // case both f2 and f3 did not produce a better result - if (f2 < f3) { + if (f2 < f3) { slam = slam1; - fp = f2; - } else { - slam = slam2; - fp = f3; + fp = f2; + } else { + slam = slam2; + fp = f3; } } } - bool iterate2 = false; - int niter = 0; + bool iterate2 = false; + int niter = 0; int maxiter = 10; - - do { + + do { iterate2 = false; - std::cout << "\n iter" << niter << " test approx deriv ad second deriv at " << slam << " fp " << fp << std::endl; - - // estimate grad and second derivative at new point taking a step of 10-3 - double h = 0.001*slam; + std::cout << "\n iter" << niter << " test approx deriv ad second deriv at " << slam << " fp " << fp << std::endl; + + // estimate grad and second derivative at new point taking a step of 10-3 + double h = 0.001*slam; double fh = fcn(st.Vec()+(slam+h)*step); double fl = fcn(st.Vec()+(slam-h)*step); double df = (fh-fl)/(2.*h); double df2 = (fh+fl-2.*fp )/(h*h); - std::cout << "deriv: " << df << " , " << df2 << std::endl; + std::cout << "deriv: " << df << " , " << df2 << std::endl; - // if I am in a point of still negative derivative - if ( std::fabs(df ) < prec.Eps() && std::fabs( df2 ) < prec.Eps() ) { + // if I am in a point of still negative derivative + if ( std::fabs(df ) < prec.Eps() && std::fabs( df2 ) < prec.Eps() ) { // try in opposite direction with an opposite value - slam = ( slam >=0 ) ? -slamax : slamax; - slamax *= 10; + slam = ( slam >=0 ) ? -slamax : slamax; + slamax *= 10; fp = fcn(st.Vec()+slam*step); } - else if ( std::fabs(df2 ) <= 0) { // gradient is significative different than zero then redo a cubic interpolation + else if ( std::fabs(df2 ) <= 0) { // gradient is significative different than zero then redo a cubic interpolation // from new point return MnParabolaPoint(slam, fp); // should redo a cubic interpol. ?? -// niter ++; +// niter ++; // if (niter > maxiter) break; - -// MinimumParameters pa = MinimumParameters(st.Vec() + stepNew, fp); + +// MinimumParameters pa = MinimumParameters(st.Vec() + stepNew, fp); // gdel = stepNew(i) -// MnParabolaPoint pp = CubicSearch(fcn, st, stepNew, df, df2 +// MnParabolaPoint pp = CubicSearch(fcn, st, stepNew, df, df2 } - else + else return MnParabolaPoint(slam, fp); - + niter++; - } while (niter < maxiter); + } while (niter < maxiter); - return MnParabolaPoint(xvmin, fvmin); + return MnParabolaPoint(xvmin, fvmin); } // class describing Fcn function in one dimension - class ProjectedFcn : public ROOT::Math::IGenFunction { + class ProjectedFcn : public ROOT::Math::IGenFunction { - public: + public: - ProjectedFcn(const MnFcn & fcn, const MinimumParameters & pa, const MnAlgebraicVector & step) : - fFcn(fcn), - fPar(pa), + ProjectedFcn(const MnFcn & fcn, const MinimumParameters & pa, const MnAlgebraicVector & step) : + fFcn(fcn), + fPar(pa), fStep(step) {} - ROOT::Math::IGenFunction * Clone() const { return new ProjectedFcn(*this); } + ROOT::Math::IGenFunction * Clone() const { return new ProjectedFcn(*this); } - private: - - double DoEval(double x) const { - return fFcn(fPar.Vec() + x*fStep); + private: + + double DoEval(double x) const { + return fFcn(fPar.Vec() + x*fStep); } - const MnFcn & fFcn; + const MnFcn & fFcn; const MinimumParameters & fPar; const MnAlgebraicVector & fStep; }; @@ -570,8 +570,8 @@ MnParabolaPoint MnLineSearch::BrentSearch(const MnFcn& fcn, const MinimumParamet if (debug) { std::cout<<"gdel= "<<gdel<<std::endl; std::cout<<"g2del= "<<g2del<<std::endl; - for (unsigned int i = 0; i < step.size(); ++i) { - if (step(i) != 0) { + for (unsigned int i = 0; i < step.size(); ++i) { + if (step(i) != 0) { std::cout<<"step(i)= "<<step(i)<<std::endl; std::cout<<"par(i) " <<st.Vec()(i) <<std::endl; break; @@ -579,7 +579,7 @@ MnParabolaPoint MnLineSearch::BrentSearch(const MnFcn& fcn, const MinimumParamet } } - ProjectedFcn func(fcn, st, step); + ProjectedFcn func(fcn, st, step); // do first a cubic interpolation @@ -591,7 +591,7 @@ MnParabolaPoint MnLineSearch::BrentSearch(const MnFcn& fcn, const MinimumParamet double fvmin = st.Fval(); double xvmin = 0.; if (debug) std::cout << "f0 " << f0 << " f1 " << f1 << std::endl; - + if(f1 < f0) { fvmin = f1; xvmin = 1.; @@ -604,8 +604,8 @@ MnParabolaPoint MnLineSearch::BrentSearch(const MnFcn& fcn, const MinimumParamet double undral = -1000; double overal = 1000; - double x0 = 0; - + double x0 = 0; + // MnParabolaPoint p0(0., f0); // MnParabolaPoint p1(slam, flast); #ifdef USE_CUBIC @@ -616,8 +616,8 @@ MnParabolaPoint MnLineSearch::BrentSearch(const MnFcn& fcn, const MinimumParamet // cubic interpolation using the two points p0,p1 and the slope at p0 and the second derivative at p0 - // cut toler8 as function goes up - double x1 = slam; + // cut toler8 as function goes up + double x1 = slam; cubicMatrix(0,0) = (x0*x0*x0 - x1*x1*x1)/3.; cubicMatrix(0,1) = (x0*x0 - x1*x1)/2.; cubicMatrix(0,2) = (x0 - x1); @@ -628,37 +628,37 @@ MnParabolaPoint MnLineSearch::BrentSearch(const MnFcn& fcn, const MinimumParamet cubicMatrix(2,1) = 1; cubicMatrix(2,2) = 0; - bVec(0) = f0-f1; - bVec(1) = gdel; - bVec(2) = g2del; - - //if (debug) std::cout << "Matrix:\n " << cubicMatrix << std::endl; - if (debug) std::cout << "Vec:\n " << bVec << std::endl; - + bVec(0) = f0-f1; + bVec(1) = gdel; + bVec(2) = g2del; + + //if (debug) std::cout << "Matrix:\n " << cubicMatrix << std::endl; + if (debug) std::cout << "Vec:\n " << bVec << std::endl; + // find the minimum need to invert the matrix - if (!cubicMatrix.Invert() ) { + if (!cubicMatrix.Invert() ) { std::cout << "Inversion failed - return " << std::endl; return MnParabolaPoint(xvmin, fvmin); } - - cubicCoeff = cubicMatrix * bVec; - if (debug) std::cout << "Cubic:\n " << cubicCoeff << std::endl; - - - double ddd = cubicCoeff(1)*cubicCoeff(1)-4*cubicCoeff(0)*cubicCoeff(2); // b**2 - 4ac + + cubicCoeff = cubicMatrix * bVec; + if (debug) std::cout << "Cubic:\n " << cubicCoeff << std::endl; + + + double ddd = cubicCoeff(1)*cubicCoeff(1)-4*cubicCoeff(0)*cubicCoeff(2); // b**2 - 4ac double slam1, slam2 = 0; // slam1 should be minimum and slam2 the maximum - if (cubicCoeff(0) > 0) { - slam1 = (- cubicCoeff(1) - std::sqrt(ddd) ) / ( 2. * cubicCoeff(0) ); - slam2 = (- cubicCoeff(1) + std::sqrt(ddd) ) / ( 2. * cubicCoeff(0) ); + if (cubicCoeff(0) > 0) { + slam1 = (- cubicCoeff(1) - std::sqrt(ddd) ) / ( 2. * cubicCoeff(0) ); + slam2 = (- cubicCoeff(1) + std::sqrt(ddd) ) / ( 2. * cubicCoeff(0) ); } - else if (cubicCoeff(0) < 0) { - slam1 = (- cubicCoeff(1) + std::sqrt(ddd) ) / ( 2. * cubicCoeff(0) ); - slam2 = (- cubicCoeff(1) - std::sqrt(ddd) ) / ( 2. * cubicCoeff(0) ); + else if (cubicCoeff(0) < 0) { + slam1 = (- cubicCoeff(1) + std::sqrt(ddd) ) / ( 2. * cubicCoeff(0) ); + slam2 = (- cubicCoeff(1) - std::sqrt(ddd) ) / ( 2. * cubicCoeff(0) ); } else { // case == 0 (-b/c) - slam1 = - gdel/g2del; - slam2 = slam1; + slam1 = - gdel/g2del; + slam2 = slam1; } if (slam1 < undral) slam1 = undral; @@ -667,42 +667,42 @@ MnParabolaPoint MnLineSearch::BrentSearch(const MnFcn& fcn, const MinimumParamet if (slam2 < undral) slam2 = undral; if (slam2 > overal) slam2 = overal; - + double fs1 = func(slam1); double fs2 = func(slam2); - std::cout << "slam1 & slam 2 " << slam1 << " " << slam2 << std::endl; - std::cout << "f(slam1) & f(slam 2) " << fs1 << " " << fs2 << std::endl; - - if (fs1 < fs2) { - x0 = slam1; - f0 = fs1; + std::cout << "slam1 & slam 2 " << slam1 << " " << slam2 << std::endl; + std::cout << "f(slam1) & f(slam 2) " << fs1 << " " << fs2 << std::endl; + + if (fs1 < fs2) { + x0 = slam1; + f0 = fs1; } - else { - x0 = slam2; + else { + x0 = slam2; f0 = fs2; } -#else +#else x0 = xvmin; f0 = fvmin; #endif double astart = 100; - + // do a Brent search in a large interval double a = x0 -astart; double b = x0 + astart; - //double x0 = 1; + //double x0 = 1; int maxiter = 20; double absTol = 0.5; double relTol = 0.05; ROOT::Math::Minim1D::Type minType = ROOT::Math::Minim1D::BRENT; - bool iterate = false; - int iter = 0; + bool iterate = false; + int iter = 0; std::cout << "f(0)" << func(0.) << std::endl; std::cout << "f(1)" << func(1.0) << std::endl; @@ -711,104 +711,104 @@ MnParabolaPoint MnLineSearch::BrentSearch(const MnFcn& fcn, const MinimumParamet double fa = func(a); double fb = func(b); - //double f0 = func(x0); - double toler = 0.01; - double delta0 = 5; - double delta = delta0; - bool enlarge = true; + //double f0 = func(x0); + double toler = 0.01; + double delta0 = 5; + double delta = delta0; + bool enlarge = true; bool scanmin = false; - double x2, f2 = 0; + double x2, f2 = 0; double dir = 1; - int nreset = 0; - - do { - + int nreset = 0; + + do { + std::cout << " iter " << iter << " a , b , x0 " << a << " " << b << " x0 " << x0 << std::endl; std::cout << " fa , fb , f0 " << fa << " " << fb << " f0 " << f0 << std::endl; - if (fa <= f0 || fb <= f0) { - scanmin = false; - if (fa < fb) { - if (fa < fvmin) { - fvmin = fa; - xvmin = a; + if (fa <= f0 || fb <= f0) { + scanmin = false; + if (fa < fb) { + if (fa < fvmin) { + fvmin = fa; + xvmin = a; } -// double f2 = fa; -// double x2 = a; - if (enlarge) { +// double f2 = fa; +// double x2 = a; + if (enlarge) { x2 = a - 1000; // move lower - f2 = func(x2); + f2 = func(x2); } if ( std::fabs ( (fa -f2 )/(a-x2) ) > toler ) { // significant change in f continue to enlarge interval x0 = a; f0 = fa; - a = x2; + a = x2; fa = f2; enlarge = true; - } else { + } else { // move direction of [a // values change a little, start from central point try with x0 = x0 - delta if (nreset == 0) dir = -1; - enlarge = false; - x0 = x0 + dir * delta; - f0 = func(x0); + enlarge = false; + x0 = x0 + dir * delta; + f0 = func(x0); // if reached limit try opposite direction , direction b] - if ( std::fabs (( f0 -fa )/(x0 -a) ) < toler ) { + if ( std::fabs (( f0 -fa )/(x0 -a) ) < toler ) { delta = 10 * delta0/(10.*(nreset+1)); // decrease the delta if still not change observed - a = x0; - fa = f0; + a = x0; + fa = f0; x0 = delta; - f0 = func(x0); - dir *= -1; - nreset++; + f0 = func(x0); + dir *= -1; + nreset++; std::cout << " A: Done a reset - scan in opposite direction ! " << std::endl; - } + } delta *= 2; // double delta at next iteration - if (x0 < b && x0 > a ) - scanmin = true; - else { - x0 = 0; + if (x0 < b && x0 > a ) + scanmin = true; + else { + x0 = 0; f0 = st.Fval(); } } } else { // fb < fa - if (fb < fvmin) { - fvmin = fb; - xvmin = b; + if (fb < fvmin) { + fvmin = fb; + xvmin = b; } - if (enlarge) { + if (enlarge) { x2 = b + 1000; // move upper - f2 = func(x2); + f2 = func(x2); } if ( std::fabs ( (fb -f2 )/(x2-b) ) > toler ) { // significant change in f continue to enlarge interval - f0 = fb; - x0 = b; + f0 = fb; + x0 = b; b = x2; // fb = f2; enlarge = true; - } else { - // here move direction b + } else { + // here move direction b // values change a little, try with x0 = fa + delta if (nreset == 0) dir = 1; enlarge = false; - x0 = x0 + dir * delta; - f0 = func(x0); + x0 = x0 + dir * delta; + f0 = func(x0); // if reached limit try other side - if ( std::fabs ( ( f0 -fb )/(x0-b) ) < toler ) { + if ( std::fabs ( ( f0 -fb )/(x0-b) ) < toler ) { delta = 10 * delta0/(10.*(nreset+1)); // decrease the delta if still not change observed - b = x0; - fb = f0; + b = x0; + fb = f0; x0 = -delta; - f0 = func(x0); - dir *= -1; - nreset++; + f0 = func(x0); + dir *= -1; + nreset++; std::cout << " B: Done a reset - scan in opposite direction ! " << std::endl; - } + } delta *= 2; // double delta at next iteration - if (x0 > a && x0 < b) - scanmin = true; - else { - x0 = 0; + if (x0 > a && x0 < b) + scanmin = true; + else { + x0 = 0; f0 = st.Fval(); } @@ -816,40 +816,40 @@ MnParabolaPoint MnLineSearch::BrentSearch(const MnFcn& fcn, const MinimumParamet } - if ( f0 < fvmin) { + if ( f0 < fvmin) { x0 = xvmin; fvmin = f0; } - std::cout << " new x0 " << x0 << " " << f0 << std::endl; + std::cout << " new x0 " << x0 << " " << f0 << std::endl; // use golden section - iterate = scanmin || enlarge; + iterate = scanmin || enlarge; - } else { // x0 is a min of [a,b] - iterate = false; + } else { // x0 is a min of [a,b] + iterate = false; } iter++; - } while (iterate && iter < maxiter ); + } while (iterate && iter < maxiter ); - if ( f0 > fa || f0 > fb) + if ( f0 > fa || f0 > fb) // skip minim 1d try Minuit LS // return (*this) (fcn, st, step, gdel, prec, debug); return MnParabolaPoint(xvmin, fvmin); - + std::cout << "1D minimization using " << minType << std::endl; - - ROOT::Math::Minimizer1D min(minType); - - min.SetFunction(func,x0, a, b); - int ret = min.Minimize(maxiter, absTol, relTol); + + ROOT::Math::Minimizer1D min(minType); + + min.SetFunction(func,x0, a, b); + int ret = min.Minimize(maxiter, absTol, relTol); std::cout << "result of GSL 1D minimization: " << ret << " niter " << min.Iterations() << std::endl; - std::cout << " xmin = " << min.XMinimum() << " fmin " << min.FValMinimum() << std::endl; + std::cout << " xmin = " << min.XMinimum() << " fmin " << min.FValMinimum() << std::endl; return MnParabolaPoint(min.XMinimum(), min.FValMinimum()); @@ -858,7 +858,7 @@ MnParabolaPoint MnLineSearch::BrentSearch(const MnFcn& fcn, const MinimumParamet #endif - + } // namespace Minuit2 } // namespace ROOT diff --git a/ThirdParty/RootMinimizers/src/Minuit2/MnMachinePrecision.cxx b/ThirdParty/RootMinimizers/src/Minuit2/MnMachinePrecision.cxx index fe71190046f7143c4c81e3ab777e1cb8f5b48fa8..12b2c005159d0e6be94be5010528ec217f9ebeca 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/MnMachinePrecision.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/MnMachinePrecision.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -15,25 +15,25 @@ namespace ROOT { namespace Minuit2 { -MnMachinePrecision::MnMachinePrecision() : +MnMachinePrecision::MnMachinePrecision() : fEpsMac(4.0E-7), fEpsMa2(2.*sqrt(4.0E-7)) { - + //determine machine precision /* char e[] = {"e"}; fEpsMac = 8.*dlamch_(e); fEpsMa2 = 2.*sqrt(fEpsMac); */ - + // std::cout<<"machine precision eps: "<<Eps()<<std::endl; - + MnTiny mytiny; - + //calculate machine precision double epstry = 0.5; double epsbak = 0.; - double epsp1 = 0.; + volatile double epsp1 = 0.; // allow to run this method with fast-math double one = 1.0; for(int i = 0; i < 100; i++) { epstry *= 0.5; @@ -44,10 +44,10 @@ MnMachinePrecision::MnMachinePrecision() : fEpsMa2 = 2.*sqrt(fEpsMac); break; } - } - + } + } - + } // namespace Minuit2 - + } // namespace ROOT diff --git a/ThirdParty/RootMinimizers/src/Minuit2/MnMinos.cxx b/ThirdParty/RootMinimizers/src/Minuit2/MnMinos.cxx index 42d5d7e35ee5242b527d2dfe2a93a53b344312e0..ceb8d752b68f06647ba3f517297a15d776183344 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/MnMinos.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/MnMinos.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -17,7 +17,7 @@ //#define DEBUG #if defined(DEBUG) || defined(WARNINGMSG) -#include "Minuit2/MnPrint.h" +#include "Minuit2/MnPrint.h" #endif @@ -26,33 +26,33 @@ namespace ROOT { namespace Minuit2 { -MnMinos::MnMinos(const FCNBase& fcn, const FunctionMinimum& min, unsigned int stra ) : - fFCN(fcn), - fMinimum(min), - fStrategy(MnStrategy(stra)) +MnMinos::MnMinos(const FCNBase& fcn, const FunctionMinimum& min, unsigned int stra ) : + fFCN(fcn), + fMinimum(min), + fStrategy(MnStrategy(stra)) { // construct from FCN + Minimum // check if Error definition has been changed, in case re-update errors - if (fcn.Up() != min.Up() ) { + if (fcn.Up() != min.Up() ) { #ifdef WARNINGMSG MN_INFO_MSG("MnMinos UP value has changed, need to update FunctionMinimum class"); -#endif +#endif } -} +} -MnMinos::MnMinos(const FCNBase& fcn, const FunctionMinimum& min, const MnStrategy& stra) : - fFCN(fcn), - fMinimum(min), - fStrategy(stra) +MnMinos::MnMinos(const FCNBase& fcn, const FunctionMinimum& min, const MnStrategy& stra) : + fFCN(fcn), + fMinimum(min), + fStrategy(stra) { // construct from FCN + Minimum // check if Error definition has been changed, in case re-update errors - if (fcn.Up() != min.Up() ) { + if (fcn.Up() != min.Up() ) { #ifdef WARNINGMSG MN_INFO_MSG("MnMinos UP value has changed, need to update FunctionMinimum class"); -#endif +#endif } -} +} std::pair<double,double> MnMinos::operator()(unsigned int par, unsigned int maxcalls, double toler) const { @@ -65,120 +65,120 @@ double MnMinos::Lower(unsigned int par, unsigned int maxcalls, double toler) con // get lower error for parameter par MnUserParameterState upar = fMinimum.UserState(); double err = fMinimum.UserState().Error(par); - + MnCross aopt = Loval(par, maxcalls,toler); - + double lower = aopt.IsValid() ? -1.*err*(1.+ aopt.Value()) : (aopt.AtLimit() ? upar.Parameter(par).LowerLimit() : upar.Value(par)); - + return lower; } double MnMinos::Upper(unsigned int par, unsigned int maxcalls, double toler) const { // upper error for parameter par MnCross aopt = Upval(par, maxcalls,toler); - + MnUserParameterState upar = fMinimum.UserState(); double err = fMinimum.UserState().Error(par); - + double upper = aopt.IsValid() ? err*(1.+ aopt.Value()) : (aopt.AtLimit() ? upar.Parameter(par).UpperLimit() : upar.Value(par)); - + return upper; } MinosError MnMinos::Minos(unsigned int par, unsigned int maxcalls, double toler) const { - // do full minos error anlysis (lower + upper) for parameter par - assert(fMinimum.IsValid()); + // do full minos error anlysis (lower + upper) for parameter par + assert(fMinimum.IsValid()); assert(!fMinimum.UserState().Parameter(par).IsFixed()); assert(!fMinimum.UserState().Parameter(par).IsConst()); - + MnCross up = Upval(par, maxcalls,toler); #ifdef DEBUG - std::cout << "Function calls to find upper error " << up.NFcn() << std::endl; + std::cout << "Function calls to find upper error " << up.NFcn() << std::endl; #endif MnCross lo = Loval(par, maxcalls,toler); #ifdef DEBUG - std::cout << "Function calls to find lower error " << lo.NFcn() << std::endl; + std::cout << "Function calls to find lower error " << lo.NFcn() << std::endl; #endif - + return MinosError(par, fMinimum.UserState().Value(par), lo, up); } MnCross MnMinos::FindCrossValue(int direction, unsigned int par, unsigned int maxcalls, double toler) const { - // get crossing value in the parameter direction : + // get crossing value in the parameter direction : // direction = + 1 upper value // direction = -1 lower value // pass now tolerance used for Migrad minimizations - assert(direction == 1 || direction == -1); + assert(direction == 1 || direction == -1); #ifdef DEBUG - if (direction == 1) - std::cout << "\n--------- MnMinos --------- \n Determination of positive Minos error for parameter " + if (direction == 1) + std::cout << "\n--------- MnMinos --------- \n Determination of positive Minos error for parameter " << par << std::endl; - else - std::cout << "\n--------- MnMinos --------- \n Determination of positive Minos error for parameter " + else + std::cout << "\n--------- MnMinos --------- \n Determination of positive Minos error for parameter " << par << std::endl; #endif - assert(fMinimum.IsValid()); + assert(fMinimum.IsValid()); assert(!fMinimum.UserState().Parameter(par).IsFixed()); assert(!fMinimum.UserState().Parameter(par).IsConst()); if(maxcalls == 0) { unsigned int nvar = fMinimum.UserState().VariableParameters(); maxcalls = 2*(nvar+1)*(200 + 100*nvar + 5*nvar*nvar); } - + std::vector<unsigned int> para(1, par); - + MnUserParameterState upar = fMinimum.UserState(); double err = direction * upar.Error(par); double val = upar.Value(par) + err; std::vector<double> xmid(1, val); std::vector<double> xdir(1, err); - + double up = fFCN.Up(); unsigned int ind = upar.IntOfExt(par); // get error matrix (methods return a copy) - MnAlgebraicSymMatrix m = fMinimum.Error().Matrix(); - // get internal parameters - const MnAlgebraicVector & xt = fMinimum.Parameters().Vec(); + MnAlgebraicSymMatrix m = fMinimum.Error().Matrix(); + // get internal parameters + const MnAlgebraicVector & xt = fMinimum.Parameters().Vec(); //LM: change to use err**2 (m(i,i) instead of err as in F77 version double xunit = sqrt(up/m(ind,ind)); - // LM (29/04/08) bug: change should be done in internal variables + // LM (29/04/08) bug: change should be done in internal variables for(unsigned int i = 0; i < m.Nrow(); i++) { if(i == ind) continue; double xdev = xunit*m(ind,i); double xnew = xt(i) + direction * xdev; - // transform to external values + // transform to external values unsigned int ext = upar.ExtOfInt(i); - - double unew = upar.Int2ext(i, xnew); -#ifdef DEBUG + double unew = upar.Int2ext(i, xnew); + +#ifdef DEBUG std::cout << "Parameter " << ext << " is set from " << upar.Value(ext) << " to " << unew << std::endl; #endif upar.SetValue(ext, unew); } - + upar.Fix(par); upar.SetValue(par, val); #ifdef DEBUG std::cout << "Parameter " << par << " is fixed and set from " << fMinimum.UserState().Value(par) << " to " << val << std::endl; -#endif - +#endif + - MnFunctionCross cross(fFCN, upar, fMinimum.Fval(), fStrategy); + MnFunctionCross cross(fFCN, upar, fMinimum.Fval(), fStrategy); MnCross aopt = cross(para, xmid, xdir, toler, maxcalls); - + #ifdef DEBUG std::cout<<"----- MnMinos: aopt found from MnFunctionCross = "<<aopt.Value()<<std::endl << std::endl; #endif - + #ifdef WARNINGMSG const char * par_name = upar.Name(par); if(aopt.AtMaxFcn()) @@ -186,19 +186,19 @@ MnCross MnMinos::FindCrossValue(int direction, unsigned int par, unsigned int ma if(aopt.NewMinimum()) MN_INFO_VAL2("MnMinos new Minimum found while looking for Parameter ",par_name); if (direction ==1) { - if(aopt.AtLimit()) + if(aopt.AtLimit()) MN_INFO_VAL2("MnMinos Parameter is at Upper limit.",par_name); - if(!aopt.IsValid()) + if(!aopt.IsValid()) MN_INFO_VAL2("MnMinos could not find Upper Value for Parameter ",par_name); } - else { - if(aopt.AtLimit()) + else { + if(aopt.AtLimit()) MN_INFO_VAL2("MnMinos Parameter is at Lower limit.",par_name); - if(!aopt.IsValid()) + if(!aopt.IsValid()) MN_INFO_VAL2("MnMinos could not find Lower Value for Parameter ",par_name); } #endif - + return aopt; } @@ -213,11 +213,11 @@ MnCross MnMinos::Loval(unsigned int par, unsigned int maxcalls, double toler) co } // #ifdef DEBUG -// std::cout << "\n--------- MnMinos --------- \n Determination of negative Minos error for parameter " +// std::cout << "\n--------- MnMinos --------- \n Determination of negative Minos error for parameter " // << par << std::endl; -// #endif +// #endif -// assert(fMinimum.IsValid()); +// assert(fMinimum.IsValid()); // assert(!fMinimum.UserState().Parameter(par).IsFixed()); // assert(!fMinimum.UserState().Parameter(par).IsConst()); // if(maxcalls == 0) { @@ -225,19 +225,19 @@ MnCross MnMinos::Loval(unsigned int par, unsigned int maxcalls, double toler) co // maxcalls = 2*(nvar+1)*(200 + 100*nvar + 5*nvar*nvar); // } // std::vector<unsigned int> para(1, par); - + // MnUserParameterState upar = fMinimum.UserState(); // double err = upar.Error(par); // double val = upar.Value(par) - err; // std::vector<double> xmid(1, val); // std::vector<double> xdir(1, -err); - + // double up = fFCN.Up(); // unsigned int ind = upar.IntOfExt(par); // MnAlgebraicSymMatrix m = fMinimum.Error().Matrix(); // double xunit = sqrt(up/m(ind,ind)); -// // get internal parameters -// const MnAlgebraicVector & xt = fMinimum.Parameters().Vec(); +// // get internal parameters +// const MnAlgebraicVector & xt = fMinimum.Parameters().Vec(); // for(unsigned int i = 0; i < m.Nrow(); i++) { // if(i == ind) continue; @@ -245,47 +245,47 @@ MnCross MnMinos::Loval(unsigned int par, unsigned int maxcalls, double toler) co // double xnew = xt(i) - xdev; -// // transform to external values -// double unew = upar.Int2ext(i, xnew); +// // transform to external values +// double unew = upar.Int2ext(i, xnew); // unsigned int ext = upar.ExtOfInt(i); -// #ifdef DEBUG +// #ifdef DEBUG // std::cout << "Parameter " << ext << " is set from " << upar.Value(ext) << " to " << unew << std::endl; // #endif // upar.SetValue(ext, unew); // } - + // upar.Fix(par); // upar.SetValue(par, val); // #ifdef DEBUG // std::cout << "Parameter " << par << " is fixed and set from " << fMinimum.UserState().Value(par) << " to " << val << std::endl; -// #endif - +// #endif + // // double edmmax = 0.5*0.1*fFCN.Up()*1.e-3; // double toler = 0.01; // MnFunctionCross cross(fFCN, upar, fMinimum.Fval(), fStrategy); - + // MnCross aopt = cross(para, xmid, xdir, toler, maxcalls); - + // #ifdef DEBUG // std::cout<<"----- MnMinos: aopt found from MnFunctionCross = "<<aopt.Value()<<std::endl << std::endl; // #endif - + // #ifdef WARNINGMSG -// if(aopt.AtLimit()) +// if(aopt.AtLimit()) // MN_INFO_VAL2("MnMinos Parameter is at Lower limit.",par); // if(aopt.AtMaxFcn()) // MN_INFO_VAL2("MnMinos maximum number of function calls exceeded for Parameter ",par); // if(aopt.NewMinimum()) // MN_INFO_VAL2("MnMinos new Minimum found while looking for Parameter ",par); -// if(!aopt.IsValid()) +// if(!aopt.IsValid()) // MN_INFO_VAL2("MnMinos could not find Lower Value for Parameter ",par); // #endif - + // return aopt; - + // } diff --git a/ThirdParty/RootMinimizers/src/Minuit2/MnParabolaFactory.cxx b/ThirdParty/RootMinimizers/src/Minuit2/MnParabolaFactory.cxx index c1ac0962d54d7e8d99f5f49d90efd74dcb95902d..4ce57ff9dda8bc0796a8114f742d9f8efb634838 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/MnParabolaFactory.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/MnParabolaFactory.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -18,42 +18,42 @@ namespace ROOT { // #include <iostream> -MnParabola MnParabolaFactory::operator()(const MnParabolaPoint& p1, - const MnParabolaPoint& p2, +MnParabola MnParabolaFactory::operator()(const MnParabolaPoint& p1, + const MnParabolaPoint& p2, const MnParabolaPoint& p3) const { - // construct the parabola from 3 points p1,p2,p3 + // construct the parabola from 3 points p1,p2,p3 double x1 = p1.X(); double x2 = p2.X(); double x3 = p3.X(); double dx12 = x1-x2; double dx13 = x1-x3; double dx23 = x2-x3; - + // std::cout<<"MnParabolaFactory x1, x2, x3: "<<x1<<" "<<x2<<" "<<x3<<std::endl; - + double xm = (x1+x2+x3)/3.; x1 -= xm; x2 -= xm; x3 -= xm; - + double y1 = p1.Y(); double y2 = p2.Y(); double y3 = p3.Y(); // std::cout<<"MnParabolaFactory y1, y2, y3: "<<y1<<" "<<y2<<" "<<y3<<std::endl; - + double a = y1/(dx12*dx13) - y2/(dx12*dx23) + y3/(dx13*dx23); double b = -y1*(x2+x3)/(dx12*dx13) + y2*(x1+x3)/(dx12*dx23) - y3*(x1+x2)/(dx13*dx23); double c = y1 - a*x1*x1 - b*x1; - + c += xm*(xm*a - b); b -= 2.*xm*a; - + // std::cout<<"a,b,c= "<<a<<" "<<b<<" "<<c<<std::endl; return MnParabola(a, b, c); } -MnParabola MnParabolaFactory::operator()(const MnParabolaPoint& p1, - double dxdy1, +MnParabola MnParabolaFactory::operator()(const MnParabolaPoint& p1, + double dxdy1, const MnParabolaPoint& p2) const { // construct the parabola from 2 points + derivative at first point dxdy1 double x1 = p1.X(); @@ -62,12 +62,12 @@ MnParabola MnParabolaFactory::operator()(const MnParabolaPoint& p1, double xx2 = x2*x2; double y1 = p1.Y(); double y12 = p1.Y() - p2.Y(); - + double det = xx1-xx2 - 2.*x1*(x1-x2); double a = -( y12 + (x2-x1)*dxdy1)/det; double b = -( -2.*x1*y12 + (xx1-xx2)*dxdy1)/det; double c = y1 - a*xx1 - b*x1; - + return MnParabola(a, b, c); } diff --git a/ThirdParty/RootMinimizers/src/Minuit2/MnParameterScan.cxx b/ThirdParty/RootMinimizers/src/Minuit2/MnParameterScan.cxx index 8f4e5508cd6e4b01e3f2ad8b93f3ee3bde0c74bd..7f418450cb177964aa41410b056e08aff21ea7ec 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/MnParameterScan.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/MnParameterScan.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -20,35 +20,35 @@ MnParameterScan::MnParameterScan(const FCNBase& fcn, const MnUserParameters& par MnParameterScan::MnParameterScan(const FCNBase& fcn, const MnUserParameters& par, double fval) : fFCN(fcn), fParameters(par), fAmin(fval) {} std::vector<std::pair<double, double> > MnParameterScan::operator()(unsigned int par, unsigned int maxsteps, double low, double high) { - // do the scan for parameter par between low and high values - + // do the scan for parameter par between low and high values + //if(maxsteps > 101) maxsteps = 101; std::vector<std::pair<double, double> > result; result.reserve(maxsteps+1); std::vector<double> params = fParameters.Params(); result.push_back(std::pair<double, double>(params[par], fAmin)); - + if(low > high) return result; if(maxsteps < 2) return result; - + if(low == 0. && high == 0.) { low = params[par] - 2.*fParameters.Error(par); high = params[par] + 2.*fParameters.Error(par); } - + if(low == 0. && high == 0. && fParameters.Parameter(par).HasLimits()) { if(fParameters.Parameter(par).HasLowerLimit()) low = fParameters.Parameter(par).LowerLimit(); if(fParameters.Parameter(par).HasUpperLimit()) high = fParameters.Parameter(par).UpperLimit(); } - + if(fParameters.Parameter(par).HasLimits()) { if(fParameters.Parameter(par).HasLowerLimit()) low = std::max(low, fParameters.Parameter(par).LowerLimit()); if(fParameters.Parameter(par).HasUpperLimit()) high = std::min(high, fParameters.Parameter(par).UpperLimit()); } - + double x0 = low; double stp = (high - low)/double(maxsteps - 1); for(unsigned int i = 0; i < maxsteps; i++) { @@ -60,7 +60,7 @@ std::vector<std::pair<double, double> > MnParameterScan::operator()(unsigned int } result.push_back(std::pair<double, double>(params[par], fval)); } - + return result; } diff --git a/ThirdParty/RootMinimizers/src/Minuit2/MnPlot.cxx b/ThirdParty/RootMinimizers/src/Minuit2/MnPlot.cxx index 14eaa872c586fcca3f25b3ca0fd271d123ef377a..89f6ac1cec10f8970b3e547cd399cdcdcd898d97 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/MnPlot.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/MnPlot.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -21,15 +21,15 @@ void MnPlot::operator()(const std::vector<std::pair<double,double> >& points) co std::vector<double> x; x.reserve(points.size()); std::vector<double> y; y.reserve(points.size()); std::vector<char> chpt; chpt.reserve(points.size()); - + for(std::vector<std::pair<double,double> >::const_iterator ipoint = points.begin(); ipoint != points.end(); ipoint++) { x.push_back((*ipoint).first); y.push_back((*ipoint).second); chpt.push_back('*'); } - + mnplot(&(x.front()), &(y.front()), &(chpt.front()), points.size(), Width(), Length()); - + } void MnPlot::operator()(double xmin, double ymin, const std::vector<std::pair<double,double> >& points) const { @@ -43,13 +43,13 @@ void MnPlot::operator()(double xmin, double ymin, const std::vector<std::pair<do std::vector<char> chpt; chpt.reserve(points.size()+2); chpt.push_back(' '); chpt.push_back('X'); - + for(std::vector<std::pair<double,double> >::const_iterator ipoint = points.begin(); ipoint != points.end(); ipoint++) { x.push_back((*ipoint).first); y.push_back((*ipoint).second); chpt.push_back('*'); } - + mnplot(&(x.front()), &(y.front()), &(chpt.front()), points.size()+2, Width(), Length()); } diff --git a/ThirdParty/RootMinimizers/src/Minuit2/MnPosDef.cxx b/ThirdParty/RootMinimizers/src/Minuit2/MnPosDef.cxx index 289a66a3a85228d9caa37f96f1d15da45361a819..abb4380032ebfdc6e3db54f65b87000abc4cbdc5 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/MnPosDef.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/MnPosDef.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -12,7 +12,7 @@ #include "Minuit2/MnMachinePrecision.h" #if defined(DEBUG) || defined(WARNINGMSG) -#include "Minuit2/MnPrint.h" +#include "Minuit2/MnPrint.h" #endif #include <algorithm> @@ -27,7 +27,7 @@ LAVector eigenvalues(const LASymMatrix&); MinimumState MnPosDef::operator()(const MinimumState& st, const MnMachinePrecision& prec) const { - // interface from minimum state + // interface from minimum state MinimumError err = (*this)(st.Error(), prec); return MinimumState(st.Parameters(), err, st.Gradient(), st.Edm(), st.NFcn()); } @@ -39,33 +39,33 @@ MinimumError MnPosDef::operator()(const MinimumError& e, const MnMachinePrecisio if(err.size() == 1 && err(0,0) < prec.Eps()) { err(0,0) = 1.; return MinimumError(err, MinimumError::MnMadePosDef()); - } + } if(err.size() == 1 && err(0,0) > prec.Eps()) { return e; - } + } // std::cout<<"MnPosDef init matrix= "<<err<<std::endl; - + double epspdf = std::max(1.e-6, prec.Eps2()); double dgmin = err(0,0); - + for(unsigned int i = 0; i < err.Nrow(); i++) { #ifdef WARNINGMSG - if(err(i,i) <= 0 /* prec.Eps2() */ ) + if(err(i,i) <= 0 /* prec.Eps2() */ ) MN_INFO_VAL2("negative or zero diagonal element in covariance matrix",i); #endif if(err(i,i) < dgmin) dgmin = err(i,i); } double dg = 0.; if(dgmin <= 0) { - //dg = 1. + epspdf - dgmin; - dg = 0.5 + epspdf - dgmin; - // dg = 0.5*(1. + epspdf - dgmin); + //dg = 1. + epspdf - dgmin; + dg = 0.5 + epspdf - dgmin; + // dg = 0.5*(1. + epspdf - dgmin); #ifdef WARNINGMSG MN_INFO_VAL2("added to diagonal of Error matrix a value",dg); #endif //std::cout << "Error matrix " << err << std::endl; } - + MnAlgebraicVector s(err.Nrow()); MnAlgebraicSymMatrix p(err.Nrow()); for(unsigned int i = 0; i < err.Nrow(); i++) { @@ -76,7 +76,7 @@ MinimumError MnPosDef::operator()(const MinimumError& e, const MnMachinePrecisio p(i,j) = err(i,j)*s(i)*s(j); } } - + //std::cout<<"MnPosDef p: "<<p<<std::endl; MnAlgebraicVector eval = eigenvalues(p); double pmin = eval(0); @@ -84,7 +84,7 @@ MinimumError MnPosDef::operator()(const MinimumError& e, const MnMachinePrecisio //std::cout<<"pmin= "<<pmin<<" pmax= "<<pmax<<std::endl; pmax = std::max(fabs(pmax), 1.); if(pmin > epspdf*pmax) return MinimumError(err, e.Dcovar()); - + double padd = 0.001*pmax - pmin; #ifdef DEBUG std::cout<<"eigenvalues: "<<std::endl; diff --git a/ThirdParty/RootMinimizers/src/Minuit2/MnPrint.cxx b/ThirdParty/RootMinimizers/src/Minuit2/MnPrint.cxx index e9991b1f33036d07d5893b4de23980d599509ec4..263b2661f42c0b26d30844e45bf17f6f5722452e 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/MnPrint.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/MnPrint.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -32,36 +32,43 @@ namespace ROOT { namespace Minuit2 { #ifdef DEBUG -int gPrintLevel = 3; +int gPrintLevel = 3; #else -int gPrintLevel = 0; +int gPrintLevel = 0; #endif -int MnPrint::SetLevel(int level) { +int MnPrint::SetLevel(int level) { int prevLevel = gPrintLevel; gPrintLevel = level; return prevLevel; } -int MnPrint::Level( ) { +int MnPrint::Level( ) { return gPrintLevel; } -void MnPrint::PrintState(std::ostream & os, const MinimumState & state, const char * msg, int iter) { +void MnPrint::PrintFcn(std::ostream & os, double value, bool endline) { + int pr = os.precision(PRECISION); + os << value; + if (endline) os << std::endl; + os.precision(pr); +} + +void MnPrint::PrintState(std::ostream & os, const MinimumState & state, const char * msg, int iter) { // helper function to print function value, edm and ncalls from state in one single line MnPrint::PrintState(os, state.Fval(), state.Edm(), state.NFcn(), msg, iter); } -void MnPrint::PrintState(std::ostream & os, double fval, double edm, int ncalls, const char * msg, int iter) { +void MnPrint::PrintState(std::ostream & os, double fval, double edm, int ncalls, const char * msg, int iter) { // helper function to print function value, edm and ncalls and message in one single line - os << msg; - if (iter>=0) os << std::setw(3) << iter; + os << msg; + if (iter>=0) os << std::setw(3) << iter; int pr = os.precision(PRECISION); const int width = PRECISION+3; os << " - FCN = " << std::setw(width) << fval; os.precision(pr); - os << " Edm = " << std::setw(12) << edm << " NCalls = " << std::setw(6) << ncalls; + os << " Edm = " << std::setw(12) << edm << " NCalls = " << std::setw(6) << ncalls; os << std::endl; } @@ -70,10 +77,10 @@ std::ostream& operator<<(std::ostream& os, const LAVector& vec) { // print a vector os << "LAVector parameters:" << std::endl; int pr = os.precision(PRECISION); - { + { int nrow = vec.size(); for (int i = 0; i < nrow; i++) { - os.width(WIDTH); + os.width(WIDTH); os << vec(i) << std::endl; } } @@ -85,7 +92,7 @@ std::ostream& operator<<(std::ostream& os, const LASymMatrix& matrix) { // print a matrix os << "LASymMatrix parameters:" << std::endl; int pr = os.precision(8); - { + { //os << std::endl; int n = matrix.Nrow(); for (int i = 0; i < n; i++) { @@ -102,16 +109,16 @@ std::ostream& operator<<(std::ostream& os, const LASymMatrix& matrix) { std::ostream& operator<<(std::ostream& os, const MnUserParameters& par) { // print the MnUserParameter object os << std::endl; - + os << "# ext. |" << "| Name |" << "| type |" << "| Value |" << "| Error +/- " << std::endl; - + os << std::endl; int pr = os.precision(); - + bool atLoLim = false; bool atHiLim = false; for(std::vector<MinuitParameter>::const_iterator ipar = par.Parameters().begin(); ipar != par.Parameters().end(); ipar++) { - os << std::setw(4) << (*ipar).Number() << std::setw(5) << "||"; + os << std::setw(4) << (*ipar).Number() << std::setw(5) << "||"; os << std::setw(10) << (*ipar).Name() << std::setw(3) << "||"; if((*ipar).IsConst()) { os << " const ||" << std::setprecision(PRECISION) << std::setw(WIDTH) << (*ipar).Value() << " ||" << std::endl; @@ -136,7 +143,7 @@ std::ostream& operator<<(std::ostream& os, const MnUserParameters& par) { os << " free ||" << std::setprecision(PRECISION) << std::setw(WIDTH) << (*ipar).Value() << " ||" << std::setw(12) << (*ipar).Error() << std::endl; else os << " free ||" << std::setprecision(PRECISION) << std::setw(WIDTH) << (*ipar).Value() << " ||" << std::setw(12) << "no" << std::endl; - + } } os << std::endl; @@ -144,17 +151,17 @@ std::ostream& operator<<(std::ostream& os, const MnUserParameters& par) { if(atHiLim) os << "** Parameter is at Upper limit" << std::endl; os << std::endl; os.precision(pr); - + return os; } std::ostream& operator<<(std::ostream& os, const MnUserCovariance& matrix) { // print the MnUserCovariance os << std::endl; - + os << "MnUserCovariance: " << std::endl; int pr = os.precision(6); - { + { os << std::endl; unsigned int n = matrix.Nrow(); for (unsigned int i = 0; i < n; i++) { @@ -167,8 +174,8 @@ std::ostream& operator<<(std::ostream& os, const MnUserCovariance& matrix) { os << std::endl; os << "MnUserCovariance Parameter correlations: " << std::endl; - - { + + { os << std::endl; unsigned int n = matrix.Nrow(); for (unsigned int i = 0; i < n; i++) { @@ -180,57 +187,60 @@ std::ostream& operator<<(std::ostream& os, const MnUserCovariance& matrix) { os << std::endl; } } - + os.precision(pr); - return os; + return os; } std::ostream& operator<<(std::ostream& os, const MnGlobalCorrelationCoeff& coeff) { // print the global correlation coefficient os << std::endl; - + os << "MnGlobalCorrelationCoeff: " << std::endl; int pr = os.precision(6); - { + { os << std::endl; for (unsigned int i = 0; i < coeff.GlobalCC().size(); i++) { os.width(13); os << coeff.GlobalCC()[i]; os << std::endl; } } - + os.precision(pr); - return os; + return os; } std::ostream& operator<<(std::ostream& os, const MnUserParameterState& state) { // print the MnUserParameterState os << std::endl; - + if(!state.IsValid()) { os << std::endl; os <<"WARNING: MnUserParameterState is not valid."<<std::endl; os << std::endl; } int pr = os.precision(PRECISION); - + os <<"# of function calls: "<<state.NFcn()<<std::endl; os <<"function Value: " << state.Fval()<<std::endl; os <<"expected distance to the Minimum (edm): " << state.Edm()<<std::endl; os <<"external parameters: "<<state.Parameters()<<std::endl; + os <<"covariance matrix status: " << state.CovarianceStatus() << std::endl; if(state.HasCovariance()) os <<"covariance matrix: "<<state.Covariance()<<std::endl; - if(state.HasGlobalCC()) + else + os <<"covariance matrix is not present or not valid "<<std::endl; + if(state.HasGlobalCC()) os <<"global correlation coefficients : "<<state.GlobalCC()<<std::endl; - + if(!state.IsValid()) os <<"WARNING: MnUserParameterState is not valid."<<std::endl; - + os << std::endl; os.precision(pr); return os; -} +} std::ostream& operator<<(std::ostream& os, const FunctionMinimum& min) { // print the FunctionMinimum @@ -242,29 +252,29 @@ std::ostream& operator<<(std::ostream& os, const FunctionMinimum& min) { os <<"Minuit did successfully converge."<<std::endl; } int pr = os.precision(PRECISION); - + os <<"# of function calls: "<<min.NFcn()<<std::endl; os <<"minimum function Value: " << min.Fval()<<std::endl; os <<"minimum edm: " << min.Edm()<<std::endl; os <<"minimum internal state vector: "<<min.Parameters().Vec()<<std::endl; - if(min.HasValidCovariance()) + if(min.HasValidCovariance()) os <<"minimum internal covariance matrix: "<<min.Error().Matrix()<<std::endl; - + os << min.UserParameters() << std::endl; //os << min.UserCovariance() << std::endl; //os << min.UserState().GlobalCC() << std::endl; - + if(!min.IsValid()) { os <<"WARNING: FunctionMinimum is invalid: " << std::endl; - if ( !min.State().IsValid() ) + if ( !min.State().IsValid() ) os << "\t State is invalid" << std::endl; - if ( min.IsAboveMaxEdm() ) + if ( min.IsAboveMaxEdm() ) os << "\t Edm is above max" << std::endl; - if ( min.HasReachedCallLimit() ) + if ( min.HasReachedCallLimit() ) os << "\t Reached call limit" << std::endl; } - + os << std::endl; os.precision(pr); @@ -272,17 +282,17 @@ std::ostream& operator<<(std::ostream& os, const FunctionMinimum& min) { } std::ostream& operator<<(std::ostream& os, const MinimumState& min) { - + os << std::endl; int pr = os.precision(PRECISION); - + os <<"minimum function Value: " << min.Fval()<<std::endl; os <<"minimum edm: " << min.Edm()<<std::endl; os <<"minimum internal state vector: "<<min.Vec()<<std::endl; os <<"minimum internal Gradient vector: "<<min.Gradient().Vec()<<std::endl; - if(min.HasCovariance()) + if(min.HasCovariance()) os <<"minimum internal covariance matrix: "<<min.Error().Matrix()<<std::endl; - + os << std::endl; os.precision(pr); @@ -292,22 +302,22 @@ std::ostream& operator<<(std::ostream& os, const MinimumState& min) { std::ostream& operator<<(std::ostream& os, const MnMachinePrecision& prec) { // print the Precision os << std::endl; - + int pr = os.precision(PRECISION); os <<"current machine precision is set to "<<prec.Eps()<<std::endl; - + os << std::endl; os.precision(pr); - + return os; } std::ostream& operator<<(std::ostream& os, const MinosError& me) { // print the Minos Error os << std::endl; - + os <<"Minos # of function calls: "<<me.NFcn()<<std::endl; - + if(!me.IsValid()) os << "Minos Error is not valid." <<std::endl; if(!me.LowerValid()) @@ -332,12 +342,12 @@ std::ostream& operator<<(std::ostream& os, const MinosError& me) { } int pr = os.precision(); - + os << "# ext. |" << "| Name |" << "| Value@min |" << "| negative |" << "| positive " << std::endl; - os << std::setw(4) << me.Parameter() << std::setw(5) << "||"; + os << std::setw(4) << me.Parameter() << std::setw(5) << "||"; os << std::setw(10) << me.LowerState().Name(me.Parameter()) << std::setw(3) << "||"; os << std::setprecision(PRECISION) << std::setw(WIDTH) << me.Min() << " ||" << std::setprecision(PRECISION) << std::setw(WIDTH) << me.Lower() << " ||" << std::setw(WIDTH) << me.Upper() << std::endl; - + os << std::endl; os.precision(pr); @@ -358,7 +368,7 @@ std::ostream& operator<<(std::ostream& os, const ContoursError& ce) { os << ipar - ce().begin() <<" "<< (*ipar).first <<" "<< (*ipar).second <<std::endl; } os << std::endl; - + return os; } diff --git a/ThirdParty/RootMinimizers/src/Minuit2/MnScan.cxx b/ThirdParty/RootMinimizers/src/Minuit2/MnScan.cxx index e6b3ddfd95a2163ab36450c291fb04bf7e6f9a79..677f853dc32eaf872fdd385211b4b3b5033b9379 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/MnScan.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/MnScan.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -19,13 +19,13 @@ std::vector<std::pair<double, double> > MnScan::Scan(unsigned int par, unsigned // perform a scan of the function in the parameter par MnParameterScan scan(fFCN, fState.Parameters()); double amin = scan.Fval(); - + std::vector<std::pair<double, double> > result = scan(par, maxsteps, low, high); if(scan.Fval() < amin) { fState.SetValue(par, scan.Parameters().Value(par)); amin = scan.Fval(); } - + return result; } diff --git a/ThirdParty/RootMinimizers/src/Minuit2/MnSeedGenerator.cxx b/ThirdParty/RootMinimizers/src/Minuit2/MnSeedGenerator.cxx index 2943fe00b876f9c8c8c8422d0ce6c75b0f2b4c07..fa986d2761f7f62c3df7d288204476f0f602f715 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/MnSeedGenerator.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/MnSeedGenerator.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -59,16 +59,17 @@ MinimumSeed MnSeedGenerator::operator()(const MnFcn& fcn, const GradientCalculat #endif int printLevel = MnPrint::Level(); - + // initial starting values MnAlgebraicVector x(n); for(unsigned int i = 0; i < n; i++) x(i) = st.IntParameters()[i]; double fcnmin = fcn(x); - if (printLevel > 1) { - std::cout << "MnSeedGenerator: for initial parameters FCN = " << fcnmin << std::endl; + if (printLevel > 1) { + std::cout << "MnSeedGenerator: for initial parameters FCN = "; + MnPrint::PrintFcn(std::cout,fcnmin); } - + MinimumParameters pa(x, fcnmin); FunctionGradient dgrad = gc(pa); MnAlgebraicSymMatrix mat(n); @@ -82,30 +83,31 @@ MinimumSeed MnSeedGenerator::operator()(const MnFcn& fcn, const GradientCalculat mat(i,i) = (fabs(dgrad.G2()(i)) > prec.Eps2() ? 1./dgrad.G2()(i) : 1.); } MinimumError err(mat, dcovar); + double edm = VariableMetricEDMEstimator().Estimate(dgrad, err); MinimumState state(pa, err, dgrad, edm, fcn.NumOfCalls()); if (printLevel >1) { - MnPrint::PrintState(std::cout, state, "MnSeedGenerator: Initial state: "); + MnPrint::PrintState(std::cout, state, "MnSeedGenerator: Initial state: "); } - + NegativeG2LineSearch ng2ls; if(ng2ls.HasNegativeG2(dgrad, prec)) { #ifdef DEBUG std::cout << "MnSeedGenerator: Negative G2 Found: " << std::endl; - std::cout << x << std::endl; - std::cout << dgrad.Grad() << std::endl; - std::cout << dgrad.G2() << std::endl; + std::cout << x << std::endl; + std::cout << dgrad.Grad() << std::endl; + std::cout << dgrad.G2() << std::endl; #endif state = ng2ls(fcn, state, gc, prec); if (printLevel >1) { - MnPrint::PrintState(std::cout, state, "MnSeedGenerator: Negative G2 found - new state: "); + MnPrint::PrintState(std::cout, state, "MnSeedGenerator: Negative G2 found - new state: "); } } - + if(stra.Strategy() == 2 && !st.HasCovariance()) { //calculate full 2nd derivative #ifdef DEBUG @@ -114,12 +116,12 @@ MinimumSeed MnSeedGenerator::operator()(const MnFcn& fcn, const GradientCalculat MinimumState tmp = MnHesse(stra)(fcn, state, st.Trafo()); if (printLevel >1) { - MnPrint::PrintState(std::cout, tmp, "MnSeedGenerator: run Hesse - new state: "); + MnPrint::PrintState(std::cout, tmp, "MnSeedGenerator: run Hesse - new state: "); } return MinimumSeed(tmp, st.Trafo()); } - + return MinimumSeed(state, st.Trafo()); } @@ -128,18 +130,18 @@ MinimumSeed MnSeedGenerator::operator()(const MnFcn& fcn, const AnalyticalGradie // find seed (initial point for minimization) using analytical gradient unsigned int n = st.VariableParameters(); const MnMachinePrecision& prec = st.Precision(); - + // initial starting values MnAlgebraicVector x(n); for(unsigned int i = 0; i < n; i++) x(i) = st.IntParameters()[i]; double fcnmin = fcn(x); MinimumParameters pa(x, fcnmin); - + InitialGradientCalculator igc(fcn, st.Trafo(), stra); FunctionGradient tmp = igc(pa); FunctionGradient grd = gc(pa); FunctionGradient dgrad(grd.Grad(), tmp.G2(), tmp.Gstep()); - + if(gc.CheckGradient()) { bool good = true; HessianGradientCalculator hgc(fcn, st.Trafo(), MnStrategy(2)); @@ -148,7 +150,7 @@ MinimumSeed MnSeedGenerator::operator()(const MnFcn& fcn, const AnalyticalGradie if(fabs(hgrd.first.Grad()(i) - grd.Grad()(i)) > hgrd.second(i)) { #ifdef WARNINGMSG MN_INFO_MSG("MnSeedGenerator:gradient discrepancy of external Parameter too large"); - int externalParameterIndex = st.Trafo().ExtOfInt(i); + int externalParameterIndex = st.Trafo().ExtOfInt(i); const char * parameter_name = st.Trafo().Name(externalParameterIndex); MN_INFO_VAL(parameter_name); MN_INFO_VAL(externalParameterIndex); @@ -164,7 +166,7 @@ MinimumSeed MnSeedGenerator::operator()(const MnFcn& fcn, const AnalyticalGradie assert(good); } } - + MnAlgebraicSymMatrix mat(n); double dcovar = 1.; if(st.HasCovariance()) { @@ -178,19 +180,19 @@ MinimumSeed MnSeedGenerator::operator()(const MnFcn& fcn, const AnalyticalGradie MinimumError err(mat, dcovar); double edm = VariableMetricEDMEstimator().Estimate(dgrad, err); MinimumState state(pa, err, dgrad, edm, fcn.NumOfCalls()); - + NegativeG2LineSearch ng2ls; if(ng2ls.HasNegativeG2(dgrad, prec)) { Numerical2PGradientCalculator ngc(fcn, st.Trafo(), stra); state = ng2ls(fcn, state, ngc, prec); } - + if(stra.Strategy() == 2 && !st.HasCovariance()) { //calculate full 2nd derivative MinimumState tmpState = MnHesse(stra)(fcn, state, st.Trafo()); return MinimumSeed(tmpState, st.Trafo()); } - + return MinimumSeed(state, st.Trafo()); } diff --git a/ThirdParty/RootMinimizers/src/Minuit2/MnStrategy.cxx b/ThirdParty/RootMinimizers/src/Minuit2/MnStrategy.cxx index f8609508b81129ffbae81d4640e7804b7472141e..22503983a61741c33830d33ce5a7a641a5332b86 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/MnStrategy.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/MnStrategy.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * diff --git a/ThirdParty/RootMinimizers/src/Minuit2/MnTiny.cxx b/ThirdParty/RootMinimizers/src/Minuit2/MnTiny.cxx index a0f5e64c8e283b979c165ed7f22145651d752338..7a1e62a2a898a2a96a5fe32b38b4334c5b8ebd54 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/MnTiny.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/MnTiny.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -16,7 +16,7 @@ namespace ROOT { double MnTiny::One() const {return fOne;} -double MnTiny::operator()(double epsp1) const { +double MnTiny::operator()(volatile double epsp1) const { // evaluate minimal diference between two floating points double result = epsp1 - One(); return result; diff --git a/ThirdParty/RootMinimizers/src/Minuit2/MnTraceObject.cxx b/ThirdParty/RootMinimizers/src/Minuit2/MnTraceObject.cxx index a3478cfdcf3a5a6de0f4dbf3c14adc48d9c08749..06dbc1c6c6751a066959f5e9a555c36f93670306 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/MnTraceObject.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/MnTraceObject.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Author: L. Moneta 2012 +// Author: L. Moneta 2012 /********************************************************************** * * @@ -20,25 +20,25 @@ namespace ROOT { void MnTraceObject::operator() (int iter, const MinimumState & state) { MnPrint::PrintState(std::cout, state, "iteration # ",iter); - if (!fUserState) return; + if (!fUserState) return; // print also parameters and derivatives - std::cout << "\t" << std::setw(12) << " " << " " - << std::setw(12) << " ext value " << " " - << std::setw(12) << " int value " << " " + std::cout << "\t" << std::setw(12) << " " << " " + << std::setw(12) << " ext value " << " " + << std::setw(12) << " int value " << " " << std::setw(12) << " gradient " << std::endl; - int firstPar = 0; + int firstPar = 0; int lastPar = state.Vec().size(); - if (fParNumber >= 0 && fParNumber < lastPar) { + if (fParNumber >= 0 && fParNumber < lastPar) { firstPar = fParNumber; lastPar = fParNumber+1; } - for (int ipar = firstPar; ipar <lastPar; ++ipar) { + for (int ipar = firstPar; ipar <lastPar; ++ipar) { int epar = fUserState->Trafo().ExtOfInt(ipar); double eval = fUserState->Trafo().Int2ext(ipar, state.Vec()(ipar) ); - std::cout << "\t" << std::setw(12) << fUserState->Name(epar) << " " - << std::setw(12) << eval << " " - << std::setw(12) << state.Vec()(ipar) << " " + std::cout << "\t" << std::setw(12) << fUserState->Name(epar) << " " + << std::setw(12) << eval << " " + << std::setw(12) << state.Vec()(ipar) << " " << std::setw(12) << state.Gradient().Vec()(ipar) << std::endl; } } diff --git a/ThirdParty/RootMinimizers/src/Minuit2/MnUserFcn.cxx b/ThirdParty/RootMinimizers/src/Minuit2/MnUserFcn.cxx index 6e25631246912df829c446315e3bce5a7650ecdc..92e776e14941fc96e772fc7672c05919f9bb56d5 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/MnUserFcn.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/MnUserFcn.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -17,7 +17,7 @@ namespace ROOT { double MnUserFcn::operator()(const MnAlgebraicVector& v) const { - // call Fcn function transforming from a MnAlgebraicVector of internal values to a std::vector of external ones + // call Fcn function transforming from a MnAlgebraicVector of internal values to a std::vector of external ones fNumCall++; // calling fTransform() like here was not thread safe because it was using a cached vector @@ -25,21 +25,21 @@ double MnUserFcn::operator()(const MnAlgebraicVector& v) const { // make a new thread-safe implementation creating a vector each time // a bit slower few% in stressFit and 10% in Rosenbrock function but it is negligible in big fits - // get first initial values of parameter (in case some one is fixed) + // get first initial values of parameter (in case some one is fixed) std::vector<double> vpar(fTransform.InitialParValues().begin(), fTransform.InitialParValues().end() ); const std::vector<MinuitParameter>& parameters = fTransform.Parameters(); - unsigned int n = v.size(); + unsigned int n = v.size(); for (unsigned int i = 0; i < n; i++) { int ext = fTransform.ExtOfInt(i); if (parameters[ext].HasLimits()) { vpar[ext] = fTransform.Int2ext(i, v(i)); - } + } else { vpar[ext] = v(i); } } - return Fcn()(vpar); + return Fcn()(vpar); } } // namespace Minuit2 diff --git a/ThirdParty/RootMinimizers/src/Minuit2/MnUserParameterState.cxx b/ThirdParty/RootMinimizers/src/Minuit2/MnUserParameterState.cxx index 9346c9244234cb7484c5886deb61fdf81150e4b8..82bbadebc9f58761ae398bb85bc31f4ac04f25c7 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/MnUserParameterState.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/MnUserParameterState.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -11,7 +11,7 @@ #include "Minuit2/MnCovarianceSqueeze.h" #include "Minuit2/MinimumState.h" -#include "Minuit2/MnPrint.h" +#include "Minuit2/MnPrint.h" namespace ROOT { @@ -22,19 +22,19 @@ namespace ROOT { // // construct from user parameters (befor minimization) // -MnUserParameterState::MnUserParameterState(const std::vector<double>& par, const std::vector<double>& err) : - fValid(true), fCovarianceValid(false), fGCCValid(false), fCovStatus(-1), fFVal(0.), fEDM(0.), fNFcn(0), fParameters(MnUserParameters(par, err)), fCovariance(MnUserCovariance()), fGlobalCC(MnGlobalCorrelationCoeff()), fIntParameters(par), fIntCovariance(MnUserCovariance()) +MnUserParameterState::MnUserParameterState(const std::vector<double>& par, const std::vector<double>& err) : + fValid(true), fCovarianceValid(false), fGCCValid(false), fCovStatus(-1), fFVal(0.), fEDM(0.), fNFcn(0), fParameters(MnUserParameters(par, err)), fCovariance(MnUserCovariance()), fGlobalCC(MnGlobalCorrelationCoeff()), fIntParameters(par), fIntCovariance(MnUserCovariance()) {} -MnUserParameterState::MnUserParameterState(const MnUserParameters& par) : +MnUserParameterState::MnUserParameterState(const MnUserParameters& par) : fValid(true), fCovarianceValid(false), fGCCValid(false), fCovStatus(-1), fFVal(0.), fEDM(0.), fNFcn(0), fParameters(par), fCovariance(MnUserCovariance()), fGlobalCC(MnGlobalCorrelationCoeff()), fIntParameters(std::vector<double>()), fIntCovariance(MnUserCovariance()) { // construct from user parameters (befor minimization) - + for(std::vector<MinuitParameter>::const_iterator ipar = MinuitParameters().begin(); ipar != MinuitParameters().end(); ipar++) { if((*ipar).IsConst() || (*ipar).IsFixed()) continue; - if((*ipar).HasLimits()) + if((*ipar).HasLimits()) fIntParameters.push_back(Ext2int((*ipar).Number(), (*ipar).Value())); - else + else fIntParameters.push_back((*ipar).Value()); } } @@ -42,10 +42,10 @@ MnUserParameterState::MnUserParameterState(const MnUserParameters& par) : // // construct from user parameters + errors (befor minimization) // -MnUserParameterState::MnUserParameterState(const std::vector<double>& par, const std::vector<double>& cov, unsigned int nrow) : - fValid(true), fCovarianceValid(true), fGCCValid(false), fCovStatus(-1), fFVal(0.), fEDM(0.), fNFcn(0), +MnUserParameterState::MnUserParameterState(const std::vector<double>& par, const std::vector<double>& cov, unsigned int nrow) : + fValid(true), fCovarianceValid(true), fGCCValid(false), fCovStatus(-1), fFVal(0.), fEDM(0.), fNFcn(0), fParameters(MnUserParameters()), fCovariance(MnUserCovariance(cov, nrow)), fGlobalCC(MnGlobalCorrelationCoeff()), fIntParameters(par), fIntCovariance(MnUserCovariance(cov, nrow)) { - // construct from user parameters + errors (before minimization) using std::vector for parameter error and // an std::vector of size n*(n+1)/2 for the covariance matrix and n (rank of cov matrix) + // construct from user parameters + errors (before minimization) using std::vector for parameter error and // an std::vector of size n*(n+1)/2 for the covariance matrix and n (rank of cov matrix) std::vector<double> err; err.reserve(par.size()); for(unsigned int i = 0; i < par.size(); i++) { @@ -56,8 +56,8 @@ MnUserParameterState::MnUserParameterState(const std::vector<double>& par, const assert(fCovariance.Nrow() == VariableParameters()); } -MnUserParameterState::MnUserParameterState(const std::vector<double>& par, const MnUserCovariance& cov) : - fValid(true), fCovarianceValid(true), fGCCValid(false), fCovStatus(-1), fFVal(0.), fEDM(0.), fNFcn(0), +MnUserParameterState::MnUserParameterState(const std::vector<double>& par, const MnUserCovariance& cov) : + fValid(true), fCovarianceValid(true), fGCCValid(false), fCovStatus(-1), fFVal(0.), fEDM(0.), fNFcn(0), fParameters(MnUserParameters()), fCovariance(cov), fGlobalCC(MnGlobalCorrelationCoeff()), fIntParameters(par), fIntCovariance(cov) { //construct from user parameters + errors (before minimization) using std::vector (params) and MnUserCovariance class @@ -71,18 +71,18 @@ MnUserParameterState::MnUserParameterState(const std::vector<double>& par, const } -MnUserParameterState::MnUserParameterState(const MnUserParameters& par, const MnUserCovariance& cov) : - fValid(true), fCovarianceValid(true), fGCCValid(false), fCovStatus(-1), fFVal(0.), fEDM(0.), fNFcn(0), +MnUserParameterState::MnUserParameterState(const MnUserParameters& par, const MnUserCovariance& cov) : + fValid(true), fCovarianceValid(true), fGCCValid(false), fCovStatus(-1), fFVal(0.), fEDM(0.), fNFcn(0), fParameters(par), fCovariance(cov), fGlobalCC(MnGlobalCorrelationCoeff()), fIntParameters(std::vector<double>()), fIntCovariance(cov) { - //construct from user parameters + errors (befor minimization) using + //construct from user parameters + errors (befor minimization) using // MnUserParameters and MnUserCovariance objects fIntCovariance.Scale(0.5); for(std::vector<MinuitParameter>::const_iterator ipar = MinuitParameters().begin(); ipar != MinuitParameters().end(); ipar++) { if((*ipar).IsConst() || (*ipar).IsFixed()) continue; - if((*ipar).HasLimits()) + if((*ipar).HasLimits()) fIntParameters.push_back(Ext2int((*ipar).Number(), (*ipar).Value())); - else + else fIntParameters.push_back((*ipar).Value()); } assert(fCovariance.Nrow() == VariableParameters()); @@ -94,12 +94,14 @@ MnUserParameterState::MnUserParameterState(const MnUserParameters& par, const Mn // // -MnUserParameterState::MnUserParameterState(const MinimumState& st, double up, const MnUserTransformation& trafo) : - fValid(st.IsValid()), fCovarianceValid(false), fGCCValid(false), fCovStatus(-1), +MnUserParameterState::MnUserParameterState(const MinimumState& st, double up, const MnUserTransformation& trafo) : + fValid(st.IsValid()), fCovarianceValid(false), fGCCValid(false), fCovStatus(-1), fFVal(st.Fval()), fEDM(st.Edm()), fNFcn(st.NFcn()), fParameters(MnUserParameters()), fCovariance(MnUserCovariance()), fGlobalCC(MnGlobalCorrelationCoeff()), fIntParameters(std::vector<double>()), fIntCovariance(MnUserCovariance()) { // // construct from internal parameters (after minimization) // + //std::cout << "build a MnUSerParameterState after minimization.." << std::endl; + for(std::vector<MinuitParameter>::const_iterator ipar = trafo.Parameters().begin(); ipar != trafo.Parameters().end(); ipar++) { if((*ipar).IsConst()) { Add((*ipar).GetName(), (*ipar).Value()); @@ -130,21 +132,22 @@ MnUserParameterState::MnUserParameterState(const MinimumState& st, double up, co Add((*ipar).GetName(), st.Vec()(i), err); } } - + + // need to be set afterwards because becore the ::Add method set fCovarianceValid to false fCovarianceValid = st.Error().IsValid(); fCovStatus = -1; // when not available //if (st.Error().HesseFailed() || st.Error().InvertFailed() ) fCovStatus = -1; - // when available + // when available if (st.Error().IsAvailable() ) fCovStatus = 0; - + if(fCovarianceValid) { fCovariance = trafo.Int2extCovariance(st.Vec(), st.Error().InvHessian()); fIntCovariance = MnUserCovariance(std::vector<double>(st.Error().InvHessian().Data(), st.Error().InvHessian().Data()+st.Error().InvHessian().size()), st.Error().InvHessian().Nrow()); fCovariance.Scale(2.*up); fGlobalCC = MnGlobalCorrelationCoeff(st.Error().InvHessian()); fGCCValid = fGlobalCC.IsValid(); - + assert(fCovariance.Nrow() == VariableParameters()); fCovStatus = 1; // when is valid @@ -154,7 +157,7 @@ MnUserParameterState::MnUserParameterState(const MinimumState& st, double up, co } -MnUserCovariance MnUserParameterState::Hessian() const { +MnUserCovariance MnUserParameterState::Hessian() const { // invert covariance matrix and return Hessian // need to copy in a MnSymMatrix MnAlgebraicSymMatrix mat(fCovariance.Nrow() ); @@ -183,7 +186,7 @@ const std::vector<MinuitParameter>& MnUserParameterState::MinuitParameters() con //access to parameters (row-wise) return fParameters.Parameters(); } - + std::vector<double> MnUserParameterState::Params() const { //access to parameters in column-wise representation return fParameters.Params(); @@ -200,31 +203,31 @@ const MinuitParameter& MnUserParameterState::Parameter(unsigned int i) const { void MnUserParameterState::Add(const std::string & name, double val, double err) { //add free Parameter - if ( fParameters.Add(name, val, err) ) { + if ( fParameters.Add(name, val, err) ) { fIntParameters.push_back(val); fCovarianceValid = false; fGCCValid = false; fValid = true; } - else { + else { // redefine an existing parameter int i = Index(name); SetValue(i,val); - if (Parameter(i).IsConst() ) { - std::string msg = "Cannot modify status of constant parameter " + name; + if (Parameter(i).IsConst() ) { + std::string msg = "Cannot modify status of constant parameter " + name; MN_INFO_MSG2("MnUserParameterState::Add",msg.c_str()); return; } SetError(i,err); - // release if it was fixed - if (Parameter(i).IsFixed() ) Release(i); + // release if it was fixed + if (Parameter(i).IsFixed() ) Release(i); } - + } void MnUserParameterState::Add(const std::string & name, double val, double err, double low, double up) { //add limited Parameter - if ( fParameters.Add(name, val, err, low, up) ) { + if ( fParameters.Add(name, val, err, low, up) ) { fCovarianceValid = false; fIntParameters.push_back(Ext2int(Index(name), val)); fGCCValid = false; @@ -233,25 +236,25 @@ void MnUserParameterState::Add(const std::string & name, double val, double err, else { // Parameter already exist - just set values int i = Index(name); SetValue(i,val); - if (Parameter(i).IsConst() ) { - std::string msg = "Cannot modify status of constant parameter " + name; + if (Parameter(i).IsConst() ) { + std::string msg = "Cannot modify status of constant parameter " + name; MN_INFO_MSG2("MnUserParameterState::Add",msg.c_str()); return; } SetError(i,err); SetLimits(i,low,up); - // release if it was fixed - if (Parameter(i).IsFixed() ) Release(i); + // release if it was fixed + if (Parameter(i).IsFixed() ) Release(i); } - - + + } void MnUserParameterState::Add(const std::string & name, double val) { //add const Parameter - if ( fParameters.Add(name, val) ) + if ( fParameters.Add(name, val) ) fValid = true; - else + else SetValue(name,val); } @@ -265,7 +268,7 @@ void MnUserParameterState::Fix(unsigned int e) { fCovariance = MnCovarianceSqueeze()(fCovariance, i); fIntCovariance = MnCovarianceSqueeze()(fIntCovariance, i); } - fIntParameters.erase(fIntParameters.begin()+i, fIntParameters.begin()+i+1); + fIntParameters.erase(fIntParameters.begin()+i, fIntParameters.begin()+i+1); } fParameters.Fix(e); fGCCValid = false; @@ -280,7 +283,7 @@ void MnUserParameterState::Release(unsigned int e) { fGCCValid = false; unsigned int i = IntOfExt(e); if(Parameter(e).HasLimits()) - fIntParameters.insert(fIntParameters.begin()+i, Ext2int(e, Parameter(e).Value())); + fIntParameters.insert(fIntParameters.begin()+i, Ext2int(e, Parameter(e).Value())); else fIntParameters.insert(fIntParameters.begin()+i, Parameter(e).Value()); } @@ -311,9 +314,9 @@ void MnUserParameterState::SetLimits(unsigned int e, double low, double up) { unsigned int i = IntOfExt(e); if(low < fIntParameters[i] && fIntParameters[i] < up) fIntParameters[i] = Ext2int(e, fIntParameters[i]); - else if (low >= fIntParameters[i] ) + else if (low >= fIntParameters[i] ) fIntParameters[i] = Ext2int(e, low + 0.1 * Parameter(e).Error() ); - else + else fIntParameters[i] = Ext2int(e, up - 0.1 * Parameter(e).Error() ); } } @@ -352,7 +355,7 @@ void MnUserParameterState::RemoveLimits(unsigned int e) { fCovarianceValid = false; fGCCValid = false; if(!Parameter(e).IsFixed() && !Parameter(e).IsConst()) - fIntParameters[IntOfExt(e)] = Value(e); + fIntParameters[IntOfExt(e)] = Value(e); } double MnUserParameterState::Value(unsigned int i) const { @@ -397,7 +400,7 @@ const char* MnUserParameterState::Name(unsigned int i) const { return fParameters.Name(i); } const std::string & MnUserParameterState::GetName(unsigned int i) const { - //convert external number into name of Parameter (new interface returning a string) + //convert external number into name of Parameter (new interface returning a string) return fParameters.GetName(i); } @@ -408,14 +411,14 @@ double MnUserParameterState::Int2ext(unsigned int i, double val) const { return fParameters.Trafo().Int2ext(i, val); } double MnUserParameterState::Ext2int(unsigned int e, double val) const { - // external to internal value + // external to internal value return fParameters.Trafo().Ext2int(e, val); } unsigned int MnUserParameterState::IntOfExt(unsigned int ext) const { - // return internal index for external index ext + // return internal index for external index ext return fParameters.Trafo().IntOfExt(ext); } -unsigned int MnUserParameterState::ExtOfInt(unsigned int internal) const { +unsigned int MnUserParameterState::ExtOfInt(unsigned int internal) const { // return external index for internal index internal return fParameters.Trafo().ExtOfInt(internal); } diff --git a/ThirdParty/RootMinimizers/src/Minuit2/MnUserParameters.cxx b/ThirdParty/RootMinimizers/src/Minuit2/MnUserParameters.cxx index 2d03022f0030f886a13a824bcf045cfad26c35fd..1821682cf7938a760e5160c477b11b5649a1a961 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/MnUserParameters.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/MnUserParameters.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -24,7 +24,7 @@ const std::vector<MinuitParameter>& MnUserParameters::Parameters() const { } std::vector<double> MnUserParameters::Params() const { - // return std::vector of double with parameter values + // return std::vector of double with parameter values return fTransformation.Params(); } @@ -115,17 +115,17 @@ double MnUserParameters::Error(unsigned int n) const { // interface using parameter name void MnUserParameters::Fix(const std::string & name) { - // fix parameter + // fix parameter Fix(Index(name)); } void MnUserParameters::Release(const std::string & name) { - // release parameter + // release parameter Release(Index(name)); } void MnUserParameters::SetValue(const std::string & name, double val) { - // set value for parameter + // set value for parameter SetValue(Index(name), val); } diff --git a/ThirdParty/RootMinimizers/src/Minuit2/MnUserTransformation.cxx b/ThirdParty/RootMinimizers/src/Minuit2/MnUserTransformation.cxx index 6e2a304a1de4073281beebb5b1489749c3375fb6..b817624b1cff69f8c5434c419c3108f9589ecc1a 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/MnUserTransformation.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/MnUserTransformation.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -12,8 +12,8 @@ #include <algorithm> #include <stdio.h> -#include <string> -#include <sstream> +#include <string> +#include <sstream> namespace ROOT { @@ -27,10 +27,10 @@ public: MnParStr(const std::string & name) : fName(name) {} ~MnParStr() {} - + bool operator()(const MinuitParameter& par) const { // return (strcmp(par.Name(), fName) == 0); - return par.GetName() == fName; + return par.GetName() == fName; } private: @@ -39,11 +39,11 @@ private: MnUserTransformation::MnUserTransformation(const std::vector<double>& par, const std::vector<double>& err) : fPrecision(MnMachinePrecision()), fParameters(std::vector<MinuitParameter>()), fExtOfInt(std::vector<unsigned int>()), fDoubleLimTrafo(SinParameterTransformation()),fUpperLimTrafo(SqrtUpParameterTransformation()), fLowerLimTrafo(SqrtLowParameterTransformation()), fCache(std::vector<double>()) { - // constructor from a vector of parameter values and a vector of errors (step sizes) - // class has as data member the transformation objects (all of the types), - // the std::vector of MinuitParameter objects and the vector with the index conversions from + // constructor from a vector of parameter values and a vector of errors (step sizes) + // class has as data member the transformation objects (all of the types), + // the std::vector of MinuitParameter objects and the vector with the index conversions from // internal to external (fExtOfInt) - + fParameters.reserve(par.size()); fExtOfInt.reserve(par.size()); fCache.reserve(par.size()); @@ -60,9 +60,9 @@ MnUserTransformation::MnUserTransformation(const std::vector<double>& par, const //#ifdef MINUIT2_THREAD_SAFE // this if a thread-safe implementation needed if want to share transformation object between the threads std::vector<double> MnUserTransformation::operator()(const MnAlgebraicVector& pstates ) const { - // transform an internal Minuit vector of internal values in a std::vector of external values + // transform an internal Minuit vector of internal values in a std::vector of external values // fixed parameters will have their fixed values - unsigned int n = pstates.size(); + unsigned int n = pstates.size(); // need to initialize to the stored (initial values) parameter values for the fixed ones std::vector<double> pcache( fCache ); for(unsigned int i = 0; i < n; i++) { @@ -77,7 +77,7 @@ std::vector<double> MnUserTransformation::operator()(const MnAlgebraicVector& ps // #else // const std::vector<double> & MnUserTransformation::operator()(const MnAlgebraicVector& pstates) const { -// // transform an internal Minuit vector of internal values in a std::vector of external values +// // transform an internal Minuit vector of internal values in a std::vector of external values // // std::vector<double> Cache(pstates.size() ); // for(unsigned int i = 0; i < pstates.size(); i++) { // if(fParameters[fExtOfInt[i]].HasLimits()) { @@ -86,7 +86,7 @@ std::vector<double> MnUserTransformation::operator()(const MnAlgebraicVector& ps // fCache[fExtOfInt[i]] = pstates(i); // } // } - + // return fCache; // } // #endif @@ -101,7 +101,7 @@ double MnUserTransformation::Int2ext(unsigned int i, double val) const { else return fLowerLimTrafo.Int2ext(val, fParameters[fExtOfInt[i]].LowerLimit()); } - + return val; } @@ -110,7 +110,7 @@ double MnUserTransformation::Int2extError(unsigned int i, double val, double err //err = sigma Value == sqrt(cov(i,i)) double dx = err; - + if(fParameters[fExtOfInt[i]].HasLimits()) { double ui = Int2ext(i, val); double du1 = Int2ext(i, val+dx) - ui; @@ -127,15 +127,15 @@ double MnUserTransformation::Int2extError(unsigned int i, double val, double err dx = 0.5*(fabs(du1) + fabs(du2)); } } - + return dx; } MnUserCovariance MnUserTransformation::Int2extCovariance(const MnAlgebraicVector& vec, const MnAlgebraicSymMatrix& cov) const { // return the external covariance matrix from the internal error matrix and the internal parameter value // the vector of internal parameter is needed for the derivatives (Jacobian of the transformation) - // Vext(i,j) = Vint(i,j) * dPext(i)/dPint(i) * dPext(j)/dPint(j) - + // Vext(i,j) = Vint(i,j) * dPext(i)/dPint(i) * dPext(j)/dPint(j) + MnUserCovariance result(cov.Nrow()); for(unsigned int i = 0; i < vec.size(); i++) { double dxdi = 1.; @@ -154,22 +154,22 @@ MnUserCovariance MnUserTransformation::Int2extCovariance(const MnAlgebraicVector // double diag = Int2extError(i, vec(i), sqrt(cov(i,i))); // result(i,i) = diag*diag; } - + return result; } double MnUserTransformation::Ext2int(unsigned int i, double val) const { // return the internal value for parameter i with external value val - + if(fParameters[i].HasLimits()) { if(fParameters[i].HasUpperLimit() && fParameters[i].HasLowerLimit()) return fDoubleLimTrafo.Ext2int(val, fParameters[i].UpperLimit(), fParameters[i].LowerLimit(), Precision()); else if(fParameters[i].HasUpperLimit() && !fParameters[i].HasLowerLimit()) return fUpperLimTrafo.Ext2int(val, fParameters[i].UpperLimit(), Precision()); - else + else return fLowerLimTrafo.Ext2int(val, fParameters[i].LowerLimit(), Precision()); } - + return val; } @@ -179,32 +179,32 @@ double MnUserTransformation::DInt2Ext(unsigned int i, double val) const { double dd = 1.; if(fParameters[fExtOfInt[i]].HasLimits()) { - if(fParameters[fExtOfInt[i]].HasUpperLimit() && fParameters[fExtOfInt[i]].HasLowerLimit()) + if(fParameters[fExtOfInt[i]].HasUpperLimit() && fParameters[fExtOfInt[i]].HasLowerLimit()) // dd = 0.5*fabs((fParameters[fExtOfInt[i]].Upper() - fParameters[fExtOfInt[i]].Lower())*cos(vec(i))); dd = fDoubleLimTrafo.DInt2Ext(val, fParameters[fExtOfInt[i]].UpperLimit(), fParameters[fExtOfInt[i]].LowerLimit()); else if(fParameters[fExtOfInt[i]].HasUpperLimit() && !fParameters[fExtOfInt[i]].HasLowerLimit()) dd = fUpperLimTrafo.DInt2Ext(val, fParameters[fExtOfInt[i]].UpperLimit()); - else + else dd = fLowerLimTrafo.DInt2Ext(val, fParameters[fExtOfInt[i]].LowerLimit()); } - + return dd; } /* double MnUserTransformation::dExt2Int(unsigned int, double) const { double dd = 1.; - + if(fParameters[fExtOfInt[i]].HasLimits()) { - if(fParameters[fExtOfInt[i]].HasUpperLimit() && fParameters[fExtOfInt[i]].HasLowerLimit()) + if(fParameters[fExtOfInt[i]].HasUpperLimit() && fParameters[fExtOfInt[i]].HasLowerLimit()) // dd = 0.5*fabs((fParameters[fExtOfInt[i]].Upper() - fParameters[fExtOfInt[i]].Lower())*cos(vec(i))); dd = fDoubleLimTrafo.dExt2Int(val, fParameters[fExtOfInt[i]].UpperLimit(), fParameters[fExtOfInt[i]].LowerLimit()); else if(fParameters[fExtOfInt[i]].HasUpperLimit() && !fParameters[fExtOfInt[i]].HasLowerLimit()) dd = fUpperLimTrafo.dExt2Int(val, fParameters[fExtOfInt[i]].UpperLimit()); - else + else dd = fLowerLimTrafo.dExtInt(val, fParameters[fExtOfInt[i]].LowerLimit()); } - + return dd; } */ @@ -216,17 +216,17 @@ unsigned int MnUserTransformation::IntOfExt(unsigned int ext) const { assert(!fParameters[ext].IsConst()); std::vector<unsigned int>::const_iterator iind = std::find(fExtOfInt.begin(), fExtOfInt.end(), ext); assert(iind != fExtOfInt.end()); - - return (iind - fExtOfInt.begin()); + + return (iind - fExtOfInt.begin()); } std::vector<double> MnUserTransformation::Params() const { - // return std::vector of double with parameter values - unsigned int n = fParameters.size(); + // return std::vector of double with parameter values + unsigned int n = fParameters.size(); std::vector<double> result(n); - for(unsigned int i = 0; i < n; ++i) - result[i] = fParameters[i].Value(); - + for(unsigned int i = 0; i < n; ++i) + result[i] = fParameters[i].Value(); + return result; } @@ -236,26 +236,26 @@ std::vector<double> MnUserTransformation::Errors() const { for(std::vector<MinuitParameter>::const_iterator ipar = Parameters().begin(); ipar != Parameters().end(); ipar++) result.push_back((*ipar).Error()); - + return result; } const MinuitParameter& MnUserTransformation::Parameter(unsigned int n) const { // return the MinuitParameter object for index n (external) - assert(n < fParameters.size()); + assert(n < fParameters.size()); return fParameters[n]; } -// bool MnUserTransformation::Remove(const std::string & name) { -// // remove parameter with name +// bool MnUserTransformation::Remove(const std::string & name) { +// // remove parameter with name // // useful if want to re-define a parameter // // return false if parameter does not exist // std::vector<MinuitParameter>::iterator itr = std::find_if(fParameters.begin(), fParameters.end(), MnParStr(name) ); -// if (itr == fParameters.end() ) return false; -// int n = itr - fParameters.begin(); -// if (n < 0 || n >= fParameters.size() ) return false; +// if (itr == fParameters.end() ) return false; +// int n = itr - fParameters.begin(); +// if (n < 0 || n >= fParameters.size() ) return false; // fParameters.erase(itr); -// fCache.erase( fExtOfInt.begin() + n); +// fCache.erase( fExtOfInt.begin() + n); // std::vector<unsigned int>::iterator iind = std::find(fExtOfInt.begin(), fExtOfInt.end(), n); // if (iind != fExtOfInt.end()) fExtOfInt.erase(iind); // } @@ -263,8 +263,8 @@ const MinuitParameter& MnUserTransformation::Parameter(unsigned int n) const { bool MnUserTransformation::Add(const std::string & name, double val, double err) { // add a new unlimited parameter giving name, value and err (step size) // return false if parameter already exists - if (std::find_if(fParameters.begin(), fParameters.end(), MnParStr(name)) != fParameters.end() ) - return false; + if (std::find_if(fParameters.begin(), fParameters.end(), MnParStr(name)) != fParameters.end() ) + return false; fExtOfInt.push_back(fParameters.size()); fCache.push_back(val); fParameters.push_back(MinuitParameter(fParameters.size(), name, val, err)); @@ -274,8 +274,8 @@ bool MnUserTransformation::Add(const std::string & name, double val, double err) bool MnUserTransformation::Add(const std::string & name, double val, double err, double low, double up) { // add a new limited parameter giving name, value, err (step size) and lower/upper limits // return false if parameter already exists - if (std::find_if(fParameters.begin(), fParameters.end(), MnParStr(name)) != fParameters.end() ) - return false; + if (std::find_if(fParameters.begin(), fParameters.end(), MnParStr(name)) != fParameters.end() ) + return false; fExtOfInt.push_back(fParameters.size()); fCache.push_back(val); fParameters.push_back(MinuitParameter(fParameters.size(), name, val, err, low, up)); @@ -285,8 +285,8 @@ bool MnUserTransformation::Add(const std::string & name, double val, double err, bool MnUserTransformation::Add(const std::string & name, double val) { // add a new constant parameter giving name and value // return false if parameter already exists - if (std::find_if(fParameters.begin(), fParameters.end(), MnParStr(name)) != fParameters.end() ) - return false; + if (std::find_if(fParameters.begin(), fParameters.end(), MnParStr(name)) != fParameters.end() ) + return false; fCache.push_back(val); // costant parameter - do not add in list of internals (fExtOfInt) fParameters.push_back(MinuitParameter(fParameters.size(), name, val)); @@ -295,7 +295,7 @@ bool MnUserTransformation::Add(const std::string & name, double val) { void MnUserTransformation::Fix(unsigned int n) { // fix parameter n (external index) - assert(n < fParameters.size()); + assert(n < fParameters.size()); std::vector<unsigned int>::iterator iind = std::find(fExtOfInt.begin(), fExtOfInt.end(), n); if (iind != fExtOfInt.end()) fExtOfInt.erase(iind, iind+1); @@ -304,9 +304,9 @@ void MnUserTransformation::Fix(unsigned int n) { void MnUserTransformation::Release(unsigned int n) { // release parameter n (external index) - assert(n < fParameters.size()); + assert(n < fParameters.size()); std::vector<unsigned int>::const_iterator iind = std::find(fExtOfInt.begin(), fExtOfInt.end(), n); - if (iind == fExtOfInt.end() ) { + if (iind == fExtOfInt.end() ) { fExtOfInt.push_back(n); std::sort(fExtOfInt.begin(), fExtOfInt.end()); } @@ -315,14 +315,14 @@ void MnUserTransformation::Release(unsigned int n) { void MnUserTransformation::SetValue(unsigned int n, double val) { // set value for parameter n (external index) - assert(n < fParameters.size()); + assert(n < fParameters.size()); fParameters[n].SetValue(val); fCache[n] = val; } void MnUserTransformation::SetError(unsigned int n, double err) { // set error for parameter n (external index) - assert(n < fParameters.size()); + assert(n < fParameters.size()); fParameters[n].SetError(err); } @@ -335,55 +335,55 @@ void MnUserTransformation::SetLimits(unsigned int n, double low, double up) { void MnUserTransformation::SetUpperLimit(unsigned int n, double up) { // set upper limit for parameter n (external index) - assert(n < fParameters.size()); + assert(n < fParameters.size()); fParameters[n].SetUpperLimit(up); } void MnUserTransformation::SetLowerLimit(unsigned int n, double lo) { // set lower limit for parameter n (external index) - assert(n < fParameters.size()); + assert(n < fParameters.size()); fParameters[n].SetLowerLimit(lo); } void MnUserTransformation::RemoveLimits(unsigned int n) { // remove limits for parameter n (external index) - assert(n < fParameters.size()); + assert(n < fParameters.size()); fParameters[n].RemoveLimits(); } void MnUserTransformation::SetName(unsigned int n, const std::string & name) { // set name for parameter n (external index) - assert(n < fParameters.size()); + assert(n < fParameters.size()); fParameters[n].SetName(name); } double MnUserTransformation::Value(unsigned int n) const { // get value for parameter n (external index) - assert(n < fParameters.size()); + assert(n < fParameters.size()); return fParameters[n].Value(); } double MnUserTransformation::Error(unsigned int n) const { // get error for parameter n (external index) - assert(n < fParameters.size()); + assert(n < fParameters.size()); return fParameters[n].Error(); } // interface by parameter name void MnUserTransformation::Fix(const std::string & name) { - // fix parameter + // fix parameter Fix(Index(name)); } void MnUserTransformation::Release(const std::string & name) { - // release parameter + // release parameter Release(Index(name)); } void MnUserTransformation::SetValue(const std::string & name, double val) { - // set value for parameter + // set value for parameter SetValue(Index(name), val); } @@ -424,7 +424,7 @@ double MnUserTransformation::Error(const std::string & name) const { unsigned int MnUserTransformation::Index(const std::string & name) const { // get index (external) corresponding to name - std::vector<MinuitParameter>::const_iterator ipar = + std::vector<MinuitParameter>::const_iterator ipar = std::find_if(fParameters.begin(), fParameters.end(), MnParStr(name)); assert(ipar != fParameters.end()); // return (ipar - fParameters.begin()); @@ -433,16 +433,16 @@ unsigned int MnUserTransformation::Index(const std::string & name) const { int MnUserTransformation::FindIndex(const std::string & name) const { // find index (external) corresponding to name - return -1 if not found - std::vector<MinuitParameter>::const_iterator ipar = + std::vector<MinuitParameter>::const_iterator ipar = std::find_if(fParameters.begin(), fParameters.end(), MnParStr(name)); - if (ipar == fParameters.end() ) return -1; + if (ipar == fParameters.end() ) return -1; return (*ipar).Number(); } const std::string & MnUserTransformation::GetName(unsigned int n) const { // get name corresponding to index (external) - assert(n < fParameters.size()); + assert(n < fParameters.size()); return fParameters[n].GetName(); } diff --git a/ThirdParty/RootMinimizers/src/Minuit2/ModularFunctionMinimizer.cxx b/ThirdParty/RootMinimizers/src/Minuit2/ModularFunctionMinimizer.cxx index 26809b85cc9f84a25615220e3b5a5d7aa5138a95..73716a8985c684e28fb7f1cc94c4f2c1a65a26fc 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/ModularFunctionMinimizer.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/ModularFunctionMinimizer.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -27,7 +27,7 @@ #include "Minuit2/MnParabolaPoint.h" #if defined(DEBUG) || defined(WARNINGMSG) -#include "Minuit2/MnPrint.h" +#include "Minuit2/MnPrint.h" #endif @@ -46,7 +46,7 @@ FunctionMinimum ModularFunctionMinimizer::Minimize(const FCNBase& fcn, const std } FunctionMinimum ModularFunctionMinimizer::Minimize(const FCNGradientBase& fcn, const std::vector<double>& par, const std::vector<double>& err, unsigned int stra, unsigned int maxfcn, double toler) const { - // minimize from FCNGradientBase (use analytical gradient provided in FCN) + // minimize from FCNGradientBase (use analytical gradient provided in FCN) // and std::vector of double's for parameter values and errors (step sizes) MnUserParameterState st(par, err); MnStrategy strategy(stra); @@ -55,18 +55,18 @@ FunctionMinimum ModularFunctionMinimizer::Minimize(const FCNGradientBase& fcn, c // move nrow before cov to avoid ambiguities when using default parameters FunctionMinimum ModularFunctionMinimizer::Minimize(const FCNBase& fcn, const std::vector<double>& par, unsigned int nrow, const std::vector<double>& cov, unsigned int stra, unsigned int maxfcn, double toler) const { - // minimize from FCNBase using std::vector for parameter error and - // an std::vector of size n*(n+1)/2 for the covariance matrix and n (rank of cov matrix) - + // minimize from FCNBase using std::vector for parameter error and + // an std::vector of size n*(n+1)/2 for the covariance matrix and n (rank of cov matrix) + MnUserParameterState st(par, cov, nrow); MnStrategy strategy(stra); return Minimize(fcn, st, strategy, maxfcn, toler); } FunctionMinimum ModularFunctionMinimizer::Minimize(const FCNGradientBase& fcn, const std::vector<double>& par, unsigned int nrow, const std::vector<double>& cov, unsigned int stra, unsigned int maxfcn, double toler) const { - // minimize from FCNGradientBase (use analytical gradient provided in FCN) - // using std::vector for parameter error and - // an std::vector of size n*(n+1)/2 for the covariance matrix and n (rank of cov matrix) + // minimize from FCNGradientBase (use analytical gradient provided in FCN) + // using std::vector for parameter error and + // an std::vector of size n*(n+1)/2 for the covariance matrix and n (rank of cov matrix) MnUserParameterState st(par, cov, nrow); MnStrategy strategy(stra); @@ -75,27 +75,27 @@ FunctionMinimum ModularFunctionMinimizer::Minimize(const FCNGradientBase& fcn, c FunctionMinimum ModularFunctionMinimizer::Minimize(const FCNBase& fcn, const MnUserParameters& upar, const MnStrategy& strategy, unsigned int maxfcn, double toler) const { // minimize from FCNBase and MnUserParameters object - + MnUserParameterState st(upar); return Minimize(fcn, st, strategy, maxfcn, toler); } FunctionMinimum ModularFunctionMinimizer::Minimize(const FCNGradientBase& fcn, const MnUserParameters& upar, const MnStrategy& strategy, unsigned int maxfcn, double toler) const { // minimize from FCNGradientBase (use analytical gradient provided in FCN) and MnUserParameters object - + MnUserParameterState st(upar); return Minimize(fcn, st, strategy, maxfcn, toler); } FunctionMinimum ModularFunctionMinimizer::Minimize(const FCNBase& fcn, const MnUserParameters& upar, const MnUserCovariance& cov, const MnStrategy& strategy, unsigned int maxfcn, double toler) const { // minimize from FCNBase and MnUserParameters and MnUserCovariance objects - + MnUserParameterState st(upar, cov); return Minimize(fcn, st, strategy, maxfcn, toler); } FunctionMinimum ModularFunctionMinimizer::Minimize(const FCNGradientBase& fcn, const MnUserParameters& upar, const MnUserCovariance& cov, const MnStrategy& strategy, unsigned int maxfcn, double toler) const { - // minimize from FCNGradientBase (use analytical gradient provided in FCN) and + // minimize from FCNGradientBase (use analytical gradient provided in FCN) and // MnUserParameters MnUserCovariance objects MnUserParameterState st(upar, cov); @@ -105,37 +105,37 @@ FunctionMinimum ModularFunctionMinimizer::Minimize(const FCNGradientBase& fcn, c FunctionMinimum ModularFunctionMinimizer::Minimize(const FCNBase& fcn, const MnUserParameterState& st, const MnStrategy& strategy, unsigned int maxfcn, double toler) const { - // minimize from a FCNBase and a MnUserparameterState - interface used by all the previous ones + // minimize from a FCNBase and a MnUserparameterState - interface used by all the previous ones // based on FCNBase. Create in this case a NumericalGradient calculator // Create the minuit FCN wrapper (MnUserFcn) containing the trasformation (int<->ext) - + // neeed MnUsserFcn for difference int-ext parameters MnUserFcn mfcn(fcn, st.Trafo() ); Numerical2PGradientCalculator gc(mfcn, st.Trafo(), strategy); - + unsigned int npar = st.VariableParameters(); if(maxfcn == 0) maxfcn = 200 + 100*npar + 5*npar*npar; MinimumSeed mnseeds = SeedGenerator()(mfcn, gc, st, strategy); - + return Minimize(mfcn, gc, mnseeds, strategy, maxfcn, toler); } -// use Gradient here +// use Gradient here FunctionMinimum ModularFunctionMinimizer::Minimize(const FCNGradientBase& fcn, const MnUserParameterState& st, const MnStrategy& strategy, unsigned int maxfcn, double toler) const { - // minimize from a FCNGradientBase and a MnUserparameterState - interface used by all the previous ones - // based on FCNGradientBase. + // minimize from a FCNGradientBase and a MnUserparameterState - interface used by all the previous ones + // based on FCNGradientBase. // Create in this acase an AnalyticalGradient calculator // Create the minuit FCN wrapper (MnUserFcn) containing the trasformation (int<->ext) - + MnUserFcn mfcn(fcn, st.Trafo()); AnalyticalGradientCalculator gc(fcn, st.Trafo()); - + unsigned int npar = st.VariableParameters(); if(maxfcn == 0) maxfcn = 200 + 100*npar + 5*npar*npar; - + MinimumSeed mnseeds = SeedGenerator()(mfcn, gc, st, strategy); - + return Minimize(mfcn, gc, mnseeds, strategy, maxfcn, toler); } @@ -143,15 +143,15 @@ FunctionMinimum ModularFunctionMinimizer::Minimize(const FCNGradientBase& fcn, c FunctionMinimum ModularFunctionMinimizer::Minimize(const MnFcn& mfcn, const GradientCalculator& gc, const MinimumSeed& seed, const MnStrategy& strategy, unsigned int maxfcn, double toler) const { // Interface used by all the others for the minimization using the base MinimumBuilder class // According to the contained type of MinimumBuilder the right type will be used - + const MinimumBuilder & mb = Builder(); //std::cout << typeid(&mb).Name() << std::endl; double effective_toler = toler * mfcn.Up(); // scale tolerance with Up() // avoid tolerance too smalls (than limits) - double eps = MnMachinePrecision().Eps2(); - if (effective_toler < eps) effective_toler = eps; + double eps = MnMachinePrecision().Eps2(); + if (effective_toler < eps) effective_toler = eps; - // check if maxfcn is already exhausted + // check if maxfcn is already exhausted // case already reached call limit if(mfcn.NumOfCalls() >= maxfcn) { #ifdef WARNINGMSG @@ -160,7 +160,7 @@ FunctionMinimum ModularFunctionMinimizer::Minimize(const MnFcn& mfcn, const Grad return FunctionMinimum(seed, std::vector<MinimumState>(1, seed.State()), mfcn.Up(), FunctionMinimum::MnReachedCallLimit()); } - + return mb.Minimum(mfcn, gc, seed, strategy, maxfcn, effective_toler); diff --git a/ThirdParty/RootMinimizers/src/Minuit2/NegativeG2LineSearch.cxx b/ThirdParty/RootMinimizers/src/Minuit2/NegativeG2LineSearch.cxx index 8abb0b69fa263568758e6e75bd9ac10b30ac4cc9..dc36155bad66d1320ad13b738d920371859be5f7 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/NegativeG2LineSearch.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/NegativeG2LineSearch.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -30,16 +30,16 @@ namespace ROOT { MinimumState NegativeG2LineSearch::operator()(const MnFcn& fcn, const MinimumState& st, const GradientCalculator& gc, const MnMachinePrecision& prec) const { - -// when the second derivatives are negative perform a line search along Parameter which gives -// negative second derivative and magnitude equal to the Gradient step size. -// Recalculate the gradients for all the Parameter after the correction and + +// when the second derivatives are negative perform a line search along Parameter which gives +// negative second derivative and magnitude equal to the Gradient step size. +// Recalculate the gradients for all the Parameter after the correction and // continue iteration in case the second derivatives are still negative // bool negG2 = HasNegativeG2(st.Gradient(), prec); if(!negG2) return st; - + unsigned int n = st.Parameters().Vec().size(); FunctionGradient dgrad = st.Gradient(); MinimumParameters pa = st.Parameters(); @@ -49,23 +49,23 @@ MinimumState NegativeG2LineSearch::operator()(const MnFcn& fcn, const MinimumSta iterate = false; for(unsigned int i = 0; i < n; i++) { -#ifdef DEBUG - std::cout << "negative G2 - iter " << iter << " param " << i << " " << pa.Vec()(i) << " grad2 " << dgrad.G2()(i) << " grad " << dgrad.Vec()(i) - << " grad step " << dgrad.Gstep()(i) << " step size " << pa.Dirin()(i) << std::endl; +#ifdef DEBUG + std::cout << "negative G2 - iter " << iter << " param " << i << " " << pa.Vec()(i) << " grad2 " << dgrad.G2()(i) << " grad " << dgrad.Vec()(i) + << " grad step " << dgrad.Gstep()(i) << " step size " << pa.Dirin()(i) << std::endl; #endif - if(dgrad.G2()(i) <= 0) { + if(dgrad.G2()(i) <= 0) { - // check also the gradient (if it is zero ) I can skip the param) - - if ( std::fabs(dgrad.Vec()(i) ) < prec.Eps() && std::fabs(dgrad.G2()(i) ) < prec.Eps() ) continue; + // check also the gradient (if it is zero ) I can skip the param) + + if ( std::fabs(dgrad.Vec()(i) ) < prec.Eps() && std::fabs(dgrad.G2()(i) ) < prec.Eps() ) continue; // if(dgrad.G2()(i) < prec.Eps()) { // do line search if second derivative negative MnAlgebraicVector step(n); MnLineSearch lsearch; - if ( dgrad.Vec()(i) < 0) + if ( dgrad.Vec()(i) < 0) step(i) = dgrad.Gstep()(i); //*dgrad.Vec()(i); - else + else step(i) = - dgrad.Gstep()(i); // *dgrad.Vec()(i); double gdel = step(i)*dgrad.Vec()(i); @@ -75,7 +75,7 @@ MinimumState NegativeG2LineSearch::operator()(const MnFcn& fcn, const MinimumSta bool debugLS = false; #ifdef DEBUG - std::cout << "step(i) " << step(i) << " gdel " << gdel << std::endl; + std::cout << "step(i) " << step(i) << " gdel " << gdel << std::endl; // std::cout << " g2del " << g2del << std::endl; debugLS = true; #endif @@ -88,9 +88,9 @@ MinimumState NegativeG2LineSearch::operator()(const MnFcn& fcn, const MinimumSta #endif step *= pp.X(); - pa = MinimumParameters(pa.Vec() + step, pp.Y()); + pa = MinimumParameters(pa.Vec() + step, pp.Y()); - dgrad = gc(pa, dgrad); + dgrad = gc(pa, dgrad); #ifdef DEBUG std::cout << "Line search - iter" << iter << " param " << i << " " << pa.Vec()(i) << " step " << step(i) << " new grad2 " << dgrad.G2()(i) << " new grad " << dgrad.Vec()(i) << " grad step " << dgrad.Gstep()(i) << std::endl; @@ -98,30 +98,30 @@ MinimumState NegativeG2LineSearch::operator()(const MnFcn& fcn, const MinimumSta iterate = true; break; - } + } } } while(iter++ < 2*n && iterate); - + MnAlgebraicSymMatrix mat(n); for(unsigned int i = 0; i < n; i++) mat(i,i) = (fabs(dgrad.G2()(i)) > prec.Eps2() ? 1./dgrad.G2()(i) : 1.); - + MinimumError err(mat, 1.); double edm = VariableMetricEDMEstimator().Estimate(dgrad, err); - + return MinimumState(pa, err, dgrad, edm, fcn.NumOfCalls()); } - + bool NegativeG2LineSearch::HasNegativeG2(const FunctionGradient& grad, const MnMachinePrecision& /*prec */ ) const { // check if function gradient has any component which is neegative - - for(unsigned int i = 0; i < grad.Vec().size(); i++) - if(grad.G2()(i) <= 0 ) { + for(unsigned int i = 0; i < grad.Vec().size(); i++) + + if(grad.G2()(i) <= 0 ) { return true; } - + return false; } diff --git a/ThirdParty/RootMinimizers/src/Minuit2/Numerical2PGradientCalculator.cxx b/ThirdParty/RootMinimizers/src/Minuit2/Numerical2PGradientCalculator.cxx index 22dd9dd37e0165b394be868aa14d24ca9e178563..5de0ed19d3dfd90099d857dfcb83807852c9dacc 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/Numerical2PGradientCalculator.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/Numerical2PGradientCalculator.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -19,7 +19,7 @@ //#define DEBUG #if defined(DEBUG) || defined(WARNINGMSG) -#include "Minuit2/MnPrint.h" +#include "Minuit2/MnPrint.h" #ifdef _OPENMP #include <omp.h> #include <iomanip> @@ -43,28 +43,28 @@ FunctionGradient Numerical2PGradientCalculator::operator()(const MinimumParamete InitialGradientCalculator gc(fFcn, fTransformation, fStrategy); FunctionGradient gra = gc(par); - - return (*this)(par, gra); + + return (*this)(par, gra); } // comment it, because it was added FunctionGradient Numerical2PGradientCalculator::operator()(const std::vector<double>& params) const { // calculate gradient from an std;:vector of paramteters - + int npar = params.size(); - + MnAlgebraicVector par(npar); for (int i = 0; i < npar; ++i) { par(i) = params[i]; } - + double fval = Fcn()(par); - + MinimumParameters minpars = MinimumParameters(par, fval); - + return (*this)(minpars); - + } @@ -72,27 +72,27 @@ FunctionGradient Numerical2PGradientCalculator::operator()(const std::vector<dou FunctionGradient Numerical2PGradientCalculator::operator()(const MinimumParameters& par, const FunctionGradient& Gradient) const { // calculate numerical gradient from MinimumParameters object // the algorithm takes correctly care when the gradient is approximatly zero - + // std::cout<<"########### Numerical2PDerivative"<<std::endl; // std::cout<<"initial grd: "<<Gradient.Grad()<<std::endl; // std::cout<<"position: "<<par.Vec()<<std::endl; - + assert(par.IsValid()); - - + + double fcnmin = par.Fval(); // std::cout<<"fval: "<<fcnmin<<std::endl; - - double eps2 = Precision().Eps2(); + + double eps2 = Precision().Eps2(); double eps = Precision().Eps(); - + double dfmin = 8.*eps2*(fabs(fcnmin)+Fcn().Up()); double vrysml = 8.*eps*eps; // double vrysml = std::max(1.e-4, eps2); // std::cout<<"dfmin= "<<dfmin<<std::endl; // std::cout<<"vrysml= "<<vrysml<<std::endl; // std::cout << " ncycle " << Ncycle() << std::endl; - + unsigned int n = (par.Vec()).size(); unsigned int ncycle = Ncycle(); // MnAlgebraicVector vgrd(n), vgrd2(n), vgstp(n); @@ -106,6 +106,9 @@ FunctionGradient Numerical2PGradientCalculator::operator()(const MinimumParamete #ifdef DEBUG std::cout << "Calculating Gradient at x = " << par.Vec() << std::endl; + int pr = std::cout.precision(13); + std::cout << "fcn(x) = " << fcnmin << std::endl; + std::cout.precision(pr); #endif #ifndef _OPENMP @@ -122,7 +125,7 @@ FunctionGradient Numerical2PGradientCalculator::operator()(const MinimumParamete // parallelize this loop using OpenMP //#define N_PARALLEL_PAR 5 #pragma omp parallel -#pragma omp for +#pragma omp for //#pragma omp for schedule (static, N_PARALLEL_PAR) for(int i = 0; i < int(n); i++) { @@ -168,17 +171,24 @@ FunctionGradient Numerical2PGradientCalculator::operator()(const MinimumParamete // pstep(i) = step; // double fs1 = Fcn()(pstate + pstep); // double fs2 = Fcn()(pstate - pstep); - + x(i) = xtf + step; double fs1 = Fcn()(x); x(i) = xtf - step; double fs2 = Fcn()(x); x(i) = xtf; - + double grdb4 = grd(i); grd(i) = 0.5*(fs1 - fs2)/step; g2(i) = (fs1 + fs2 - 2.*fcnmin)/step/step; - + +#ifdef DEBUG + pr = std::cout.precision(13); + std::cout << "cycle " << j << " x " << x(i) << " step " << step << " f1 " << fs1 << " f2 " << fs2 + << " grd " << grd(i) << " g2 " << g2(i) << std::endl; + std::cout.precision(pr); +#endif + if(fabs(grdb4-grd(i))/(fabs(grd(i))+dfmin/step) < GradTolerance()) { // std::cout<<"j= "<<j<<std::endl; // std::cout<<"step= "<<step<<std::endl; @@ -187,7 +197,7 @@ FunctionGradient Numerical2PGradientCalculator::operator()(const MinimumParamete break; } } - + #ifdef DEBUG_MP #pragma omp critical @@ -199,14 +209,15 @@ FunctionGradient Numerical2PGradientCalculator::operator()(const MinimumParamete // vgrd(i) = grd; // vgrd2(i) = g2; // vgstp(i) = gstep; - } + #ifdef DEBUG - std::cout << "Gradient = " << grd << std::endl; + pr = std::cout.precision(13); + int iext = Trafo().ExtOfInt(i); + std::cout << "Parameter " << Trafo().Name(iext) << " Gradient = " << grd(i) << " g2 = " << g2(i) << " step " << gstep(i) << std::endl; + std::cout.precision(pr); #endif - - // std::cout<<"final grd: "<<grd<<std::endl; - // std::cout<<"########### return from Numerical2PDerivative"<<std::endl; + } #ifndef _OPENMP mpiproc.SyncVector(grd); diff --git a/ThirdParty/RootMinimizers/src/Minuit2/ParametricFunction.cxx b/ThirdParty/RootMinimizers/src/Minuit2/ParametricFunction.cxx index 8c76695fb0032618fd905ee2740393e51eae747c..52d987abd5cb2b5b95e7e1a209776a4b9d02362b 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/ParametricFunction.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/ParametricFunction.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -23,27 +23,27 @@ namespace ROOT { -std::vector<double> ParametricFunction::GetGradient(const std::vector<double>& x) const { - // calculate the numerical gradient (using Numerical2PGradientCalculator) +std::vector<double> ParametricFunction::GetGradient(const std::vector<double>& x) const { + // calculate the numerical gradient (using Numerical2PGradientCalculator) //LM: this I believe is not very efficient MnFcn mfcn(*this); - + MnStrategy strategy(1); - + // ????????? how does it know the transformation???????? std::vector<double> err(x.size()); err.assign(x.size(), 0.1); - // need to use parameters + // need to use parameters MnUserParameterState st(x, err); - + Numerical2PGradientCalculator gc(mfcn, st.Trafo(), strategy); - FunctionGradient g = gc(x); + FunctionGradient g = gc(x); const MnAlgebraicVector & grad = g.Vec(); assert( grad.size() == x.size() ); - MnVectorTransform vt; - // std::cout << "Param Function Gradient " << grad << std::endl; - return vt( grad ); + MnVectorTransform vt; + // std::cout << "Param Function Gradient " << grad << std::endl; + return vt( grad ); } } // namespace Minuit2 diff --git a/ThirdParty/RootMinimizers/src/Minuit2/ScanBuilder.cxx b/ThirdParty/RootMinimizers/src/Minuit2/ScanBuilder.cxx index c000fb57bec8b7524cfea290bbf05d869dc8b211..797274dd626749376c5ad7dfd0383d25ad43cb94 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/ScanBuilder.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/ScanBuilder.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -20,7 +20,7 @@ namespace ROOT { FunctionMinimum ScanBuilder::Minimum(const MnFcn& mfcn, const GradientCalculator&, const MinimumSeed& seed, const MnStrategy&, unsigned int, double) const { - // find the function minimum performing a parameter scan (using MnParameterScan class) + // find the function minimum performing a parameter scan (using MnParameterScan class) // function gradient is not used MnAlgebraicVector x = seed.Parameters().Vec(); MnUserParameterState upst(seed.State(), mfcn.Up(), seed.Trafo()); diff --git a/ThirdParty/RootMinimizers/src/Minuit2/SimplexBuilder.cxx b/ThirdParty/RootMinimizers/src/Minuit2/SimplexBuilder.cxx index 9f5132dbb98fe6b79b0a0c353479cdf2e3f54d05..16c8de3951e1ede86158ed7802259c7ef4ad08ef 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/SimplexBuilder.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/SimplexBuilder.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -15,7 +15,7 @@ #include "Minuit2/MinimumState.h" #if defined(DEBUG) || defined(WARNINGMSG) -#include "Minuit2/MnPrint.h" +#include "Minuit2/MnPrint.h" #endif @@ -28,17 +28,17 @@ namespace ROOT { FunctionMinimum SimplexBuilder::Minimum(const MnFcn& mfcn, const GradientCalculator&, const MinimumSeed& seed, const MnStrategy&, unsigned int maxfcn, double minedm) const { // find the minimum using the Simplex method of Nelder and Mead (does not use function gradient) - // method to find initial simplex is slightly different than in the orginal Fortran + // method to find initial simplex is slightly different than in the orginal Fortran // Minuit since has not been proofed that one to be better - + #ifdef DEBUG std::cout << "Running Simplex with maxfcn = " << maxfcn << " minedm = " << minedm << std::endl; -#endif - +#endif + const MnMachinePrecision& prec = seed.Precision(); MnAlgebraicVector x = seed.Parameters().Vec(); MnAlgebraicVector step = 10.*seed.Gradient().Gstep(); - + unsigned int n = x.size(); double wg = 1./double(n); double alpha = 1., beta = 0.5, gamma = 2., rhomin = 4., rhomax = 8.; @@ -46,14 +46,14 @@ FunctionMinimum SimplexBuilder::Minimum(const MnFcn& mfcn, const GradientCalcula //double rho2 = rho1 + alpha*gamma; //change proposed by david sachs (fnal) double rho2 = 1. + alpha*gamma; - - + + std::vector<std::pair<double, MnAlgebraicVector> > simpl; simpl.reserve(n+1); simpl.push_back(std::pair<double, MnAlgebraicVector>(seed.Fval(), x)); - + unsigned int jl = 0, jh = 0; double amin = seed.Fval(), aming = seed.Fval(); - + for(unsigned int i = 0; i < n; i++) { double dmin = 8.*prec.Eps2()*(fabs(x(i)) + prec.Eps2()); if(step(i) < dmin) step(i) = dmin; @@ -71,13 +71,13 @@ FunctionMinimum SimplexBuilder::Minimum(const MnFcn& mfcn, const GradientCalcula x(i) -= step(i); } SimplexParameters simplex(simpl, jh, jl); - + #ifdef DEBUG std::cout << "simplex initial parameters - min " << jl << " " << amin << " max " << jh << " " << aming << std::endl; - for (unsigned int i = 0; i < simplex.Simplex().size(); ++i) - std::cout << " i = " << i << " x = " << simplex(i).second << " fval(x) = " << simplex(i).first << std::endl; + for (unsigned int i = 0; i < simplex.Simplex().size(); ++i) + std::cout << " i = " << i << " x = " << simplex(i).second << " fval(x) = " << simplex(i).first << std::endl; #endif - + double edmPrev = simplex.Edm(); int niterations = 0; do { @@ -85,15 +85,15 @@ FunctionMinimum SimplexBuilder::Minimum(const MnFcn& mfcn, const GradientCalcula jh = simplex.Jh(); amin = simplex(jl).first; edmPrev = simplex.Edm(); - + #ifdef DEBUG - std::cout << "\n\nsimplex iteration: edm = " << simplex.Edm() - << "\n--> Min Param is " << jl << " pmin " << simplex(jl).second << " f(pmin) " << amin + std::cout << "\n\nsimplex iteration: edm = " << simplex.Edm() + << "\n--> Min Param is " << jl << " pmin " << simplex(jl).second << " f(pmin) " << amin << "\n--> Max param is " << jh << " " << simplex(jh).first << std::endl; - - // std::cout << "ALL SIMPLEX PARAMETERS: "<< std::endl; - // for (unsigned int i = 0; i < simplex.Simplex().size(); ++i) - // std::cout << " i = " << i << " x = " << simplex(i).second << " fval(x) = " << simplex(i).first << std::endl; + + // std::cout << "ALL SIMPLEX PARAMETERS: "<< std::endl; + // for (unsigned int i = 0; i < simplex.Simplex().size(); ++i) + // std::cout << " i = " << i << " x = " << simplex(i).second << " fval(x) = " << simplex(i).first << std::endl; #endif // trace the iterations (need to create a MinimunState although errors and gradient are not existing) @@ -107,36 +107,36 @@ FunctionMinimum SimplexBuilder::Minimum(const MnFcn& mfcn, const GradientCalcula if(i == jh) continue; pbar += (wg*simplex(i).second); } - + MnAlgebraicVector pstar = (1. + alpha)*pbar - alpha*simplex(jh).second; double ystar = mfcn(pstar); - + #ifdef DEBUG std::cout << " pbar = " << pbar << std::endl; std::cout << " pstar = " << pstar << " f(pstar) = " << ystar << std::endl; #endif - + if(ystar > amin) { if(ystar < simplex(jh).first) { simplex.Update(ystar, pstar); if(jh != simplex.Jh()) continue; - } + } MnAlgebraicVector pstst = beta*simplex(jh).second + (1. - beta)*pbar; double ystst = mfcn(pstst); #ifdef DEBUG std::cout << "Reduced simplex pstst = " << pstst << " f(pstst) = " << ystst << std::endl; -#endif - if(ystst > simplex(jh).first) break; +#endif + if(ystst > simplex(jh).first) break; simplex.Update(ystst, pstst); continue; } - + MnAlgebraicVector pstst = gamma*pstar + (1. - gamma)*pbar; double ystst = mfcn(pstst); #ifdef DEBUG std::cout << " pstst = " << pstst << " f(pstst) = " << ystst << std::endl; #endif - + double y1 = (ystar - simplex(jh).first)*rho2; double y2 = (ystst - simplex(jh).first)*rho1; double rho = 0.5*(rho2*y1 - rho1*y2)/(y1 - y2); @@ -167,18 +167,18 @@ FunctionMinimum SimplexBuilder::Minimum(const MnFcn& mfcn, const GradientCalcula if(ystar > simplex(jh).first) { pstst = beta*simplex(jh).second + (1. - beta)*pbar; ystst = mfcn(pstst); - if(ystst > simplex(jh).first) break; + if(ystst > simplex(jh).first) break; simplex.Update(ystst, pstst); } #ifdef DEBUG std::cout << "End loop : edm = " << simplex.Edm() << " pstst = " << pstst << " f(pstst) = " << ystst << std::endl; #endif } while( (simplex.Edm() > minedm || edmPrev > minedm ) && mfcn.NumOfCalls() < maxfcn); - + jl = simplex.Jl(); jh = simplex.Jh(); amin = simplex(jl).first; - + MnAlgebraicVector pbar(n); for(unsigned int i = 0; i < n+1; i++) { if(i == jh) continue; @@ -190,22 +190,22 @@ FunctionMinimum SimplexBuilder::Minimum(const MnFcn& mfcn, const GradientCalcula pbar = simplex(jl).second; ybar = simplex(jl).first; } - + MnAlgebraicVector dirin = simplex.Dirin(); - // Scale to sigmas on parameters werr^2 = dirin^2 * (up/edm) + // Scale to sigmas on parameters werr^2 = dirin^2 * (up/edm) dirin *= sqrt(mfcn.Up()/simplex.Edm()); - + #ifdef DEBUG std::cout << "End simplex " << simplex.Edm() << " pbar = " << pbar << " f(p) = " << ybar << std::endl; #endif - - + + MinimumState st(MinimumParameters(pbar, dirin, ybar), simplex.Edm(), mfcn.NumOfCalls()); - if (PrintLevel() > 1) + if (PrintLevel() > 1) MnPrint::PrintState(std::cout,st,"Simplex: Final iteration"); if (TraceIter() ) TraceIteration(niterations, st); - + if(mfcn.NumOfCalls() > maxfcn) { #ifdef WARNINGMSG MN_INFO_MSG("Simplex did not converge, #fcn calls exhausted."); @@ -218,7 +218,7 @@ FunctionMinimum SimplexBuilder::Minimum(const MnFcn& mfcn, const GradientCalcula #endif return FunctionMinimum(seed, std::vector<MinimumState>(1, st), mfcn.Up(), FunctionMinimum::MnAboveMaxEdm()); } - + return FunctionMinimum(seed, std::vector<MinimumState>(1, st), mfcn.Up()); } diff --git a/ThirdParty/RootMinimizers/src/Minuit2/SimplexParameters.cxx b/ThirdParty/RootMinimizers/src/Minuit2/SimplexParameters.cxx index 66bebdef98cb83dbdd1a342ed28160e0425d5cd3..22c57910dc6c4b9b6faed45a770c0b37829b8770 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/SimplexParameters.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/SimplexParameters.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -18,15 +18,15 @@ void SimplexParameters::Update(double y, const MnAlgebraicVector& p) { // update the SimplexParameter object with a new value y = FCN(p) fSimplexParameters[Jh()] = std::pair<double, MnAlgebraicVector>(y, p); if(y < fSimplexParameters[Jl()].first) fJLow = Jh(); - + unsigned int jh = 0; for(unsigned int i = 1; i < fSimplexParameters.size(); i++) { if(fSimplexParameters[i].first > fSimplexParameters[jh].first) jh = i; } fJHigh = jh; - + return; -} +} MnAlgebraicVector SimplexParameters::Dirin() const { // find simplex direction (vector from big to smaller parameter points) @@ -38,8 +38,8 @@ MnAlgebraicVector SimplexParameters::Dirin() const { if(fSimplexParameters[j].second(i) > pbig) pbig = fSimplexParameters[j].second(i); } dirin(i) = pbig - plit; - } - + } + return dirin; } diff --git a/ThirdParty/RootMinimizers/src/Minuit2/SimplexSeedGenerator.cxx b/ThirdParty/RootMinimizers/src/Minuit2/SimplexSeedGenerator.cxx index 4db4862346831e0a79e37bd8f86ef8a4c1ffa352..f900cc11fd3580004dccec05b1c96c92e297157e 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/SimplexSeedGenerator.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/SimplexSeedGenerator.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -21,11 +21,11 @@ namespace ROOT { MinimumSeed SimplexSeedGenerator::operator()(const MnFcn& fcn, const GradientCalculator&, const MnUserParameterState& st, const MnStrategy& stra) const { - // create starting state for Simplex, which corresponds to the initial parameter values + // create starting state for Simplex, which corresponds to the initial parameter values // using the simple Initial gradient calculator (does not use any FCN function calls) unsigned int n = st.VariableParameters(); const MnMachinePrecision& prec = st.Precision(); - + // initial starting values MnAlgebraicVector x(n); for(unsigned int i = 0; i < n; i++) x(i) = st.IntParameters()[i]; @@ -40,8 +40,8 @@ MinimumSeed SimplexSeedGenerator::operator()(const MnFcn& fcn, const GradientCal MinimumError err(mat, dcovar); double edm = VariableMetricEDMEstimator().Estimate(dgrad, err); MinimumState state(pa, err, dgrad, edm, fcn.NumOfCalls()); - - return MinimumSeed(state, st.Trafo()); + + return MinimumSeed(state, st.Trafo()); } MinimumSeed SimplexSeedGenerator::operator()(const MnFcn& fcn, const AnalyticalGradientCalculator& gc, const MnUserParameterState& st, const MnStrategy& stra) const { diff --git a/ThirdParty/RootMinimizers/src/Minuit2/SinParameterTransformation.cxx b/ThirdParty/RootMinimizers/src/Minuit2/SinParameterTransformation.cxx index 9f279e6c5a218773eb739f584a9fe2901b79d9b9..a58a68ed34ee2680ff4dae71a109cad5a8351ddb 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/SinParameterTransformation.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/SinParameterTransformation.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -25,12 +25,12 @@ double SinParameterTransformation::Int2ext(double Value, double Upper, double Lo double SinParameterTransformation::Ext2int(double Value, double Upper, double Lower, const MnMachinePrecision& prec) const { // transformation from external (limited by Lower/Upper ) to internal (unlimited) values given the lower/upper limits - + double piby2 = 2.*atan(1.); double distnn = 8.*sqrt(prec.Eps2()); double vlimhi = piby2 - distnn; double vlimlo = -piby2 + distnn; - + double yy = 2.*(Value - Lower)/(Upper - Lower) - 1.; double yy2 = yy*yy; if(yy2 > (1. - prec.Eps2())) { @@ -43,9 +43,9 @@ double SinParameterTransformation::Ext2int(double Value, double Upper, double Lo // std::cout<<"SinParameterTransformation warning: is at its Upper allowed limit."<<std::endl; return vlimhi; } - + } else { - return asin(yy); + return asin(yy); } } diff --git a/ThirdParty/RootMinimizers/src/Minuit2/SqrtLowParameterTransformation.cxx b/ThirdParty/RootMinimizers/src/Minuit2/SqrtLowParameterTransformation.cxx index 08a0c89d50f38a5735932867dbe26212500da5b9..cee2b57219f4159c675fd19de7f2d1ce27ac73e4 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/SqrtLowParameterTransformation.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/SqrtLowParameterTransformation.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -9,7 +9,7 @@ // Project : LCG // Package : Minuit -// Author : Lorenzo.MONETA@cern.ch +// Author : Lorenzo.MONETA@cern.ch // Created by: moneta at Thu Apr 8 10:26:22 2004 #include "Minuit2/SqrtLowParameterTransformation.h" @@ -22,27 +22,27 @@ namespace ROOT { double SqrtLowParameterTransformation::Int2ext(double value, double lower) const { - /// internal to external transformation + /// internal to external transformation double val = lower - 1. + sqrt( value*value + 1.); - return val; + return val; } double SqrtLowParameterTransformation::Ext2int(double value, double lower, const MnMachinePrecision& ) const { // external to internal transformation - double yy = value - lower + 1.; - double yy2 = yy*yy; - if (yy2 < 1. ) - return 0; - else - return sqrt( yy2 -1); + double yy = value - lower + 1.; + double yy2 = yy*yy; + if (yy2 < 1. ) + return 0; + else + return sqrt( yy2 -1); } double SqrtLowParameterTransformation::DInt2Ext(double value, double) const { - // derivative of internal to external transofrmation : d (Int2Ext) / d Int + // derivative of internal to external transofrmation : d (Int2Ext) / d Int double val = value/( sqrt( value*value + 1.) ); - return val; + return val; } } // namespace Minuit2 diff --git a/ThirdParty/RootMinimizers/src/Minuit2/SqrtUpParameterTransformation.cxx b/ThirdParty/RootMinimizers/src/Minuit2/SqrtUpParameterTransformation.cxx index a23829b2267f541d397355bd2a29117aa25836f5..d35ec4938a15d725c420db291bbb7fedaf7ecfca 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/SqrtUpParameterTransformation.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/SqrtUpParameterTransformation.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -9,7 +9,7 @@ // Project : LCG // Package : Minuit -// Author : Lorenzo.MONETA@cern.ch +// Author : Lorenzo.MONETA@cern.ch // Created by: moneta at Thu Apr 8 10:26:22 2004 @@ -25,25 +25,25 @@ namespace ROOT { double SqrtUpParameterTransformation::Int2ext(double value, double upper) const { // internal to external transformation double val = upper + 1. - sqrt( value*value + 1.); - return val; + return val; } double SqrtUpParameterTransformation::Ext2int(double value, double upper, const MnMachinePrecision& ) const { - // external to internal transformation - double yy = upper - value + 1.; - double yy2 = yy*yy; - if (yy2 < 1. ) - return 0; - else - return sqrt( yy2 -1); + // external to internal transformation + double yy = upper - value + 1.; + double yy2 = yy*yy; + if (yy2 < 1. ) + return 0; + else + return sqrt( yy2 -1); } double SqrtUpParameterTransformation::DInt2Ext(double value, double) const { - // derivative of internal to external transofrmation : d (Int2Ext ) / d Int + // derivative of internal to external transofrmation : d (Int2Ext ) / d Int double val = - value/( sqrt( value*value + 1.) ); - return val; + return val; } } // namespace Minuit2 diff --git a/ThirdParty/RootMinimizers/src/Minuit2/VariableMetricBuilder.cxx b/ThirdParty/RootMinimizers/src/Minuit2/VariableMetricBuilder.cxx index 9b42667e58a080de98f02237b0aa64924ff8eb8b..675313c721f00a6ecc5e675abf662a9c3b7165f6 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/VariableMetricBuilder.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/VariableMetricBuilder.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -24,8 +24,8 @@ #include "Minuit2/MnStrategy.h" #include "Minuit2/MnHesse.h" -//#define DEBUG -#include "Minuit2/MnPrint.h" +//#define DEBUG +#include "Minuit2/MnPrint.h" // #if defined(DEBUG) || defined(WARNINGMSG) // #endif @@ -42,46 +42,46 @@ double inner_product(const LAVector&, const LAVector&); void VariableMetricBuilder::AddResult( std::vector<MinimumState>& result, const MinimumState & state, bool store) const { if (!store) store = StorageLevel(); store |= (result.size() == 0); - if (store) + if (store) result.push_back(state); - else { - result.back() = state; + else { + result.back() = state; } if (TraceIter() ) TraceIteration(result.size()-1, result.back() ); else { if (PrintLevel() > 1) { - MnPrint::PrintState(std::cout, result.back(), "VariableMetric: Iteration # ",result.size()-1); + MnPrint::PrintState(std::cout, result.back(), "VariableMetric: Iteration # ",result.size()-1); } } } -FunctionMinimum VariableMetricBuilder::Minimum(const MnFcn& fcn, const GradientCalculator& gc, const MinimumSeed& seed, const MnStrategy& strategy, unsigned int maxfcn, double edmval) const { - // top level function to find minimum from a given initial seed +FunctionMinimum VariableMetricBuilder::Minimum(const MnFcn& fcn, const GradientCalculator& gc, const MinimumSeed& seed, const MnStrategy& strategy, unsigned int maxfcn, double edmval) const { + // top level function to find minimum from a given initial seed // iterate on a minimum search in case of first attempt is not successful - + // to be consistent with F77 Minuit // in Minuit2 edm is correct and is ~ a factor of 2 smaller than F77Minuit - // There are also a check for convergence if (edm < 0.1 edmval for exiting the loop) + // There are also a check for convergence if (edm < 0.1 edmval for exiting the loop) // LM: change factor to 2E-3 to be consistent with F77Minuit - edmval *= 0.002; - + edmval *= 0.002; + int printLevel = PrintLevel(); - + #ifdef DEBUG std::cout<<"VariableMetricBuilder convergence when edm < "<<edmval<<std::endl; #endif - + if(seed.Parameters().Vec().size() == 0) { return FunctionMinimum(seed, fcn.Up()); } - - + + // double edm = Estimator().Estimate(seed.Gradient(), seed.Error()); double edm = seed.State().Edm(); - + FunctionMinimum min(seed, fcn.Up() ); - + if(edm < 0.) { #ifdef WARNINGMSG MN_INFO_MSG("VariableMetricBuilder: initial matrix not pos.def."); @@ -89,49 +89,49 @@ FunctionMinimum VariableMetricBuilder::Minimum(const MnFcn& fcn, const GradientC //assert(!seed.Error().IsPosDef()); return min; } - + std::vector<MinimumState> result; - if (StorageLevel() > 0) + if (StorageLevel() > 0) result.reserve(10); else result.reserve(2); - - + + // do actual iterations if (printLevel >1) { std::cout << "VariableMetric: start iterating until Edm is < " << edmval << std::endl; - MnPrint::PrintState(std::cout, seed.State(), "VariableMetric: Initial state "); + MnPrint::PrintState(std::cout, seed.State(), "VariableMetric: Initial state "); } AddResult( result, seed.State(), true); - - - // try first with a maxfxn = 80% of maxfcn + + + // try first with a maxfxn = 80% of maxfcn int maxfcn_eff = maxfcn; int ipass = 0; - bool iterate = false; - - do { - - iterate = false; + bool iterate = false; + + do { + + iterate = false; #ifdef DEBUG - std::cout << "start iterating... " << std::endl; - if (ipass > 0) std::cout << "continue iterating... " << std::endl; + std::cout << "start iterating... " << std::endl; + if (ipass > 0) std::cout << "continue iterating... " << std::endl; #endif - + min = Minimum(fcn, gc, seed, result, maxfcn_eff, edmval); // if max function call reached exits - if ( min.HasReachedCallLimit() ) { + if ( min.HasReachedCallLimit() ) { #ifdef WARNINGMSG MN_INFO_MSG("VariableMetricBuilder: FunctionMinimum is invalid, reached the function call limit"); #endif - return min; + return min; } - - // second time check for validity of function Minimum - if (ipass > 0) { + + // second time check for validity of function Minimum + if (ipass > 0) { if(!min.IsValid()) { #ifdef WARNINGMSG MN_INFO_MSG("VariableMetricBuilder: FunctionMinimum is invalid after second try"); @@ -139,44 +139,44 @@ FunctionMinimum VariableMetricBuilder::Minimum(const MnFcn& fcn, const GradientC return min; } } - + // resulting edm of minimization edm = result.back().Edm(); - // need to re-coorect for Dcovar ? - - if( (strategy.Strategy() == 2) || + // need to re-coorect for Dcovar ? + + if( (strategy.Strategy() == 2) || (strategy.Strategy() == 1 && min.Error().Dcovar() > 0.05) ) { - + #ifdef DEBUG std::cout<<"MnMigrad will verify convergence and Error matrix. "<< std::endl; std::cout<<"dcov is = "<< min.Error().Dcovar() << std::endl; #endif - + MinimumState st = MnHesse(strategy)(fcn, min.State(), min.Seed().Trafo(),maxfcn); - if (printLevel > 1) { - MnPrint::PrintState(std::cout, st, "VariableMetric: After Hessian "); + if (printLevel > 1) { + MnPrint::PrintState(std::cout, st, "VariableMetric: After Hessian "); } - AddResult( result, st, true); + AddResult( result, st, true); - - // check new edm + + // check new edm edm = st.Edm(); #ifdef DEBUG std::cout << "edm after Hesse calculation " << edm << " requested " << edmval << std::endl; #endif - if (edm > edmval) { + if (edm > edmval) { // be careful with machine precision and avoid too small edm - double machineLimit = fabs(seed.Precision().Eps2()*result.back().Fval()); - if (edm >= machineLimit) { - iterate = true; + double machineLimit = fabs(seed.Precision().Eps2()*result.back().Fval()); + if (edm >= machineLimit) { + iterate = true; #ifdef WARNINGMSG MN_INFO_MSG("VariableMetricBuilder: Tolerance is not sufficient, continue the minimization"); MN_INFO_VAL2("Current Edm is",edm); MN_INFO_VAL2("Required Edm is",edmval); #endif } - else { + else { #ifdef WARNINGMSG MN_INFO_MSG("VariableMetricBuilder: Stop the minimization - reached machine accuracy limit"); MN_INFO_VAL2("Edm is smaller than machine accuracy",machineLimit); @@ -187,19 +187,19 @@ FunctionMinimum VariableMetricBuilder::Minimum(const MnFcn& fcn, const GradientC } } - - + + // end loop on iterations - // ? need a maximum here (or max of function calls is enough ? ) - // continnue iteration (re-calculate function Minimum if edm IS NOT sufficient) + // ? need a maximum here (or max of function calls is enough ? ) + // continnue iteration (re-calculate function Minimum if edm IS NOT sufficient) // no need to check that hesse calculation is done (if isnot done edm is OK anyway) // count the pass to exit second time when function Minimum is invalid // increase by 20% maxfcn for doing some more tests if (ipass == 0) maxfcn_eff = int(maxfcn*1.3); ipass++; } while ( iterate ); - - + + // Add latest state (Hessian calculation) // and check edm (add a factor of 10 in tolerance ) if (edm > 10*edmval) { @@ -223,68 +223,68 @@ FunctionMinimum VariableMetricBuilder::Minimum(const MnFcn& fcn, const GradientC #ifdef DEBUG std::cout << "Obtained function minimum " << min << std::endl; #endif - + return min; } FunctionMinimum VariableMetricBuilder::Minimum(const MnFcn& fcn, const GradientCalculator& gc, const MinimumSeed& seed, std::vector<MinimumState>& result, unsigned int maxfcn, double edmval) const { - // function performing the minimum searches using the Variable Metric algorithm (MIGRAD) + // function performing the minimum searches using the Variable Metric algorithm (MIGRAD) // perform first a line search in the - Vg direction and then update using the Davidon formula (Davidon Error updator) // stop when edm reached is less than required (edmval) - - // after the modification when I iterate on this functions, so it can be called many times, - // the seed is used here only to get precision and construct the returned FunctionMinimum object - - + // after the modification when I iterate on this functions, so it can be called many times, + // the seed is used here only to get precision and construct the returned FunctionMinimum object + + + const MnMachinePrecision& prec = seed.Precision(); - - + + // result.push_back(MinimumState(seed.Parameters(), seed.Error(), seed.Gradient(), edm, fcn.NumOfCalls())); const MinimumState & initialState = result.back(); - + double edm = initialState.Edm(); - - + + #ifdef DEBUG - std::cout << "\n\nDEBUG Variable Metric Builder \nInitial State: " - << " Parameter " << initialState.Vec() - << " Gradient " << initialState.Gradient().Vec() - << " Inv Hessian " << initialState.Error().InvHessian() + std::cout << "\n\nDEBUG Variable Metric Builder \nInitial State: " + << " Parameter " << initialState.Vec() + << " Gradient " << initialState.Gradient().Vec() + << " Inv Hessian " << initialState.Error().InvHessian() << " edm = " << initialState.Edm() << std::endl; #endif - - - + + + // iterate until edm is small enough or max # of iterations reached edm *= (1. + 3.*initialState.Error().Dcovar()); MnLineSearch lsearch; MnAlgebraicVector step(initialState.Gradient().Vec().size()); // keep also prevStep MnAlgebraicVector prevStep(initialState.Gradient().Vec().size()); - - do { + + do { // const MinimumState& s0 = result.back(); MinimumState s0 = result.back(); - + step = -1.*s0.Error().InvHessian()*s0.Gradient().Vec(); - + #ifdef DEBUG - std::cout << "\n\n---> Iteration - " << result.size() - << "\nFval = " << s0.Fval() << " numOfCall = " << fcn.NumOfCalls() - << "\nInternal Parameter values " << s0.Vec() - << " Newton step " << step << std::endl; + std::cout << "\n\n---> Iteration - " << result.size() + << "\nFval = " << s0.Fval() << " numOfCall = " << fcn.NumOfCalls() + << "\nInternal Parameter values " << s0.Vec() + << " Newton step " << step << std::endl; #endif - + // check if derivatives are not zero - if ( inner_product(s0.Gradient().Vec(),s0.Gradient().Vec() ) <= 0 ) { + if ( inner_product(s0.Gradient().Vec(),s0.Gradient().Vec() ) <= 0 ) { #ifdef DEBUG std::cout << "VariableMetricBuilder: all derivatives are zero - return current status" << std::endl; #endif break; } - + double gdel = inner_product(step, s0.Gradient().Grad()); @@ -302,7 +302,7 @@ FunctionMinimum VariableMetricBuilder::Minimum(const MnFcn& fcn, const GradientC s0 = psdf(s0, prec); step = -1.*s0.Error().InvHessian()*s0.Gradient().Vec(); // #ifdef DEBUG - // std::cout << "After MnPosdef - Error " << s0.Error().InvHessian() << " Gradient " << s0.Gradient().Vec() << " step " << step << std::endl; + // std::cout << "After MnPosdef - Error " << s0.Error().InvHessian() << " Gradient " << s0.Gradient().Vec() << " step " << step << std::endl; // #endif gdel = inner_product(step, s0.Gradient().Grad()); #ifdef WARNINGMSG @@ -322,31 +322,31 @@ FunctionMinimum VariableMetricBuilder::Minimum(const MnFcn& fcn, const GradientC #endif // no improvement exit (is it really needed LM ? in vers. 1.22 tried alternative ) // add new state where only fcn changes - AddResult(result, MinimumState(s0.Parameters(), s0.Error(), s0.Gradient(), s0.Edm(), fcn.NumOfCalls()), + AddResult(result, MinimumState(s0.Parameters(), s0.Error(), s0.Gradient(), s0.Edm(), fcn.NumOfCalls()), result.size()<=1); - break; - - + break; + + } - + #ifdef DEBUG - std::cout << "Result after line search : \nx = " << pp.X() - << "\nOld Fval = " << s0.Fval() - << "\nNew Fval = " << pp.Y() - << "\nNFcalls = " << fcn.NumOfCalls() << std::endl; + std::cout << "Result after line search : \nx = " << pp.X() + << "\nOld Fval = " << s0.Fval() + << "\nNew Fval = " << pp.Y() + << "\nNFcalls = " << fcn.NumOfCalls() << std::endl; #endif - + MinimumParameters p(s0.Vec() + pp.X()*step, pp.Y()); - - + + FunctionGradient g = gc(p, s0.Gradient()); - - + + edm = Estimator().Estimate(g, s0.Error()); - - + + if(edm < 0.) { #ifdef WARNINGMSG MN_INFO_MSG("VariableMetricBuilder: matrix not pos.def. : edm is < 0. Make pos def..."); @@ -361,46 +361,46 @@ FunctionMinimum VariableMetricBuilder::Minimum(const MnFcn& fcn, const GradientC result.push_back(s0); return FunctionMinimum(seed, result, fcn.Up()); } - } + } MinimumError e = ErrorUpdator().Update(s0, p, g); - + #ifdef DEBUG - std::cout << "Updated new point: \n " - << " Parameter " << p.Vec() - << " Gradient " << g.Vec() - << " InvHessian " << e.Matrix() - << " Hessian " << e.Hessian() + std::cout << "Updated new point: \n " + << " Parameter " << p.Vec() + << " Gradient " << g.Vec() + << " InvHessian " << e.Matrix() + << " Hessian " << e.Hessian() << " edm = " << edm << std::endl << std::endl; #endif - - AddResult(result, MinimumState(p, e, g, edm, fcn.NumOfCalls()), result.size() <= 1); - - // correct edm + + AddResult(result, MinimumState(p, e, g, edm, fcn.NumOfCalls()), result.size() <= 1); + + // correct edm edm *= (1. + 3.*e.Dcovar()); - + #ifdef DEBUG std::cout << "Dcovar = " << e.Dcovar() << "\tCorrected edm = " << edm << std::endl; #endif - - - + + + } while(edm > edmval && fcn.NumOfCalls() < maxfcn); // end of iteration loop - + if(fcn.NumOfCalls() >= maxfcn) { #ifdef WARNINGMSG MN_INFO_MSG("VariableMetricBuilder: call limit exceeded."); #endif return FunctionMinimum(seed, result, fcn.Up(), FunctionMinimum::MnReachedCallLimit()); } - + if(edm > edmval) { if(edm < fabs(prec.Eps2()*result.back().Fval())) { #ifdef WARNINGMSG MN_INFO_MSG("VariableMetricBuilder: machine accuracy limits further improvement."); #endif return FunctionMinimum(seed, result, fcn.Up()); - } else if(edm < 10*edmval) { + } else if(edm < 10*edmval) { return FunctionMinimum(seed, result, fcn.Up()); } else { #ifdef WARNINGMSG @@ -412,14 +412,14 @@ FunctionMinimum VariableMetricBuilder::Minimum(const MnFcn& fcn, const GradientC } } // std::cout<<"result.back().Error().Dcovar()= "<<result.back().Error().Dcovar()<<std::endl; - + #ifdef DEBUG - std::cout << "Exiting successfully Variable Metric Builder \n" - << "NFCalls = " << fcn.NumOfCalls() - << "\nFval = " << result.back().Fval() - << "\nedm = " << edm << " requested = " << edmval << std::endl; + std::cout << "Exiting successfully Variable Metric Builder \n" + << "NFCalls = " << fcn.NumOfCalls() + << "\nFval = " << result.back().Fval() + << "\nedm = " << edm << " requested = " << edmval << std::endl; #endif - + return FunctionMinimum(seed, result, fcn.Up()); } diff --git a/ThirdParty/RootMinimizers/src/Minuit2/VariableMetricEDMEstimator.cxx b/ThirdParty/RootMinimizers/src/Minuit2/VariableMetricEDMEstimator.cxx index a9ffa04eeeb78cbe37cc10b34d3643d18f58aaf3..409de1d4efd04a2dd89e50e535875a85b77be81c 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/VariableMetricEDMEstimator.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/VariableMetricEDMEstimator.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -19,12 +19,12 @@ namespace ROOT { double similarity(const LAVector&, const LASymMatrix&); double VariableMetricEDMEstimator::Estimate(const FunctionGradient& g, const MinimumError& e) const { - // estimate the edm (expected distance to the minimum) = 0.5 * g^T V g (where V is the error matrix, inverse of Hessian) - // assuminigfirst derivatives if F are zero at the mminimum, - - if(e.InvHessian().size() == 1) + // estimate the edm (expected distance to the minimum) = 0.5 * g^T V g (where V is the error matrix, inverse of Hessian) + // assuminigfirst derivatives if F are zero at the mminimum, + + if(e.InvHessian().size() == 1) return 0.5*g.Grad()(0)*g.Grad()(0)*e.InvHessian()(0,0); - + double rho = similarity(g.Grad(), e.InvHessian()); return 0.5*rho; } diff --git a/ThirdParty/RootMinimizers/src/Minuit2/mnbins.cxx b/ThirdParty/RootMinimizers/src/Minuit2/mnbins.cxx index cefd2bad0c72b4d412705c9f24301aba459be638..878313817654384133301a439b29b9d5d9e171fa 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/mnbins.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/mnbins.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -24,23 +24,23 @@ void mnbins(double a1, double a2, int naa, double& bl, double& bh, int& nb, doub //*-* PROGRAM MAKES REASONABLE BINNING FROM BL TO BH OF WIDTH BWID //*-* F. JAMES, AUGUST, 1974 , stolen for Minuit, 1988 //*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* - + /* Local variables */ double awid,ah, al, sigfig, sigrnd, alb; int kwid, lwid, na=0, log_; - + al = a1 < a2 ? a1 : a2; // al = std::min(a1,a2); // ah = std::max(a1,a2); ah = a1 > a2 ? a1 : a2; if (al == ah) ah = al + 1; - + //*-*- IF NAA .EQ. -1 , PROGRAM USES BWID INPUT FROM CALLING ROUTINE if (naa == -1) goto L150; L10: na = naa - 1; if (na < 1) na = 1; - + //*-*- GET NOMINAL BIN WIDTH IN EXPON FORM L20: awid = (ah-al) / double(na); diff --git a/ThirdParty/RootMinimizers/src/Minuit2/mndasum.cxx b/ThirdParty/RootMinimizers/src/Minuit2/mndasum.cxx index 727d3afb8675c32e9bb4ff90be84bcae8f4de046..5fef071d32e85613230f244a605a13776ff462d5 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/mndasum.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/mndasum.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -23,22 +23,22 @@ double mndasum(unsigned int n, const double* dx, int incx) { /* System generated locals */ int i__1, i__2; double ret_val, d__1, d__2, d__3, d__4, d__5, d__6; - + /* Local variables */ int i__, m; double dtemp; int nincx, mp1; - - + + /* takes the sum of the absolute values. */ /* jack dongarra, linpack, 3/11/78. */ /* modified 3/93 to return if incx .le. 0. */ /* modified 12/3/93, array(1) declarations changed to array(*) */ - - + + /* Parameter adjustments */ --dx; - + /* Function Body */ ret_val = 0.; dtemp = 0.; @@ -48,9 +48,9 @@ double mndasum(unsigned int n, const double* dx, int incx) { if (incx == 1) { goto L20; } - + /* code for increment not equal to 1 */ - + nincx = n * incx; i__1 = nincx; i__2 = incx; @@ -60,12 +60,12 @@ double mndasum(unsigned int n, const double* dx, int incx) { } ret_val = dtemp; return ret_val; - + /* code for increment equal to 1 */ - - + + /* clean-up loop */ - + L20: m = n % 6; if (m == 0) { @@ -83,9 +83,9 @@ L40: mp1 = m + 1; i__2 = n; for (i__ = mp1; i__ <= i__2; i__ += 6) { - dtemp = dtemp + (d__1 = dx[i__], fabs(d__1)) + (d__2 = dx[i__ + 1], - fabs(d__2)) + (d__3 = dx[i__ + 2], fabs(d__3)) + - (d__4 = dx[i__ + 3], fabs(d__4)) + + dtemp = dtemp + (d__1 = dx[i__], fabs(d__1)) + (d__2 = dx[i__ + 1], + fabs(d__2)) + (d__3 = dx[i__ + 2], fabs(d__3)) + + (d__4 = dx[i__ + 3], fabs(d__4)) + (d__5 = dx[i__ + 4], fabs(d__5)) + (d__6 = dx[i__ + 5], fabs(d__6)); /* L50: */ } diff --git a/ThirdParty/RootMinimizers/src/Minuit2/mndaxpy.cxx b/ThirdParty/RootMinimizers/src/Minuit2/mndaxpy.cxx index 16e2723a39e44787f44082962d02ad52f032d8a8..91cbd6a39c0832fbae021cf4d261199847c8bff1 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/mndaxpy.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/mndaxpy.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -16,26 +16,26 @@ namespace ROOT { namespace Minuit2 { - -int Mndaxpy(unsigned int n, double da, const double* dx, int incx, double* dy, + +int Mndaxpy(unsigned int n, double da, const double* dx, int incx, double* dy, int incy) { /* System generated locals */ int i__1; - + /* Local variables */ int i__, m, ix, iy, mp1; - - + + /* constant times a vector plus a vector. */ /* uses unrolled loops for increments equal to one. */ /* jack dongarra, linpack, 3/11/78. */ /* modified 12/3/93, array(1) declarations changed to array(*) */ - - + + /* Parameter adjustments */ --dy; --dx; - + /* Function Body */ if (n <= 0) { return 0; @@ -46,10 +46,10 @@ int Mndaxpy(unsigned int n, double da, const double* dx, int incx, double* dy, if (incx == 1 && incy == 1) { goto L20; } - + /* code for unequal increments or equal increments */ /* not equal to 1 */ - + ix = 1; iy = 1; if (incx < 0) { @@ -66,12 +66,12 @@ int Mndaxpy(unsigned int n, double da, const double* dx, int incx, double* dy, /* L10: */ } return 0; - + /* code for both increments equal to 1 */ - - + + /* clean-up loop */ - + L20: m = n % 4; if (m == 0) { diff --git a/ThirdParty/RootMinimizers/src/Minuit2/mnddot.cxx b/ThirdParty/RootMinimizers/src/Minuit2/mnddot.cxx index 860f1e43f8e54e0f39c1f2f27387abceacccb5f9..67bb2a0870add9bd5a6d55613b860a898146bb7e 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/mnddot.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/mnddot.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -17,28 +17,28 @@ namespace ROOT { namespace Minuit2 { -double mnddot(unsigned int n, const double* dx, int incx, const double* dy, +double mnddot(unsigned int n, const double* dx, int incx, const double* dy, int incy) { /* System generated locals */ int i__1; double ret_val; - + /* Local variables */ int i__, m; double dtemp; int ix, iy, mp1; - - + + /* forms the dot product of two vectors. */ /* uses unrolled loops for increments equal to one. */ /* jack dongarra, linpack, 3/11/78. */ /* modified 12/3/93, array(1) declarations changed to array(*) */ - - + + /* Parameter adjustments */ --dy; --dx; - + /* Function Body */ ret_val = 0.; dtemp = 0.; @@ -48,10 +48,10 @@ double mnddot(unsigned int n, const double* dx, int incx, const double* dy, if (incx == 1 && incy == 1) { goto L20; } - + /* code for unequal increments or equal increments */ /* not equal to 1 */ - + ix = 1; iy = 1; if (incx < 0) { @@ -69,12 +69,12 @@ double mnddot(unsigned int n, const double* dx, int incx, const double* dy, } ret_val = dtemp; return ret_val; - + /* code for both increments equal to 1 */ - - + + /* clean-up loop */ - + L20: m = n % 5; if (m == 0) { @@ -93,7 +93,7 @@ L40: i__1 = n; for (i__ = mp1; i__ <= i__1; i__ += 5) { dtemp = dtemp + dx[i__] * dy[i__] + dx[i__ + 1] * dy[i__ + 1] + dx[ - i__ + 2] * dy[i__ + 2] + dx[i__ + 3] * dy[i__ + 3] + dx[i__ + + i__ + 2] * dy[i__ + 2] + dx[i__ + 3] * dy[i__ + 3] + dx[i__ + 4] * dy[i__ + 4]; /* L50: */ } diff --git a/ThirdParty/RootMinimizers/src/Minuit2/mndscal.cxx b/ThirdParty/RootMinimizers/src/Minuit2/mndscal.cxx index 0ef64770164a576931181227157614a4cb07f566..00f9b7affadce642efdb96d370bc047d90f68147 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/mndscal.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/mndscal.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -20,21 +20,21 @@ namespace ROOT { int Mndscal(unsigned int n, double da, double* dx, int incx) { /* System generated locals */ int i__1, i__2; - + /* Local variables */ int i__, m, nincx, mp1; - - + + /* scales a vector by a constant. */ /* uses unrolled loops for increment equal to one. */ /* jack dongarra, linpack, 3/11/78. */ /* modified 3/93 to return if incx .le. 0. */ /* modified 12/3/93, array(1) declarations changed to array(*) */ - - + + /* Parameter adjustments */ --dx; - + /* Function Body */ if (n <= 0 || incx <= 0) { return 0; @@ -42,9 +42,9 @@ int Mndscal(unsigned int n, double da, double* dx, int incx) { if (incx == 1) { goto L20; } - + /* code for increment not equal to 1 */ - + nincx = n * incx; i__1 = nincx; i__2 = incx; @@ -53,12 +53,12 @@ int Mndscal(unsigned int n, double da, double* dx, int incx) { /* L10: */ } return 0; - + /* code for increment equal to 1 */ - - + + /* clean-up loop */ - + L20: m = n % 5; if (m == 0) { diff --git a/ThirdParty/RootMinimizers/src/Minuit2/mndspmv.cxx b/ThirdParty/RootMinimizers/src/Minuit2/mndspmv.cxx index f726181a83aba35e954a52432c0e221e1eef514a..e35d23b237d24ff2649b7468af1cc122602c2168 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/mndspmv.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/mndspmv.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -20,57 +20,57 @@ namespace ROOT { bool mnlsame(const char*, const char*); int mnxerbla(const char*, int); -int Mndspmv(const char* uplo, unsigned int n, double alpha, - const double* ap, const double* x, int incx, double beta, +int Mndspmv(const char* uplo, unsigned int n, double alpha, + const double* ap, const double* x, int incx, double beta, double* y, int incy) { /* System generated locals */ int i__1, i__2; - + /* Local variables */ int info; double temp1, temp2; int i__, j, k; int kk, ix, iy, jx, jy, kx, ky; - + /* .. Scalar Arguments .. */ /* .. Array Arguments .. */ /* .. */ - + /* Purpose */ /* ======= */ - + /* DSPMV performs the matrix-vector operation */ - + /* y := alpha*A*x + beta*y, */ - + /* where alpha and beta are scalars, x and y are n element vectors and */ /* A is an n by n symmetric matrix, supplied in packed form. */ - + /* Parameters */ /* ========== */ - + /* UPLO - CHARACTER*1. */ /* On entry, UPLO specifies whether the Upper or Lower */ /* triangular part of the matrix A is supplied in the packed */ /* array AP as follows: */ - + /* UPLO = 'U' or 'u' The Upper triangular part of A is */ /* supplied in AP. */ - + /* UPLO = 'L' or 'l' The Lower triangular part of A is */ /* supplied in AP. */ - + /* Unchanged on exit. */ - + /* N - INTEGER. */ /* On entry, N specifies the order of the matrix A. */ /* N must be at least zero. */ /* Unchanged on exit. */ - + /* ALPHA - DOUBLE PRECISION. */ /* On entry, ALPHA specifies the scalar alpha. */ /* Unchanged on exit. */ - + /* AP - DOUBLE PRECISION array of DIMENSION at least */ /* ( ( n*( n + 1 ) )/2 ). */ /* Before entry with UPLO = 'U' or 'u', the array AP must */ @@ -84,66 +84,66 @@ int Mndspmv(const char* uplo, unsigned int n, double alpha, /* contains a( 1, 1 ), AP( 2 ) and AP( 3 ) contain a( 2, 1 ) */ /* and a( 3, 1 ) respectively, and so on. */ /* Unchanged on exit. */ - + /* X - DOUBLE PRECISION array of dimension at least */ /* ( 1 + ( n - 1 )*abs( INCX ) ). */ /* Before entry, the incremented array X must contain the n */ /* element vector x. */ /* Unchanged on exit. */ - + /* INCX - INTEGER. */ /* On entry, INCX specifies the increment for the Elements of */ /* X. INCX must not be zero. */ /* Unchanged on exit. */ - + /* BETA - DOUBLE PRECISION. */ /* On entry, BETA specifies the scalar beta. When BETA is */ /* supplied as zero then Y need not be set on input. */ /* Unchanged on exit. */ - + /* Y - DOUBLE PRECISION array of dimension at least */ /* ( 1 + ( n - 1 )*abs( INCY ) ). */ /* Before entry, the incremented array Y must contain the n */ /* element vector y. On exit, Y is overwritten by the updated */ /* vector y. */ - + /* INCY - INTEGER. */ /* On entry, INCY specifies the increment for the Elements of */ /* Y. INCY must not be zero. */ /* Unchanged on exit. */ - - + + /* Level 2 Blas routine. */ - + /* -- Written on 22-October-1986. */ /* Jack Dongarra, Argonne National Lab. */ /* Jeremy Du Croz, Nag Central Office. */ /* Sven Hammarling, Nag Central Office. */ /* Richard Hanson, Sandia National Labs. */ - - + + /* .. Parameters .. */ /* .. Local Scalars .. */ /* .. External Functions .. */ /* .. External Subroutines .. */ /* .. */ /* .. Executable Statements .. */ - + /* Test the input parameters. */ - + /* Parameter adjustments */ --y; --x; --ap; - + /* Function Body */ info = 0; if (! mnlsame(uplo, "U") && ! mnlsame(uplo, "L")) { info = 1; - } + } // else if (n < 0) { // info = 2; - // } + // } else if (incx == 0) { info = 6; } else if (incy == 0) { @@ -153,15 +153,15 @@ int Mndspmv(const char* uplo, unsigned int n, double alpha, mnxerbla("DSPMV ", info); return 0; } - + /* Quick return if possible. */ - + if ( ( n == 0) || ( alpha == 0. && beta == 1.) ) { return 0; } - + /* Set up the start points in X and Y. */ - + if (incx > 0) { kx = 1; } else { @@ -172,12 +172,12 @@ int Mndspmv(const char* uplo, unsigned int n, double alpha, } else { ky = 1 - (n - 1) * incy; } - + /* Start the operations. In this version the Elements of the array AP */ /* are accessed sequentially with one pass through AP. */ - + /* First form y := beta*y. */ - + if (beta != 1.) { if (incy == 1) { if (beta == 0.) { @@ -217,9 +217,9 @@ int Mndspmv(const char* uplo, unsigned int n, double alpha, } kk = 1; if (mnlsame(uplo, "U")) { - + /* Form y when AP contains the Upper triangle. */ - + if (incx == 1 && incy == 1) { i__1 = n; for (j = 1; j <= i__1; ++j) { @@ -262,9 +262,9 @@ int Mndspmv(const char* uplo, unsigned int n, double alpha, } } } else { - + /* Form y when AP contains the Lower triangle. */ - + if (incx == 1 && incy == 1) { i__1 = n; for (j = 1; j <= i__1; ++j) { @@ -309,11 +309,11 @@ int Mndspmv(const char* uplo, unsigned int n, double alpha, } } } - + return 0; - + /* End of DSPMV . */ - + } /* dspmv_ */ diff --git a/ThirdParty/RootMinimizers/src/Minuit2/mndspr.cxx b/ThirdParty/RootMinimizers/src/Minuit2/mndspr.cxx index a0d8a26bffdca6b4b87460ba00fb277333599d60..d4b772065e39c14dd72c94858d49509e737859df 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/mndspr.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/mndspr.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -20,67 +20,67 @@ namespace ROOT { bool mnlsame(const char*, const char*); int mnxerbla(const char*, int); -int mndspr(const char* uplo, unsigned int n, double alpha, +int mndspr(const char* uplo, unsigned int n, double alpha, const double* x, int incx, double* ap) { /* System generated locals */ int i__1, i__2; - + /* Local variables */ int info; double temp; int i__, j, k; int kk, ix, jx, kx = 0; - + /* .. Scalar Arguments .. */ /* .. Array Arguments .. */ /* .. */ - + /* Purpose */ /* ======= */ - + /* DSPR performs the symmetric rank 1 operation */ - + /* A := alpha*x*x' + A, */ - + /* where alpha is a real scalar, x is an n element vector and A is an */ /* n by n symmetric matrix, supplied in packed form. */ - + /* Parameters */ /* ========== */ - + /* UPLO - CHARACTER*1. */ /* On entry, UPLO specifies whether the Upper or Lower */ /* triangular part of the matrix A is supplied in the packed */ /* array AP as follows: */ - + /* UPLO = 'U' or 'u' The Upper triangular part of A is */ /* supplied in AP. */ - + /* UPLO = 'L' or 'l' The Lower triangular part of A is */ /* supplied in AP. */ - + /* Unchanged on exit. */ - + /* N - INTEGER. */ /* On entry, N specifies the order of the matrix A. */ /* N must be at least zero. */ /* Unchanged on exit. */ - + /* ALPHA - DOUBLE PRECISION. */ /* On entry, ALPHA specifies the scalar alpha. */ /* Unchanged on exit. */ - + /* X - DOUBLE PRECISION array of dimension at least */ /* ( 1 + ( n - 1 )*abs( INCX ) ). */ /* Before entry, the incremented array X must contain the n */ /* element vector x. */ /* Unchanged on exit. */ - + /* INCX - INTEGER. */ /* On entry, INCX specifies the increment for the Elements of */ /* X. INCX must not be zero. */ /* Unchanged on exit. */ - + /* AP - DOUBLE PRECISION array of DIMENSION at least */ /* ( ( n*( n + 1 ) )/2 ). */ /* Before entry with UPLO = 'U' or 'u', the array AP must */ @@ -97,38 +97,38 @@ int mndspr(const char* uplo, unsigned int n, double alpha, /* and a( 3, 1 ) respectively, and so on. On exit, the array */ /* AP is overwritten by the Lower triangular part of the */ /* updated matrix. */ - - + + /* Level 2 Blas routine. */ - + /* -- Written on 22-October-1986. */ /* Jack Dongarra, Argonne National Lab. */ /* Jeremy Du Croz, Nag Central Office. */ /* Sven Hammarling, Nag Central Office. */ /* Richard Hanson, Sandia National Labs. */ - - + + /* .. Parameters .. */ /* .. Local Scalars .. */ /* .. External Functions .. */ /* .. External Subroutines .. */ /* .. */ /* .. Executable Statements .. */ - + /* Test the input parameters. */ - + /* Parameter adjustments */ --ap; --x; - + /* Function Body */ info = 0; if (! mnlsame(uplo, "U") && ! mnlsame(uplo, "L")) { info = 1; - } + } // else if (n < 0) { // info = 2; - // } + // } else if (incx == 0) { info = 5; } @@ -136,29 +136,29 @@ int mndspr(const char* uplo, unsigned int n, double alpha, mnxerbla("DSPR ", info); return 0; } - + /* Quick return if possible. */ - + if (n == 0 || alpha == 0.) { return 0; } - + /* Set the start point in X if the increment is not unity. */ - + if (incx <= 0) { kx = 1 - (n - 1) * incx; } else if (incx != 1) { kx = 1; } - + /* Start the operations. In this version the Elements of the array AP */ /* are accessed sequentially with one pass through AP. */ - + kk = 1; if (mnlsame(uplo, "U")) { - + /* Form A when Upper triangle is stored in AP. */ - + if (incx == 1) { i__1 = n; for (j = 1; j <= i__1; ++j) { @@ -195,9 +195,9 @@ int mndspr(const char* uplo, unsigned int n, double alpha, } } } else { - + /* Form A when Lower triangle is stored in AP. */ - + if (incx == 1) { i__1 = n; for (j = 1; j <= i__1; ++j) { @@ -234,11 +234,11 @@ int mndspr(const char* uplo, unsigned int n, double alpha, } } } - + return 0; - + /* End of DSPR . */ - + } /* dspr_ */ diff --git a/ThirdParty/RootMinimizers/src/Minuit2/mnlsame.cxx b/ThirdParty/RootMinimizers/src/Minuit2/mnlsame.cxx index 71bc98ba6989f8d16fa4811012bb34e3404ed82e..89c8736e47da7eb5854999bb4ef6852514bfd5fb 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/mnlsame.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/mnlsame.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -22,45 +22,45 @@ namespace ROOT { bool mnlsame(const char* ca, const char* cb) { /* System generated locals */ bool ret_val = false; - + /* Local variables */ // integer inta, intb, zcode; - - + + /* -- LAPACK auxiliary routine (version 2.0) -- */ /* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., */ /* Courant Institute, Argonne National Lab, and Rice University */ /* January 31, 1994 */ - + /* .. Scalar Arguments .. */ /* .. */ - + /* Purpose */ /* ======= */ - + /* LSAME returns .TRUE. if CA is the same letter as CB regardless of */ /* case. */ - + /* Arguments */ /* ========= */ - + /* CA (input) CHARACTER*1 */ /* CB (input) CHARACTER*1 */ /* CA and CB specify the single characters to be compared. */ - + /* ===================================================================== */ - + /* .. Intrinsic Functions .. */ /* .. */ /* .. Local Scalars .. */ /* .. */ /* .. Executable Statements .. */ - + /* Test if the characters are equal */ - + int comp = strcmp(ca, cb); if(comp == 0) ret_val = true; - + return ret_val; } /* lsame_ */ diff --git a/ThirdParty/RootMinimizers/src/Minuit2/mnteigen.cxx b/ThirdParty/RootMinimizers/src/Minuit2/mnteigen.cxx index 23a5802e61590f03be4e796c8e6145aaaf50472b..ff890fc59536abaf2b1acc5e3e97d2d19032a45e 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/mnteigen.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/mnteigen.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -19,43 +19,43 @@ namespace ROOT { namespace Minuit2 { -int mneigen(double* a, unsigned int ndima, unsigned int n, unsigned int mits, +int mneigen(double* a, unsigned int ndima, unsigned int n, unsigned int mits, double* work, double precis) { // compute matrix eignevalues (transaltion from mneig.F of Minuit) - + /* System generated locals */ unsigned int a_dim1, a_offset, i__1, i__2, i__3; double r__1, r__2; - + /* Local variables */ double b, c__, f, h__; unsigned int i__, j, k, l, m = 0; double r__, s; unsigned int i0, i1, j1, m1, n1; double hh, gl, pr, pt; - - + + /* PRECIS is the machine precision EPSMAC */ /* Parameter adjustments */ a_dim1 = ndima; a_offset = 1 + a_dim1 * 1; a -= a_offset; --work; - + /* Function Body */ int ifault = 1; - + i__ = n; i__1 = n; for (i1 = 2; i1 <= i__1; ++i1) { l = i__ - 2; f = a[i__ + (i__ - 1) * a_dim1]; gl = (double)0.; - + if (l < 1) { goto L25; } - + i__2 = l; for (k = 1; k <= i__2; ++k) { /* Computing 2nd power */ @@ -66,23 +66,23 @@ L25: /* Computing 2nd power */ r__1 = f; h__ = gl + r__1 * r__1; - + if (gl > (double)1e-35) { goto L30; } - + work[i__] = (double)0.; work[n + i__] = f; goto L65; L30: ++l; - + gl = sqrt(h__); - + if (f >= (double)0.) { gl = -gl; } - + work[n + i__] = gl; h__ -= f * gl; a[i__ + (i__ - 1) * a_dim1] = f - gl; @@ -95,11 +95,11 @@ L30: for (k = 1; k <= i__3; ++k) { gl += a[j + k * a_dim1] * a[i__ + k * a_dim1]; } - + if (j >= l) { goto L47; } - + j1 = j + 1; i__3 = l; for (k = j1; k <= i__3; ++k) { @@ -117,7 +117,7 @@ L47: work[n + j] = gl; i__3 = j; for (k = 1; k <= i__3; ++k) { - a[j + k * a_dim1] = a[j + k * a_dim1] - f * work[n + k] - gl + a[j + k * a_dim1] = a[j + k * a_dim1] - f * work[n + k] - gl * a[i__ + k * a_dim1]; } } @@ -130,11 +130,11 @@ L65: i__1 = n; for (i__ = 1; i__ <= i__1; ++i__) { l = i__ - 1; - + if (work[i__] == (double)0. || l == 0) { goto L100; } - + i__3 = l; for (j = 1; j <= i__3; ++j) { gl = (double)0.; @@ -150,11 +150,11 @@ L65: L100: work[i__] = a[i__ + i__ * a_dim1]; a[i__ + i__ * a_dim1] = (double)1.; - + if (l == 0) { goto L110; } - + i__2 = l; for (j = 1; j <= i__2; ++j) { a[i__ + j * a_dim1] = (double)0.; @@ -163,8 +163,8 @@ L100: L110: ; } - - + + n1 = n - 1; i__1 = n; for (i__ = 2; i__ <= i__1; ++i__) { @@ -177,42 +177,42 @@ L110: i__1 = n; for (l = 1; l <= i__1; ++l) { j = 0; - h__ = precis * ((r__1 = work[l], fabs(r__1)) + (r__2 = work[n + l], + h__ = precis * ((r__1 = work[l], fabs(r__1)) + (r__2 = work[n + l], fabs(r__2))); - + if (b < h__) { b = h__; } - + i__2 = n; for (m1 = l; m1 <= i__2; ++m1) { m = m1; - + if ((r__1 = work[n + m], fabs(r__1)) <= b) { goto L150; } - + } - + L150: if (m == l) { goto L205; } - + L160: if (j == mits) { return ifault; } - + ++j; pt = (work[l + 1] - work[l]) / (work[n + l] * (double)2.); r__ = sqrt(pt * pt + (double)1.); pr = pt + r__; - + if (pt < (double)0.) { pr = pt - r__; } - + h__ = work[l] - work[n + l] / pr; i__2 = n; for (i__ = l; i__ <= i__2; ++i__) { @@ -230,11 +230,11 @@ L160: --i__; gl = c__ * work[n + i__]; h__ = c__ * pt; - + if (fabs(pt) >= (r__1 = work[n + i__], fabs(r__1))) { goto L180; } - + c__ = pt / work[n + i__]; r__ = sqrt(c__ * c__ + (double)1.); work[n + j] = s * work[n + i__] * r__; @@ -259,11 +259,11 @@ L190: } work[n + l] = s * pt; work[l] = c__ * pt; - + if ((r__1 = work[n + l], fabs(r__1)) > b) { goto L160; } - + L205: work[l] += f; } @@ -274,21 +274,21 @@ L205: i1 = i__ + 1; i__3 = n; for (j = i1; j <= i__3; ++j) { - + if (work[j] >= pt) { goto L220; } - + k = j; pt = work[j]; L220: ; } - + if (k == i__) { goto L240; } - + work[k] = work[i__]; work[i__] = pt; i__3 = n; @@ -301,7 +301,7 @@ L240: ; } ifault = 0; - + return ifault; } /* mneig_ */ diff --git a/ThirdParty/RootMinimizers/src/Minuit2/mntplot.cxx b/ThirdParty/RootMinimizers/src/Minuit2/mntplot.cxx index 9c72b403d9b73b7560ff77a0c8f10cf9d58884ce..e80812dd979538d51bebd0aac9e780f0c470e62b 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/mntplot.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/mntplot.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -47,7 +47,7 @@ void mnplot(double* xpt, double* ypt, char* chpt, int nxypt, int npagwd, int npa bool overpr; char cline[120]; char chsav, chbest; - + /* Function Body */ //*-* Computing MIN maxnx = npagwd-20 < 100 ? npagwd-20 : 100; @@ -174,7 +174,7 @@ L400: } printf(" %s",cline); printf("\n"); - + for (ibk = 1; ibk <= 12; ++ibk) { xvalus[ibk-1] = xmin + double(ibk-1)*10*bwidx; } @@ -184,7 +184,7 @@ L400: printf(" %9.4g", xvalus[ibk-1]); } printf("\n"); - + if (overpr) { char chmess[] = " Overprint character is &"; printf(" ONE COLUMN=%13.7g%s",bwidx,(const char*)chmess); @@ -193,7 +193,7 @@ L400: printf(" ONE COLUMN=%13.7g%s",bwidx,(const char*)chmess); } printf("\n"); - + } /* mnplot_ */ } // namespace Minuit2 diff --git a/ThirdParty/RootMinimizers/src/Minuit2/mnvert.cxx b/ThirdParty/RootMinimizers/src/Minuit2/mnvert.cxx index 56632287d00aaf7f431e09e9405136d269fc3607..bc775c1bbcc8487a86ca5319c81ffd1014ed2d18 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/mnvert.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/mnvert.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -16,28 +16,28 @@ namespace ROOT { namespace Minuit2 { -/** Inverts a symmetric matrix. Matrix is first scaled to have all ones on - the diagonal (equivalent to change of units) but no pivoting is done - since matrix is positive-definite. +/** Inverts a symmetric matrix. Matrix is first scaled to have all ones on + the diagonal (equivalent to change of units) but no pivoting is done + since matrix is positive-definite. */ int mnvert(MnAlgebraicSymMatrix& a) { - + unsigned int nrow = a.Nrow(); MnAlgebraicVector s(nrow); MnAlgebraicVector q(nrow); MnAlgebraicVector pp(nrow); - + for(unsigned int i = 0; i < nrow; i++) { double si = a(i,i); if (si < 0.) return 1; s(i) = 1./std::sqrt(si); } - + for(unsigned int i = 0; i < nrow; i++) for(unsigned int j = i; j < nrow; j++) a(i,j) *= (s(i)*s(j)); - + for(unsigned i = 0; i < nrow; i++) { unsigned int k = i; if(a(k,k) == 0.) return 1; @@ -61,13 +61,13 @@ int mnvert(MnAlgebraicSymMatrix& a) { } for(unsigned int j = 0; j < nrow; j++) for(k = j; k < nrow; k++) - a(j,k) += (pp(j)*q(k)); + a(j,k) += (pp(j)*q(k)); } - + for(unsigned int j = 0; j < nrow; j++) for(unsigned int k = j; k < nrow; k++) - a(j,k) *= (s(j)*s(k)); - + a(j,k) *= (s(j)*s(k)); + return 0; } diff --git a/ThirdParty/RootMinimizers/src/Minuit2/mnxerbla.cxx b/ThirdParty/RootMinimizers/src/Minuit2/mnxerbla.cxx index 2e11ee9345ec1ea580a0c4ecae1e4a16104c2622..3a85f7ce71b280ebbcecf265adb5ca6e81002ab1 100644 --- a/ThirdParty/RootMinimizers/src/Minuit2/mnxerbla.cxx +++ b/ThirdParty/RootMinimizers/src/Minuit2/mnxerbla.cxx @@ -1,5 +1,5 @@ // @(#)root/minuit2:$Id$ -// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 +// Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * @@ -27,7 +27,7 @@ namespace ROOT { int mnxerbla(const char* srname, int info) { /* Format strings */ // static char fmt_9999[] = "(\002 ** On entry to \002,a6,\002 Parameter nu\// mber \002,i2,\002 had \002,\002an illegal Value\002)"; - + /* -- LAPACK auxiliary routine (version 3.0) -- */ /* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., */ /* Courant Institute, Argonne National Lab, and Rice University */ @@ -59,11 +59,11 @@ int mnxerbla(const char* srname, int info) { /* ===================================================================== */ /* .. Executable Statements .. */ - + std::cout<<" ** On entry to "<<srname<<" Parameter number "<<info<<" had an illegal Value"<<std::endl; - + /* End of XERBLA */ - + return 0; } /* xerbla_ */ diff --git a/dev-tools/code-tools/update_minimizers.py b/dev-tools/code-tools/update_minimizers.py index 7d4e70d1f0056df6fed219cc8d337976ddf18365..0d4571364b77f80ffb4f8e43c48ceedaedad76e7 100644 --- a/dev-tools/code-tools/update_minimizers.py +++ b/dev-tools/code-tools/update_minimizers.py @@ -5,8 +5,8 @@ from ROOT to our source tree. import os import filecmp -ROOT_SOURCE = "/home/pospelov/software/root/root_v5.34.20.source" -BORNAGAIN_SOURCE = "/home/pospelov/development/BornAgain/source/ThirdParty/RootMinimizers" +ROOT_SOURCE = "/home/pospelov/software/root/root-6.04.02.source" +BORNAGAIN_SOURCE = "/home/pospelov/development/BornAgain/BornAgain/ThirdParty/RootMinimizers" @@ -65,7 +65,7 @@ def build_difference_map(): print ba_file, found_files[0] #os.system(cmd) else: - print ba_file, len(found_files) + print ba_file, len(found_files), found_files if __name__ == '__main__':