Path: blob/master/modules/core/src/downhill_simplex.cpp
16337 views
/*M///////////////////////////////////////////////////////////////////////////////////////1//2// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.3//4// By downloading, copying, installing or using the software you agree to this license.5// If you do not agree to this license, do not download, install,6// copy or use the software.7//8//9// License Agreement10// For Open Source Computer Vision Library11//12// Copyright (C) 2013, OpenCV Foundation, all rights reserved.13// Third party copyrights are property of their respective owners.14//15// Redistribution and use in source and binary forms, with or without modification,16// are permitted provided that the following conditions are met:17//18// * Redistribution's of source code must retain the above copyright notice,19// this list of conditions and the following disclaimer.20//21// * Redistribution's in binary form must reproduce the above copyright notice,22// this list of conditions and the following disclaimer in the documentation23// and/or other materials provided with the distribution.24//25// * The name of the copyright holders may not be used to endorse or promote products26// derived from this software without specific prior written permission.27//28// This software is provided by the copyright holders and contributors "as is" and29// any express or implied warranties, including, but not limited to, the implied30// warranties of merchantability and fitness for a particular purpose are disclaimed.31// In no event shall the OpenCV Foundation or contributors be liable for any direct,32// indirect, incidental, special, exemplary, or consequential damages33// (including, but not limited to, procurement of substitute goods or services;34// loss of use, data, or profits; or business interruption) however caused35// and on any theory of liability, whether in contract, strict liability,36// or tort (including negligence or otherwise) arising in any way out of37// the use of this software, even if advised of the possibility of such damage.38//39//M*/40#include "precomp.hpp"4142#if 043#define dprintf(x) printf x44#define print_matrix(x) print(x)45#else46#define dprintf(x)47#define print_matrix(x)48#endif4950/*5152****Error Message********************************************************************************************************************5354Downhill Simplex method in OpenCV dev 3.0.0 getting this error:5556OpenCV Error: Assertion failed (dims <= 2 && data && (unsigned)i0 < (unsigned)(s ize.p[0] * size.p[1])57&& elemSize() == (((((DataType<_Tp>::type) & ((512 - 1) << 3)) >> 3) + 1) << ((((sizeof(size_t)/4+1)16384|0x3a50)58>> ((DataType<_Tp>::typ e) & ((1 << 3) - 1))2) & 3))) in Mat::at,59file C:\builds\master_PackSlave-w in32-vc12-shared\opencv\modules\core\include\opencv2/core/mat.inl.hpp, line 8936061****Problem and Possible Fix*********************************************************************************************************6263DownhillSolverImpl::innerDownhillSimplex something looks broken here:64Mat_<double> coord_sum(1,ndim,0.0),buf(1,ndim,0.0),y(1,ndim,0.0);65fcount = 0;66for(i=0;i<ndim+1;++i)67{68y(i) = f->calc(p[i]);69}7071y has only ndim elements, while the loop goes over ndim+17273Edited the following for possible fix:7475Replaced y(1,ndim,0.0) ------> y(1,ndim+1,0.0)7677***********************************************************************************************************************************7879The code below was used in tesing the source code.80Created by @SareeAlnaghy8182#include <iostream>83#include <cstdlib>84#include <cmath>85#include <algorithm>86#include <opencv2\optim\optim.hpp>8788using namespace std;89using namespace cv;9091void test(Ptr<optim::DownhillSolver> MinProblemSolver, Ptr<optim::MinProblemSolver::Function> ptr_F, Mat &P, Mat &step)92{93try{9495MinProblemSolver->setFunction(ptr_F);96MinProblemSolver->setInitStep(step);97double res = MinProblemSolver->minimize(P);9899cout << "res " << res << endl;100}101catch (exception e)102{103cerr << "Error:: " << e.what() << endl;104}105}106107int main()108{109110class DistanceToLines :public optim::MinProblemSolver::Function {111public:112double calc(const double* x)const{113114return x[0] * x[0] + x[1] * x[1];115116}117};118119Mat P = (Mat_<double>(1, 2) << 1.0, 1.0);120Mat step = (Mat_<double>(2, 1) << -0.5, 0.5);121122Ptr<optim::MinProblemSolver::Function> ptr_F(new DistanceToLines());123Ptr<optim::DownhillSolver> MinProblemSolver = optim::createDownhillSolver();124125test(MinProblemSolver, ptr_F, P, step);126127system("pause");128return 0;129}130131****Suggestion for improving Simplex implementation***************************************************************************************132133Currently the downhilll simplex method outputs the function value that is minimized. It should also return the coordinate points where the134function is minimized. This is very useful in many applications such as using back projection methods to find a point of intersection of135multiple lines in three dimensions as not all lines intersect in three dimensions.136137*/138139namespace cv140{141142class DownhillSolverImpl CV_FINAL : public DownhillSolver143{144public:145DownhillSolverImpl()146{147_Function=Ptr<Function>();148_step=Mat_<double>();149}150151void getInitStep(OutputArray step) const CV_OVERRIDE { _step.copyTo(step); }152void setInitStep(InputArray step) CV_OVERRIDE153{154// set dimensionality and make a deep copy of step155Mat m = step.getMat();156dprintf(("m.cols=%d\nm.rows=%d\n", m.cols, m.rows));157if( m.rows == 1 )158m.copyTo(_step);159else160transpose(m, _step);161}162163Ptr<MinProblemSolver::Function> getFunction() const CV_OVERRIDE { return _Function; }164165void setFunction(const Ptr<Function>& f) CV_OVERRIDE { _Function=f; }166167TermCriteria getTermCriteria() const CV_OVERRIDE { return _termcrit; }168169void setTermCriteria( const TermCriteria& termcrit ) CV_OVERRIDE170{171CV_Assert( termcrit.type == (TermCriteria::MAX_ITER + TermCriteria::EPS) &&172termcrit.epsilon > 0 &&173termcrit.maxCount > 0 );174_termcrit=termcrit;175}176177double minimize( InputOutputArray x_ ) CV_OVERRIDE178{179dprintf(("hi from minimize\n"));180CV_Assert( !_Function.empty() );181CV_Assert( std::min(_step.cols, _step.rows) == 1 &&182std::max(_step.cols, _step.rows) >= 2 &&183_step.type() == CV_64FC1 );184dprintf(("termcrit:\n\ttype: %d\n\tmaxCount: %d\n\tEPS: %g\n",_termcrit.type,_termcrit.maxCount,_termcrit.epsilon));185dprintf(("step\n"));186print_matrix(_step);187188Mat x = x_.getMat(), simplex;189190createInitialSimplex(x, simplex, _step);191int count = 0;192double res = innerDownhillSimplex(simplex,_termcrit.epsilon, _termcrit.epsilon,193count, _termcrit.maxCount);194dprintf(("%d iterations done\n",count));195196if( !x.empty() )197{198Mat simplex_0m(x.rows, x.cols, CV_64F, simplex.ptr<double>());199simplex_0m.convertTo(x, x.type());200}201else202{203int x_type = x_.fixedType() ? x_.type() : CV_64F;204simplex.row(0).convertTo(x_, x_type);205}206return res;207}208protected:209Ptr<MinProblemSolver::Function> _Function;210TermCriteria _termcrit;211Mat _step;212213inline void updateCoordSum(const Mat& p, Mat& coord_sum)214{215int i, j, m = p.rows, n = p.cols;216double* coord_sum_ = coord_sum.ptr<double>();217CV_Assert( coord_sum.cols == n && coord_sum.rows == 1 );218219for( j = 0; j < n; j++ )220coord_sum_[j] = 0.;221222for( i = 0; i < m; i++ )223{224const double* p_i = p.ptr<double>(i);225for( j = 0; j < n; j++ )226coord_sum_[j] += p_i[j];227}228229dprintf(("\nupdated coord sum:\n"));230print_matrix(coord_sum);231232}233234inline void createInitialSimplex( const Mat& x0, Mat& simplex, Mat& step )235{236int i, j, ndim = step.cols;237CV_Assert( _Function->getDims() == ndim );238Mat x = x0;239if( x0.empty() )240x = Mat::zeros(1, ndim, CV_64F);241CV_Assert( (x.cols == 1 && x.rows == ndim) || (x.cols == ndim && x.rows == 1) );242CV_Assert( x.type() == CV_32F || x.type() == CV_64F );243244simplex.create(ndim + 1, ndim, CV_64F);245Mat simplex_0m(x.rows, x.cols, CV_64F, simplex.ptr<double>());246247x.convertTo(simplex_0m, CV_64F);248double* simplex_0 = simplex.ptr<double>();249const double* step_ = step.ptr<double>();250for( i = 1; i <= ndim; i++ )251{252double* simplex_i = simplex.ptr<double>(i);253for( j = 0; j < ndim; j++ )254simplex_i[j] = simplex_0[j];255simplex_i[i-1] += 0.5*step_[i-1];256}257for( j = 0; j < ndim; j++ )258simplex_0[j] -= 0.5*step_[j];259260dprintf(("\nthis is simplex\n"));261print_matrix(simplex);262}263264/*265Performs the actual minimization of MinProblemSolver::Function f (after the initialization was done)266267The matrix p[ndim+1][1..ndim] represents ndim+1 vertices that268form a simplex - each row is an ndim vector.269On output, fcount gives the number of function evaluations taken.270*/271double innerDownhillSimplex( Mat& p, double MinRange, double MinError, int& fcount, int nmax )272{273int i, j, ndim = p.cols;274Mat coord_sum(1, ndim, CV_64F), buf(1, ndim, CV_64F), y(1, ndim+1, CV_64F);275double* y_ = y.ptr<double>();276277fcount = ndim+1;278for( i = 0; i <= ndim; i++ )279y_[i] = calc_f(p.ptr<double>(i));280281updateCoordSum(p, coord_sum);282283for (;;)284{285// find highest (worst), next-to-worst, and lowest286// (best) points by going through all of them.287int ilo = 0, ihi, inhi;288if( y_[0] > y_[1] )289{290ihi = 0; inhi = 1;291}292else293{294ihi = 1; inhi = 0;295}296for( i = 0; i <= ndim; i++ )297{298double yval = y_[i];299if (yval <= y_[ilo])300ilo = i;301if (yval > y_[ihi])302{303inhi = ihi;304ihi = i;305}306else if (yval > y_[inhi] && i != ihi)307inhi = i;308}309CV_Assert( ihi != inhi );310if( ilo == inhi || ilo == ihi )311{312for( i = 0; i <= ndim; i++ )313{314double yval = y_[i];315if( yval == y_[ilo] && i != ihi && i != inhi )316{317ilo = i;318break;319}320}321}322dprintf(("\nthis is y on iteration %d:\n",fcount));323print_matrix(y);324325// check stop criterion326double error = fabs(y_[ihi] - y_[ilo]);327double range = 0;328for( j = 0; j < ndim; j++ )329{330double minval, maxval;331minval = maxval = p.at<double>(0, j);332for( i = 1; i <= ndim; i++ )333{334double pval = p.at<double>(i, j);335minval = std::min(minval, pval);336maxval = std::max(maxval, pval);337}338range = std::max(range, fabs(maxval - minval));339}340341if( range <= MinRange || error <= MinError || fcount >= nmax )342{343// Put best point and value in first slot.344std::swap(y_[0], y_[ilo]);345for( j = 0; j < ndim; j++ )346{347std::swap(p.at<double>(0, j), p.at<double>(ilo, j));348}349break;350}351352double y_lo = y_[ilo], y_nhi = y_[inhi], y_hi = y_[ihi];353// Begin a new iteration. First, reflect the worst point about the centroid of others354double alpha = -1.0;355double y_alpha = tryNewPoint(p, coord_sum, ihi, alpha, buf, fcount);356357dprintf(("\ny_lo=%g, y_nhi=%g, y_hi=%g, y_alpha=%g, p_alpha:\n", y_lo, y_nhi, y_hi, y_alpha));358print_matrix(buf);359360if( y_alpha < y_nhi )361{362if( y_alpha < y_lo )363{364// If that's better than the best point, go twice as far in that direction365double beta = -2.0;366double y_beta = tryNewPoint(p, coord_sum, ihi, beta, buf, fcount);367dprintf(("\ny_beta=%g, p_beta:\n", y_beta));368print_matrix(buf);369if( y_beta < y_alpha )370{371alpha = beta;372y_alpha = y_beta;373}374}375replacePoint(p, coord_sum, y, ihi, alpha, y_alpha);376}377else378{379// The new point is worse than the second-highest,380// do not go so far in that direction381double gamma = 0.5;382double y_gamma = tryNewPoint(p, coord_sum, ihi, gamma, buf, fcount);383dprintf(("\ny_gamma=%g, p_gamma:\n", y_gamma));384print_matrix(buf);385if( y_gamma < y_hi )386replacePoint(p, coord_sum, y, ihi, gamma, y_gamma);387else388{389// Can't seem to improve things.390// Contract the simplex to good point391// in hope to find a simplex landscape.392for( i = 0; i <= ndim; i++ )393{394if (i != ilo)395{396for( j = 0; j < ndim; j++ )397p.at<double>(i, j) = 0.5*(p.at<double>(i, j) + p.at<double>(ilo, j));398y_[i] = calc_f(p.ptr<double>(i));399}400}401fcount += ndim;402updateCoordSum(p, coord_sum);403}404}405dprintf(("\nthis is simplex on iteration %d\n",fcount));406print_matrix(p);407}408return y_[0];409}410411inline double calc_f(const double* ptr)412{413double res = _Function->calc(ptr);414CV_Assert( !cvIsNaN(res) && !cvIsInf(res) );415return res;416}417418double tryNewPoint( Mat& p, Mat& coord_sum, int ihi, double alpha_, Mat& ptry, int& fcount )419{420int j, ndim = p.cols;421422double alpha = (1.0 - alpha_)/ndim;423double beta = alpha - alpha_;424double* p_ihi = p.ptr<double>(ihi);425double* ptry_ = ptry.ptr<double>();426double* coord_sum_ = coord_sum.ptr<double>();427428for( j = 0; j < ndim; j++ )429ptry_[j] = coord_sum_[j]*alpha - p_ihi[j]*beta;430431fcount++;432return calc_f(ptry_);433}434435void replacePoint( Mat& p, Mat& coord_sum, Mat& y, int ihi, double alpha_, double ytry )436{437int j, ndim = p.cols;438439double alpha = (1.0 - alpha_)/ndim;440double beta = alpha - alpha_;441double* p_ihi = p.ptr<double>(ihi);442double* coord_sum_ = coord_sum.ptr<double>();443444for( j = 0; j < ndim; j++ )445p_ihi[j] = coord_sum_[j]*alpha - p_ihi[j]*beta;446y.at<double>(ihi) = ytry;447updateCoordSum(p, coord_sum);448}449};450451452// both minRange & minError are specified by termcrit.epsilon;453// In addition, user may specify the number of iterations that the algorithm does.454Ptr<DownhillSolver> DownhillSolver::create( const Ptr<MinProblemSolver::Function>& f,455InputArray initStep, TermCriteria termcrit )456{457Ptr<DownhillSolver> DS = makePtr<DownhillSolverImpl>();458DS->setFunction(f);459DS->setInitStep(initStep);460DS->setTermCriteria(termcrit);461return DS;462}463464}465466467