Skip to content
Snippets Groups Projects
Commit 9338be00 authored by Pospelov, Gennady's avatar Pospelov, Gennady
Browse files

Few functional tests for minimizers.

parent 5a7fa427
No related branches found
No related tags found
No related merge requests found
Showing
with 239 additions and 602 deletions
//// ************************************************************************** //
////
//// BornAgain: simulate and fit scattering at grazing incidence
////
////! @file FitKernel/inc/ROOTGSLSimAnMinimizer.h
////! @brief Defines patched class ROOTGSLSimAnMinimizer.
////!
//// ************************************************************************** //
//#ifndef ROOTGSLSIMANMINIMIZER_H
//#define ROOTGSLSIMANMINIMIZER_H
//// @(#)root/mathmore:$Id: GSLSimAnMinimizer.h 32583 2010-03-12 09:57:42Z moneta $
//// Author: L. Moneta Wed Dec 20 17:16:32 2006
///**********************************************************************
// * *
// * Copyright (c) 2006 LCG ROOT Math Team, CERN/PH-SFT *
// * *
// * This library is free software; you can redistribute it and/or *
// * modify it under the terms of the GNU General Public License *
// * as published by the Free Software Foundation; either version 2 *
// * of the License, or (at your option) any later version. *
// * *
// * This library is distributed in the hope that it will be useful, *
// * but WITHOUT ANY WARRANTY; without even the implied warranty of *
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
// * General Public License for more details. *
// * *
// * You should have received a copy of the GNU General Public License *
// * along with this library (see file COPYING); if not, write *
// * to the Free Software Foundation, Inc., 59 Temple Place, Suite *
// * 330, Boston, MA 02111-1307 USA, or contact the author. *
// * *
// **********************************************************************/
//// Header file for class GSLSimAnMinimizer
//#ifndef ROOT_Math_BasicMinimizer
//#include "Math/BasicMinimizer.h"
//#endif
//#ifndef ROOT_Math_IFunctionfwd
//#include "Math/IFunctionfwd.h"
//#endif
//#ifndef ROOT_Math_IParamFunctionfwd
//#include "Math/IParamFunctionfwd.h"
//#endif
//#ifndef ROOT_Math_GSLSimAnnealing
//#include "Math/GSLSimAnnealing.h"
//#endif
//namespace ROOT {
// namespace Patch {
// //typedef ROOT::Math::MinimTransformFunction MinimTransformFunction;
// using ROOT::Math::kDefault;
// using ROOT::Math::kLowBound;
// using ROOT::Math::kUpBound;
// using ROOT::Math::kBounds;
// using ROOT::Math::kFix;
// using ROOT::Math::MultiNumGradFunction;
// using ROOT::Math::MinimTransformFunction;
//// class MinimTransformFunction;
////_____________________________________________________________________________________
///**
// GSLSimAnMinimizer class for minimization using simulated annealing
// using the algorithm from
// <A HREF="http://www.gnu.org/software/gsl/manual/html_node/Simulated-Annealing.html">
// GSL</A>.
// It implements the ROOT::Minimizer interface and
// a plug-in (name "GSLSimAn") exists to instantiate this class via the plug-in manager
// @ingroup MultiMin
//*/
//class GSLSimAnMinimizer : public ROOT::Math::Minimizer {
// public:
// /**
// Default constructor
// */
// GSLSimAnMinimizer (int type = 0);
// /**
// Destructor (no operations)
// */
// ~GSLSimAnMinimizer ();
// private:
// // usually copying is non trivial, so we make this unaccessible
// /**
// Copy constructor
// */
// GSLSimAnMinimizer(const GSLSimAnMinimizer& ) : ROOT::Math::Minimizer() {}
// /**
// Assignment operator
// */
// GSLSimAnMinimizer& operator = (const GSLSimAnMinimizer& rhs) {
// if (this ==& rhs) return *this; // time saving self-test
// return *this;
// }
// public:
// /// set the function to minimize
// virtual void SetFunction(const ROOT::Math::IMultiGenFunction& func);
// /// set gradient the function to minimize
// 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 fixed variable (override if minimizer supports them )
// virtual bool SetFixedVariable(unsigned int /* ivar */, const std::string& /* name */, double /* val */);
// /// 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 );
// /// 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 */);
// /// 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 the existing parameters)
// virtual bool SetVariableValues(const double * x);
// /// method to perform the minimization
// virtual bool Minimize();
// /// return minimum function value
// virtual double MinValue() const { return fMinVal; }
// /// return expected distance reached from the minimum
// virtual double Edm() const { return 0; } // not impl. }
// /// return pointer to X values at the minimum
// virtual const double * X() const { return& fValues.front(); }
// /// return pointer to gradient values at the minimum
// virtual const double * MinGradient() const { return 0; } // not impl.
// /// number of function calls to reach the minimum
// virtual unsigned int NCalls() const { return 0; } // not yet ipl.
// /// 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 fDim; }
// /// minimizer provides error and error matrix
// virtual bool ProvidesError() const { return false; }
// /// return errors at the minimum
// virtual const double * Errors() const { return 0; }
// /** 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; }
// /// return reference to the objective function
// ///virtual const ROOT::Math::IGenFunction& Function() const;
// ROOT::Math::GSLSimAnnealing& getSolver() { return fSolver; }
// //void SetAnnealingParameters(const GSLSimAnParams& newpars) { fSolver.Params()
// protected:
// private:
// unsigned int fDim; // dimension of the function to be minimized
// bool fOwnFunc; // flag to indicate if objective function is managed
// ROOT::Math::GSLSimAnnealing fSolver;
// const ROOT::Math::IMultiGenFunction * fObjFunc;
// double fMinVal; // minimum values
// mutable 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 Math
//} // end namespace ROOT
//#endif // ROOTGSLSIMANMINIMIZER_H
...@@ -17,7 +17,6 @@ ...@@ -17,7 +17,6 @@
#define ROOTMINIMIZERHELPER_H #define ROOTMINIMIZERHELPER_H
#include "ROOTMinimizer.h" #include "ROOTMinimizer.h"
#include "PatchedGSLSimAnMinimizer.h"
//! @class ROOTMinimizerHelper //! @class ROOTMinimizerHelper
......
...@@ -17,8 +17,7 @@ ...@@ -17,8 +17,7 @@
#define ROOTSIMANMINIMIZER_H #define ROOTSIMANMINIMIZER_H
#include "ROOTMinimizer.h" #include "ROOTMinimizer.h"
//#include "PatchedGSLSimAnMinimizer.h" #include "Math/PatchedGSLSimAnMinimizer.h"
#include "Math/GSLSimAnMinimizer.h"
//! @class ROOTSimAnMinimizer //! @class ROOTSimAnMinimizer
...@@ -34,7 +33,6 @@ public: ...@@ -34,7 +33,6 @@ public:
protected: protected:
virtual void propagateOptions(); virtual void propagateOptions();
// ROOT::Patch::GSLSimAnMinimizer *m_siman_minimizer;
ROOT::Math::GSLSimAnMinimizer *m_siman_minimizer; ROOT::Math::GSLSimAnMinimizer *m_siman_minimizer;
}; };
......
//// ************************************************************************** //
////
//// BornAgain: simulate and fit scattering at grazing incidence
////
////! @file FitKernel/src/ROOTGSLSimAnMinimizer.cpp
////! @brief Implements patched class ROOTGSLSimAnMinimizer.
////!
//// ************************************************************************** //
//#include "PatchedGSLSimAnMinimizer.h"
////#include "Math/GSLSimAnMinimizer.h"
//#include "Math/WrappedParamFunction.h"
//#include "Math/Error.h"
//#include "Math/MinimTransformFunction.h"
//#include "Math/MultiNumGradFunction.h" // needed to use transformation function
//#include <iostream>
//#include <cassert>
//namespace ROOT {
// namespace Patch {
//// GSLSimAnMinimizer implementation
//GSLSimAnMinimizer::GSLSimAnMinimizer( int /* ROOT::Math::EGSLSimAnMinimizerType type */ ) :
// fDim(0),
// fOwnFunc(false),
// fObjFunc(0),
// fMinVal(0)
//{
// // Constructor implementation : create GSLMultiFit wrapper object
// fValues.reserve(10);
// fNames.reserve(10);
// fSteps.reserve(10);
// SetMaxIterations(100);
// SetPrintLevel(0);
//}
//GSLSimAnMinimizer::~GSLSimAnMinimizer () {
// if ( fOwnFunc && fObjFunc) delete fObjFunc;
//}
//bool GSLSimAnMinimizer::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);
// fNames.push_back(name);
// // step is the simmulated annealing scale
// fSteps.push_back( step );
// fVarTypes.push_back(kDefault);
// }
// else {
// fValues[ivar] = val;
// fNames[ivar] = name;
// 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);
// }
// return true;
//}
//bool GSLSimAnMinimizer::SetLowerLimitedVariable(unsigned int ivar, const std::string& name, double val, double step, double lower ) {
// bool ret = SetVariable(ivar, name, val, step);
// if (!ret) return false;
// fBounds[ivar] = std::make_pair( lower, lower);
// fVarTypes[ivar] = kLowBound;
// return true;
//}
//bool GSLSimAnMinimizer::SetUpperLimitedVariable(unsigned int ivar, const std::string& name, double val, double step, double upper) {
// bool ret = SetVariable(ivar, name, val, step);
// if (!ret) return false;
// fBounds[ivar] = std::make_pair( upper, upper);
// fVarTypes[ivar] = kUpBound;
// return true;
//}
//bool GSLSimAnMinimizer::SetLimitedVariable(unsigned int ivar, const std::string& name, double val, double step, double lower, double upper ) {
// bool ret = SetVariable(ivar, name, val, step);
// if (!ret) return false;
// fBounds[ivar] = std::make_pair( lower, upper);
// fVarTypes[ivar] = kBounds;
// return true;
//}
//bool GSLSimAnMinimizer::SetFixedVariable(unsigned int ivar, const std::string& name, double val) {
// /// set fixed variable (override if minimizer supports them )
// // use zero step size
// bool ret = SetVariable(ivar, name, val, 0.);
// if (!ret) return false;
// fVarTypes[ivar] = kFix;
// return true;
//}
//bool GSLSimAnMinimizer::SetVariableValue(unsigned int ivar, double val) {
// // set variable value in minimizer
// // no transformation implemented - so far
// if (ivar > fValues.size() ) return false;
// fValues[ivar] = val;
// return true;
//}
//bool GSLSimAnMinimizer::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;
//}
//void GSLSimAnMinimizer::SetFunction(const ROOT::Math::IMultiGenFunction& func) {
// // set the function to minimize
// // keep pointers to the chi2 function
// fObjFunc =& func;
// fDim = func.NDim();
//}
//void GSLSimAnMinimizer::SetFunction(const ROOT::Math::IMultiGradFunction& func ) {
// // set the function to minimize
// // use the other methods
// SetFunction( static_cast<const ROOT::Math::IMultiGenFunction& >(func) );
//}
//bool GSLSimAnMinimizer::Minimize() {
// // set initial parameters of the minimizer
// int debugLevel = PrintLevel();
// if (debugLevel >=1 ) std::cout <<"Minimize using GSLSimAnMinimizer " << std::endl;
// // adapt the steps (use largers)
// for (unsigned int i = 0; i < fSteps.size() ; ++i)
// fSteps[i] *= 10;
// // vector of internal values (copied by default)
// std::vector<double> xvar (fValues );
// std::vector<double> steps (fSteps);
// // check if a transformation is needed
// bool doTransform = (fBounds.size() > 0);
// unsigned int ivar = 0;
// while (!doTransform && ivar < fVarTypes.size() ) {
// doTransform = (fVarTypes[ivar++] != kDefault );
// }
// // if needed do transformation and wrap objective function in a new transformation function
// // and transform from external variables (and steps) to internals one
// MinimTransformFunction * trFunc = 0;
// if (doTransform) {
// // since objective function is gradient build a gradient function for the transformation
// // although gradient is not needed
// trFunc = new MinimTransformFunction ( new MultiNumGradFunction( *fObjFunc), fVarTypes, fValues, fBounds );
// trFunc->InvTransformation(&fValues.front(), &xvar[0]);
// // need to transform also the steps
// trFunc->InvStepTransformation(&fValues.front(), &fSteps.front(), &steps[0]);
// xvar.resize( trFunc->NDim() );
// steps.resize( trFunc->NDim() );
// fObjFunc = trFunc;
// fOwnFunc = true; // flag to indicate we need to delete the function
// }
// assert (xvar.size() == steps.size() );
// // output vector
// std::vector<double> xmin(xvar.size() );
// int iret = fSolver.Solve(*fObjFunc, &xvar.front(), &steps.front(), &xmin[0], (debugLevel > 1) );
// fMinVal = (*fObjFunc)(&xmin.front() );
// // get the result (transform if needed)
// if (trFunc != 0) {
// const double * xtrans = trFunc->Transformation(&xmin.front());
// assert(fValues.size() == trFunc->NTot() );
// assert( trFunc->NTot() == NDim() );
// std::copy(xtrans, xtrans + trFunc->NTot(), fValues.begin() );
// }
// else {
// // case of no transformation applied
// assert( fValues.size() == xmin.size() );
// std::copy(xmin.begin(), xmin.end(), fValues.begin() );
// }
// if (debugLevel >=1 ) {
// if (iret == 0)
// std::cout << "GSLSimAnMinimizer: Minimum Found" << std::endl;
// else
// std::cout << "GSLSimAnMinimizer: Error in solving" << std::endl;
// int pr = (int)std::cout.precision(18);
// std::cout << "FVAL = " << fMinVal << std::endl;
// std::cout.precision(pr);
// for (unsigned int i = 0; i < fDim; ++i)
// std::cout << fNames[i] << "\t = " << fValues[i] << std::endl;
// }
// return ( iret == 0) ? true : false;
//}
// } // end namespace Patch
//} // end namespace ROOT
...@@ -14,7 +14,6 @@ ...@@ -14,7 +14,6 @@
// ************************************************************************** // // ************************************************************************** //
#include "ROOTMinimizerHelper.h" #include "ROOTMinimizerHelper.h"
#include "PatchedGSLSimAnMinimizer.h"
#include "Utils.h" #include "Utils.h"
#include <boost/lexical_cast.hpp> #include <boost/lexical_cast.hpp>
#include "Math/GenAlgoOptions.h" #include "Math/GenAlgoOptions.h"
......
...@@ -38,15 +38,12 @@ void ROOTSimAnMinimizer::propagateOptions() ...@@ -38,15 +38,12 @@ void ROOTSimAnMinimizer::propagateOptions()
{ {
ROOTMinimizer::propagateOptions(); ROOTMinimizer::propagateOptions();
// FIXME ROOT::Math::GSLSimAnParams& pars = m_siman_minimizer->getSolver().Params();
throw Exceptions::NotImplementedException("FIXME ASUP"); m_options.getValue("ntries", pars.n_tries);
m_options.getValue("niters_fixed_t", pars.iters_fixed_T);
// ROOT::Math::GSLSimAnParams& pars = m_siman_minimizer->getSolver().Params(); m_options.getValue("step_size", pars.step_size);
// m_options.getValue("ntries", pars.n_tries); m_options.getValue("k", pars.k);
// m_options.getValue("niters_fixed_t", pars.iters_fixed_T); m_options.getValue("t_initial", pars.t_initial);
// m_options.getValue("step_size", pars.step_size); m_options.getValue("mu", pars.mu);
// m_options.getValue("k", pars.k); m_options.getValue("t_min", pars.t_min);
// m_options.getValue("t_initial", pars.t_initial);
// m_options.getValue("mu", pars.mu);
// m_options.getValue("t_min", pars.t_min);
} }
...@@ -3,10 +3,15 @@ ...@@ -3,10 +3,15 @@
############################################################################ ############################################################################
set(list_of_tests set(list_of_tests
"testfit01.py" "testfit_UsingBuilder.py"
"testfit02.py" "testfit_Genetic.py"
"testfit_GSLLMA.py"
"testfit_GSLMultiMin.py"
"testfit_GSLSimAn.py"
"testfit_Minuit2.py"
) )
foreach(_test ${list_of_tests}) foreach(_test ${list_of_tests})
#add_test(${_test} ${PYTHON_EXECUTABLE} "${CMAKE_CURRENT_SOURCE_DIR}/${_test}") #add_test(${_test} ${PYTHON_EXECUTABLE} "${CMAKE_CURRENT_SOURCE_DIR}/${_test}")
add_test(${_test} ${PYTHON_EXECUTABLE} "${CMAKE_BINARY_DIR}/Tests/FunctionalTests/TestPyFit/${_test}") add_test(${_test} ${PYTHON_EXECUTABLE} "${CMAKE_BINARY_DIR}/Tests/FunctionalTests/TestPyFit/${_test}")
......
...@@ -9,6 +9,13 @@ cmake; make check ...@@ -9,6 +9,13 @@ cmake; make check
--- List of tests --- --- List of tests ---
testfit01.py - Two parameter fit using variety of minimizers. Geometry: cylinders in the air.
testfit02.py - Fitting using sample builder
testfit_Genetic.py Test of Genetic minimizer with default settings
testfit_GSLLMA.py Test of GSL LMA minimizer with default settings
testfit_GSLMultiMin.py Test of various GSL gradient descent minimizers
testfit_GSLSimAn.py Test of GSL Simmulated Annealing minimizer
testfit_Minuit2.py Test of Minuit2 minimizer
testfit_UsingBuilder.py Fitting via sample builder
import sys
import os
#sys.path.append(os.path.abspath(
# os.path.join(os.path.split(__file__)[0],
# '..', '..', '..', 'lib')))
from libBornAgainCore import *
from libBornAgainFit import *
CYLINDER_HEIGHT = 5.0
CYLINDER_RADIUS = 5.0
def getReferenceParameters():
return [CYLINDER_HEIGHT, CYLINDER_RADIUS]
def get_sample():
"""
Returns test sample
"""
global CYLINDER_HEIGHT
global CYLINDER_RADIUS
cylinder_ff = FormFactorCylinder(CYLINDER_HEIGHT, CYLINDER_RADIUS)
mParticle = HomogeneousMaterial("Particle", 6e-4, 2e-8)
cylinder = Particle(mParticle, cylinder_ff)
particle_layout = ParticleLayout()
particle_layout.addParticle(cylinder)
mAmbience = HomogeneousMaterial("Air", 0.0, 0.0)
air_layer = Layer(mAmbience)
air_layer.setLayout(particle_layout)
multi_layer = MultiLayer()
multi_layer.addLayer(air_layer)
return multi_layer
def get_simulation():
"""
Returns test simulation
"""
simulation = Simulation()
simulation.setDetectorParameters(50, 0.0*degree, 2.0*degree, 50, 0.0*degree, 2.0*degree)
simulation.setBeamParameters(1.0*angstrom, -0.2*degree, 0.0*degree)
simulation.setBeamIntensity(1e10)
simulation.setSample(get_sample())
return simulation
def get_real_data():
"""
Returns 'real' data
"""
simulation = get_simulation()
simulation.runSimulation()
return simulation.getIntensityData()
def get_fit_suite(minimizer, algorithm):
"""
Creates FitSuite fully ready for minimization
"""
fit_suite = FitSuite()
fit_suite.addFitParameter("*height", 4.*nanometer, 0.04*nanometer, AttLimits.limited(2.0, 8.0))
fit_suite.addFitParameter("*radius", 6.*nanometer, 0.06*nanometer, AttLimits.limited(2.0, 8.0))
fit_suite.addSimulationAndRealData(get_simulation(), get_real_data())
fit_suite.setMinimizer(MinimizerFactory.createMinimizer(minimizer, algorithm))
return fit_suite
def print_fit_results(fit_suite):
fitpars = fit_suite.getFitParameters()
refpars = getReferenceParameters()
print "-"*30
print "RealTime :", fit_suite.getMinimizer().getMinimizerName(), fit_suite.getMinimizer().getAlgorithmName()
print "RealTime : {0:.3f} sec".format(fit_suite.getRunTime())
print "NCalls : {0:<5d}".format(fit_suite.getNCalls())
for i in range(0, fitpars.size()):
print 'par{0:2d} : {1:.4f} ({2:.3g}) '.format(i, fitpars[0].getValue(), fitpars[i].getValue() - refpars[i])
def run_fit_suite(minimizer, algorithm=""):
fit_suite = get_fit_suite(minimizer, algorithm)
fit_suite.initPrint(100 )
fit_suite.runFit()
print_fit_results(fit_suite)
return fit_suite.getFitParameters().getValues(), getReferenceParameters()
# functional test: two parameter fit using variety of minimizers
#
# In this test we are using simple geometry: cylinders without interference in
# air layer with two parameters (radius and height of cylinders), describing
# the sample. Our "real" data is 2D intensity map obtained from the simulation of
# the same geometry with fixed values height = 5nm and radius = 5nm.
# Then we run our minimization consequently using different minimization engines,
# with height=4nm, radius=6nm as starting fit parameter values.
import sys
import os
import numpy
import time
sys.path.append(os.path.abspath(
os.path.join(os.path.split(__file__)[0],
'..', '..', '..', 'lib')))
from libBornAgainCore import *
from libBornAgainFit import *
# sample parameters we are going to find
cylinder_height = 5*nanometer
cylinder_radius = 5*nanometer
# minimizer name and type of minimization algorithm
Minimizers = [
#("Minuit2", "Migrad"),
#("Minuit2", "Fumili"),
#("GSLMultiMin", "BFGS"),
#("GSLMultiMin", "SteepestDescent"),
("GSLLMA", ""),
# ("GSLSimAn","")
]
# -----------------------------------------------------------------------------
# run several minimization rounds using different minimizers
# -----------------------------------------------------------------------------
def runTest():
#print "**********************************************************************"
#print "* Starting TestFit01 *"
#print "**********************************************************************"
nTest=0
status = "OK"
for m in Minimizers:
minimizer_name = m[0]
minimizer_algorithm = m[1]
print "Minimizer {0:-2d} {1:}({2:})".format(nTest, minimizer_name, minimizer_algorithm)
result_ok = run_fitting(minimizer_name, minimizer_algorithm)
nTest+=1
if not result_ok: status = "FAILED"
return "TestFit01", "Two parameters fit using variety of minimizers.", status
# -----------------------------------------------------------------------------
# run fitting specified minimizer
# -----------------------------------------------------------------------------
def run_fitting(minimizer_name, minimizer_algorithm):
sample = buildSample()
simulation = createSimulation()
simulation.setSample(sample)
# creating real data, which is simply results of our simulation with default values
simulation.runSimulation()
real_data = simulation.getIntensityData()
# setting fit suite
fitSuite = FitSuite()
fitSuite.setMinimizer( MinimizerFactory.createMinimizer(minimizer_name, minimizer_algorithm) )
fitSuite.addFitParameter("*height", 4.*nanometer, 0.04*nanometer, AttLimits.lowerLimited(0.01) )
fitSuite.addFitParameter("*radius", 6.*nanometer, 0.06*nanometer, AttLimits.lowerLimited(0.01) )
fitSuite.addSimulationAndRealData(simulation, real_data)
# run fit
start_time = time.time()
fitSuite.runFit()
real_time = time.time() - start_time
height_found = fitSuite.getMinimizer().getValueOfVariableAtMinimum(0)
height_diff = abs(height_found - cylinder_height)/cylinder_height
radius_found = fitSuite.getMinimizer().getValueOfVariableAtMinimum(1)
radius_diff = abs(radius_found - cylinder_radius)/cylinder_radius
print " RealTime : {0:.3f} sec".format(real_time)
print " NCalls : {0:<5d}".format(fitSuite.getNCalls())
print ' par1 : {0:.4f} ({1:.3g}) '.format(height_found, height_diff)
print ' par2 : {0:.4f} ({1:.3g}) '.format(radius_found, radius_diff)
diff = 1.0e-02
isSuccess = True
if( (height_diff > diff) or (radius_diff > diff) ) : isSuccess=False
return isSuccess
# -----------------------------------------------------------------------------
# create cylinders in the air
# -----------------------------------------------------------------------------
def buildSample():
cylinder_ff = FormFactorCylinder(cylinder_height, cylinder_radius)
mParticle = HomogeneousMaterial("Particle", 6e-4, 2e-8 )
cylinder = Particle(mParticle, cylinder_ff)
interference = InterferenceFunctionNone()
particle_layout = ParticleLayout()
particle_layout.addParticle(cylinder)
particle_layout.addInterferenceFunction(interference)
mAmbience = HomogeneousMaterial("Air", 0.0, 0.0 )
air_layer = Layer(mAmbience)
air_layer.setLayout(particle_layout)
multi_layer = MultiLayer()
multi_layer.addLayer(air_layer)
return multi_layer
def createSimulation():
simulation = Simulation();
simulation.setDetectorParameters(100, 0.0*degree, 2.0*degree,100 , 0.0*degree, 2.0*degree);
simulation.setBeamParameters(1.0*angstrom, -0.2*degree, 0.0*degree);
simulation.setBeamIntensity(1e10);
return simulation
#-------------------------------------------------------------
# main()
#-------------------------------------------------------------
if __name__ == '__main__':
name,description,status = runTest()
print name,description,status
if("FAILED" in status) : exit(1)
import sys
import os
import fitting_utils
import unittest
sys.path.append(os.path.abspath(
os.path.join(os.path.split(__file__)[0],
'..', '..', '..', 'lib')))
from libBornAgainCore import *
from libBornAgainFit import *
class MinimizersTest_GSLLMA(unittest.TestCase):
def test_GSLLMA(self):
fitpars, refpars = fitting_utils.run_fit_suite("GSLLMA")
for i in range(0, len(fitpars)):
self.assertAlmostEqual(fitpars[i], refpars[i], delta=1e-3)
if __name__ == '__main__':
unittest.main()
\ No newline at end of file
import sys
import os
import fitting_utils
import unittest
sys.path.append(os.path.abspath(
os.path.join(os.path.split(__file__)[0],
'..', '..', '..', 'lib')))
from libBornAgainCore import *
from libBornAgainFit import *
class MinimizersTest_GSLMultiMin(unittest.TestCase):
def test_GSLMultiMin_BFGS(self):
fitpars, refpars = fitting_utils.run_fit_suite("GSLMultiMin", "BFGS")
for i in range(0, len(fitpars)):
self.assertAlmostEqual(fitpars[i], refpars[i], delta=1e-3)
def test_GSLMultiMin_SteepestDescent(self):
fitpars, refpars = fitting_utils.run_fit_suite("GSLMultiMin", "SteepestDescent")
for i in range(0, len(fitpars)):
self.assertAlmostEqual(fitpars[i], refpars[i], delta=1e-3)
if __name__ == '__main__':
unittest.main()
\ No newline at end of file
import sys
import os
import fitting_utils
import unittest
sys.path.append(os.path.abspath(
os.path.join(os.path.split(__file__)[0],
'..', '..', '..', 'lib')))
from libBornAgainCore import *
from libBornAgainFit import *
class MinimizersTest_GSLSimAn(unittest.TestCase):
def test_GSLSimAn(self):
fitpars, refpars = fitting_utils.run_fit_suite("GSLSimAn")
for i in range(0, len(fitpars)):
self.assertAlmostEqual(fitpars[i], refpars[i], delta=0.2)
if __name__ == '__main__':
unittest.main()
import sys
import os
import fitting_utils
import unittest
sys.path.append(os.path.abspath(
os.path.join(os.path.split(__file__)[0],
'..', '..', '..', 'lib')))
from libBornAgainCore import *
from libBornAgainFit import *
class MinimizersTest_Genetic(unittest.TestCase):
def test_Genetic(self):
fitpars, refpars = fitting_utils.run_fit_suite("Genetic")
for i in range(0, len(fitpars)):
self.assertAlmostEqual(fitpars[i], refpars[i], delta=1e-3)
if __name__ == '__main__':
unittest.main()
\ No newline at end of file
import sys
import os
import fitting_utils
import unittest
sys.path.append(os.path.abspath(
os.path.join(os.path.split(__file__)[0],
'..', '..', '..', 'lib')))
from libBornAgainCore import *
from libBornAgainFit import *
class MinimizersTest_Minuit2(unittest.TestCase):
def test_minuit2_migrad(self):
fitpars, refpars = fitting_utils.run_fit_suite("Minuit2", "Migrad")
for i in range(0, len(fitpars)):
self.assertAlmostEqual(fitpars[i], refpars[i], delta=1e-3)
def test_minuit2_fumili(self):
fitpars, refpars = fitting_utils.run_fit_suite("Minuit2", "Fumili")
for i in range(0, len(fitpars)):
self.assertAlmostEqual(fitpars[i], refpars[i], delta=1e-3)
if __name__ == '__main__':
unittest.main()
...@@ -107,6 +107,8 @@ public: ...@@ -107,6 +107,8 @@ public:
//number of calls //number of calls
unsigned int NCalls() const; unsigned int NCalls() const;
ROOT::Math::GSLSimAnnealing& getSolver() { return fSolver; }
protected: protected:
......
...@@ -10,7 +10,7 @@ ...@@ -10,7 +10,7 @@
// Implementation file for class GSLSimAnMinimizer // Implementation file for class GSLSimAnMinimizer
#include "Math/GSLSimAnMinimizer.h" #include "Math/PatchedGSLSimAnMinimizer.h"
#include "Math/WrappedParamFunction.h" #include "Math/WrappedParamFunction.h"
#include "Math/Error.h" #include "Math/Error.h"
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment