/*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) 2000, Intel Corporation, all rights reserved.13// Copyright (C) 2013, OpenCV Foundation, all rights reserved.14// Third party copyrights are property of their respective owners.15//16// Redistribution and use in source and binary forms, with or without modification,17// are permitted provided that the following conditions are met:18//19// * Redistribution's of source code must retain the above copyright notice,20// this list of conditions and the following disclaimer.21//22// * Redistribution's in binary form must reproduce the above copyright notice,23// this list of conditions and the following disclaimer in the documentation24// and/or other materials provided with the distribution.25//26// * The name of the copyright holders may not be used to endorse or promote products27// derived from this software without specific prior written permission.28//29// This software is provided by the copyright holders and contributors "as is" and30// any express or implied warranties, including, but not limited to, the implied31// warranties of merchantability and fitness for a particular purpose are disclaimed.32// In no event shall the Intel Corporation or contributors be liable for any direct,33// indirect, incidental, special, exemplary, or consequential damages34// (including, but not limited to, procurement of substitute goods or services;35// loss of use, data, or profits; or business interruption) however caused36// and on any theory of liability, whether in contract, strict liability,37// or tort (including negligence or otherwise) arising in any way out of38// the use of this software, even if advised of the possibility of such damage.39//40//M*/4142#include "precomp.hpp"43#include <stdio.h>4445/*46This is a translation to C++ from the Matlab's LMSolve package by Miroslav Balda.47Here is the original copyright:48============================================================================4950Copyright (c) 2007, Miroslav Balda51All rights reserved.5253Redistribution and use in source and binary forms, with or without54modification, are permitted provided that the following conditions are55met:5657* Redistributions of source code must retain the above copyright58notice, this list of conditions and the following disclaimer.59* Redistributions in binary form must reproduce the above copyright60notice, this list of conditions and the following disclaimer in61the documentation and/or other materials provided with the distribution6263THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"64AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE65IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE66ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE67LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR68CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF69SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS70INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN71CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)72ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE73POSSIBILITY OF SUCH DAMAGE.74*/7576namespace cv77{7879class LMSolverImpl CV_FINAL : public LMSolver80{81public:82LMSolverImpl() : maxIters(100) { init(); }83LMSolverImpl(const Ptr<LMSolver::Callback>& _cb, int _maxIters) : cb(_cb), maxIters(_maxIters) { init(); }8485void init()86{87epsx = epsf = FLT_EPSILON;88printInterval = 0;89}9091int run(InputOutputArray _param0) const CV_OVERRIDE92{93Mat param0 = _param0.getMat(), x, xd, r, rd, J, A, Ap, v, temp_d, d;94int ptype = param0.type();9596CV_Assert( (param0.cols == 1 || param0.rows == 1) && (ptype == CV_32F || ptype == CV_64F));97CV_Assert( cb );9899int lx = param0.rows + param0.cols - 1;100param0.convertTo(x, CV_64F);101102if( x.cols != 1 )103transpose(x, x);104105if( !cb->compute(x, r, J) )106return -1;107double S = norm(r, NORM_L2SQR);108int nfJ = 2;109110mulTransposed(J, A, true);111gemm(J, r, 1, noArray(), 0, v, GEMM_1_T);112113Mat D = A.diag().clone();114115const double Rlo = 0.25, Rhi = 0.75;116double lambda = 1, lc = 0.75;117int i, iter = 0;118119if( printInterval != 0 )120{121printf("************************************************************************************\n");122printf("\titr\tnfJ\t\tSUM(r^2)\t\tx\t\tdx\t\tl\t\tlc\n");123printf("************************************************************************************\n");124}125126for( ;; )127{128CV_Assert( A.type() == CV_64F && A.rows == lx );129A.copyTo(Ap);130for( i = 0; i < lx; i++ )131Ap.at<double>(i, i) += lambda*D.at<double>(i);132solve(Ap, v, d, DECOMP_EIG);133subtract(x, d, xd);134if( !cb->compute(xd, rd, noArray()) )135return -1;136nfJ++;137double Sd = norm(rd, NORM_L2SQR);138gemm(A, d, -1, v, 2, temp_d);139double dS = d.dot(temp_d);140double R = (S - Sd)/(fabs(dS) > DBL_EPSILON ? dS : 1);141142if( R > Rhi )143{144lambda *= 0.5;145if( lambda < lc )146lambda = 0;147}148else if( R < Rlo )149{150// find new nu if R too low151double t = d.dot(v);152double nu = (Sd - S)/(fabs(t) > DBL_EPSILON ? t : 1) + 2;153nu = std::min(std::max(nu, 2.), 10.);154if( lambda == 0 )155{156invert(A, Ap, DECOMP_EIG);157double maxval = DBL_EPSILON;158for( i = 0; i < lx; i++ )159maxval = std::max(maxval, std::abs(Ap.at<double>(i,i)));160lambda = lc = 1./maxval;161nu *= 0.5;162}163lambda *= nu;164}165166if( Sd < S )167{168nfJ++;169S = Sd;170std::swap(x, xd);171if( !cb->compute(x, r, J) )172return -1;173mulTransposed(J, A, true);174gemm(J, r, 1, noArray(), 0, v, GEMM_1_T);175}176177iter++;178bool proceed = iter < maxIters && norm(d, NORM_INF) >= epsx && norm(r, NORM_INF) >= epsf;179180if( printInterval != 0 && (iter % printInterval == 0 || iter == 1 || !proceed) )181{182printf("%c%10d %10d %15.4e %16.4e %17.4e %16.4e %17.4e\n",183(proceed ? ' ' : '*'), iter, nfJ, S, x.at<double>(0), d.at<double>(0), lambda, lc);184}185186if(!proceed)187break;188}189190if( param0.size != x.size )191transpose(x, x);192193x.convertTo(param0, ptype);194if( iter == maxIters )195iter = -iter;196197return iter;198}199200void setCallback(const Ptr<LMSolver::Callback>& _cb) CV_OVERRIDE { cb = _cb; }201202Ptr<LMSolver::Callback> cb;203204double epsx;205double epsf;206int maxIters;207int printInterval;208};209210211Ptr<LMSolver> createLMSolver(const Ptr<LMSolver::Callback>& cb, int maxIters)212{213return makePtr<LMSolverImpl>(cb, maxIters);214}215216}217218219