fitter.cpp 8.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
/* ALTA --- Analysis of Bidirectional Reflectance Distribution Functions

   Copyright (C) 2013, 2014 Inria

   This file is part of ALTA.

   This Source Code Form is subject to the terms of the Mozilla Public
   License, v. 2.0.  If a copy of the MPL was not distributed with this
   file, You can obtain one at http://mozilla.org/MPL/2.0/.  */

11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
#include "fitter.h"

#include <Eigen/Dense>

#include <coin/IpTNLP.hpp>
#include <coin/IpIpoptApplication.hpp>
#include <coin/IpSolveStatistics.hpp>

#include <string>
#include <iostream>
#include <fstream>
#include <limits>
#include <algorithm>
#include <cmath>

#include <core/common.h>

ALTA_DLL_EXPORT fitter* provide_fitter()
{
    return new nonlinear_fitter_ipopt();
}

class altaNLP : public Ipopt::TNLP
{
	public:
36
		altaNLP(const ptr<nonlinear_function>& f, const ptr<data>& d) : TNLP(), _f(f), _d(d)
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
		{
		}

		// Return the size of the NL problem
		virtual bool get_nlp_info(Ipopt::Index& n, Ipopt::Index& m, Ipopt::Index& nnz_jac_g,
		                          Ipopt::Index& nnz_h_lag, IndexStyleEnum& index_style)
		{
			// Size of the problem
			n = _f->nbParameters();
			m = 0;
			
			// Nonzeros in the Jacobian and Hessian
			nnz_jac_g = 0;
			nnz_h_lag = 0;

			// C++ indexing of arrays
			index_style = C_STYLE;

			return true;
		}

		virtual bool get_bounds_info(Ipopt::Index n, Ipopt::Number* x_l, Ipopt::Number* x_u,
		                             Ipopt::Index m, Ipopt::Number* g_l, Ipopt::Number* g_u)
		{
			// Check the size of the problem
			assert(n == _f->nbParameters());
			assert(m == 0);

			// min and Max values for the parameters
			vec p_min = _f->getParametersMin();
			vec p_max = _f->getParametersMax();

			for(int i=0; i<n; ++i)
			{
				x_l[i] = p_min[i];
				x_u[i] = p_max[i];
			}

			return true;
		}

		virtual bool get_starting_point(Ipopt::Index n, bool init_x, Ipopt::Number* x,
		                                bool init_z, Ipopt::Number* z_L, Ipopt::Number* z_U,
		                                Ipopt::Index m, bool init_lambda,
		                                Ipopt::Number* lambda)
		{
			// Check the input
			assert(n == _f->nbParameters());
			assert(init_x == true);

			vec p = _f->parameters();
			for(int i=0; i<n; ++i)
			{
				x[i] = p[i];
			}

			return true;
		}
		

		virtual bool eval_f(Ipopt::Index n, const Ipopt::Number* x, bool new_x, 
		                    Ipopt::Number& obj_value)
		{
			// Update the parameters vector
			vec _p(n);
			for(int i=0; i<n; ++i) { _p[i] = x[i]; }
			_f->setParameters(_p);

			obj_value = 0.0;
			for(int s=0; s<_d->size(); ++s)
			{
				vec _x  = _d->get(s);

				// Extract the objective from the current vector
				vec _di = vec(_f->dimY());
				for(int i=0; i<_f->dimY(); ++i)
				{
					_di[i] = _x[_f->dimX() + i];
				}

117 118 119 120
				// Convert the sample point into the function space
				vec x(_f->dimX());
				params::convert(&_x[0], _d->input_parametrization(), _f->input_parametrization(), &x[0]);

121 122
				// Compute the difference vector and add its
				// components to the obj_value
123
				vec _y = _di - _f->value(x);
124 125
				for(int i=0; i<_f->dimY(); ++i)
				{
126
					obj_value += pow(_y[i], 2);
127 128 129 130 131 132 133 134 135
				}
			}

			return true;
		}
		
		virtual bool eval_grad_f(Ipopt::Index n, const Ipopt::Number* x, 
		                         bool new_x, Ipopt::Number* grad_f)
		{
Laurent Belcour's avatar
Laurent Belcour committed
136 137 138 139 140
			// Update the parameters vector
			vec _p(n);
			for(int i=0; i<n; ++i) { _p[i] = x[i]; }
			_f->setParameters(_p);

141 142 143 144 145 146 147
			// Clean the value
			for(int i=0; i<n; ++i) { grad_f[i] = 0.0; }

			// Add all the gradients
			for(int s=0; s<_d->size(); ++s)
			{
				vec _x  = _d->get(s);
Laurent Belcour's avatar
Laurent Belcour committed
148 149 150 151 152 153 154
				
				// Extract the objective from the current vector
				vec _di = vec(_f->dimY());
				for(int i=0; i<_f->dimY(); ++i)
				{
					_di[i] = _x[_f->dimX() + i];
				}
155 156 157 158
				
				// Convert the sample point into the function space
				vec x(_f->dimX());
				params::convert(&_x[0], _d->input_parametrization(), _f->input_parametrization(), &x[0]);
Laurent Belcour's avatar
Laurent Belcour committed
159 160 161

				// Compute the difference vector and add its
				// components to the obj_value
162
				vec _y = _f->value(x) - _di;
163 164 165

				// Get the jacobian of the function at position x_i for the current
				// set of parameters (set prior to function call)
166
				vec _jac = _f->parametersJacobian(x);
167 168 169 170 171 172 173 174

				// Fill the columns of the matrix
				for(int j=0; j<_f->nbParameters(); ++j)
				{
					// For each output channel, update the subpart of the
					// vector row
					for(int i=0; i<_f->dimY(); ++i)
					{
175
						grad_f[j] += 2 * _y[i] * _jac[i*_f->nbParameters() + j];
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
					}
				}
			}

			return true;
		}
		
		virtual bool eval_g(Ipopt::Index n, const Ipopt::Number* x, bool new_x, 
		                    Ipopt::Index m, Ipopt::Number* g)
		{
			return true;
		}
		
		virtual bool eval_jac_g(Ipopt::Index n, const Ipopt::Number* x, bool new_x,
                              Ipopt::Index m, Ipopt::Index nele_jac, Ipopt::Index* iRow, 
										Ipopt::Index *jCol, Ipopt::Number* values)
		{
			return true;
		}

		/*
		virtual bool eval_h(Ipopt::Index n, const Ipopt::Number* x, bool new_x,
                          Ipopt::Number obj_factor, Ipopt::Index m, 
								  const Ipopt::Number* lambda, bool new_lambda, 
								  Ipopt::Index nele_hess, Ipopt::Index* iRow,
                          Ipopt::Index* jCol, Ipopt::Number* values)
		{
			return false;
		}
		*/

		virtual void finalize_solution(Ipopt::SolverReturn status, Ipopt::Index n, 
		                               const Ipopt::Number* x, const Ipopt::Number* z_L, 
												 const Ipopt::Number* z_U, Ipopt::Index m, 
												 const Ipopt::Number* g, const Ipopt::Number* lambda,
                                     Ipopt::Number obj_value, const Ipopt::IpoptData* ip_data,
		                               Ipopt::IpoptCalculatedQuantities* ip_cq)
		{
Laurent Belcour's avatar
Laurent Belcour committed
214 215 216 217
			// Update the parameters vector
			vec _p(n);
			for(int i=0; i<n; ++i) { _p[i] = x[i]; }
			_f->setParameters(_p);
218
		}
Laurent Belcour's avatar
Laurent Belcour committed
219

220 221
	protected:

222 223
		const ptr<data>& _d;
		const ptr<nonlinear_function>& _f;
224 225 226 227 228 229 230 231 232
};

nonlinear_fitter_ipopt::nonlinear_fitter_ipopt() 
{
}
nonlinear_fitter_ipopt::~nonlinear_fitter_ipopt() 
{
}

233
bool nonlinear_fitter_ipopt::fit_data(const ptr<data>& d, ptr<function>& fit, const arguments &args)
234 235 236 237 238 239 240 241 242
{
	// I need to set the dimension of the resulting function to be equal
	// to the dimension of my fitting problem
	fit->setDimX(d->dimX()) ;
	fit->setDimY(d->dimY()) ;
	fit->setMin(d->min()) ;
	fit->setMax(d->max()) ;

	// Convert the function and bootstrap it with the data
243 244
	ptr<nonlinear_function> nf = dynamic_pointer_cast<nonlinear_function>(fit);
	if(!nf)
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
	{
		std::cerr << "<<ERROR>> the function is not a non-linear function" << std::endl;
		return false;
	}
	nf->bootstrap(d, args);

#ifndef DEBUG
	std::cout << "<<DEBUG>> number of parameters: " << nf->nbParameters() << std::endl;
#endif
	if(nf->nbParameters() == 0)
	{
		return true;
	}

	/* the following starting values provide a rough fit. */
	vec p = nf->parameters();

	// Create the problem
	Ipopt::SmartPtr<Ipopt::TNLP> nlp = new altaNLP(nf, d);
	Ipopt::SmartPtr<Ipopt::IpoptApplication> app = IpoptApplicationFactory();


	Ipopt::ApplicationReturnStatus status;
	status = app->Initialize();
	if(status != Ipopt::Solve_Succeeded) 
	{
		std::cout << "<<ERROR>> unable to create Ipopt solver" << std::endl;
		return false;
	}

	// Static parameters for the Solver
	app->Options()->SetStringValue("hessian_approximation", "limited-memory");
277 278 279 280 281
#ifdef DEBUG
	app->Options()->SetIntegerValue("print_level", 5);
#else
	app->Options()->SetIntegerValue("print_level", 0);
#endif
282 283 284

	// Solver's options
	app->Options()->SetIntegerValue("max_iter", args.get_int("ipopt-max-iter", 10));
285
	app->Options()->SetStringValue("linear_solver", args.get_string("ipopt-solver", "mumps"));
286 287 288 289 290 291 292 293
	

	// Solves the NL problem
	status = app->OptimizeTNLP(nlp);
	if(status == Ipopt::Solve_Succeeded)
	{
#ifdef DEBUG
		Ipopt::Index iter_count = app->Statistics()->IterationCount();
Laurent Belcour's avatar
Laurent Belcour committed
294 295 296 297 298 299 300 301 302 303 304 305
		std::cout << "<<DEBUG>> number of iterations: " << iter_count << std::endl;
#endif
			std::cout << "<<INFO>> found parameters: " << nf->parameters() << std::endl;

		return true;
	}
	else if(status == Ipopt::Maximum_Iterations_Exceeded)
	{
		std::cout << "<<INFO>> the maximum number of iteration has been reached" << std::endl;
#ifdef DEBUG
		Ipopt::Index iter_count = app->Statistics()->IterationCount();
		std::cout << "<<DEBUG>> number of iterations: " << iter_count << std::endl;
306
#endif
Laurent Belcour's avatar
Laurent Belcour committed
307
		std::cout << "<<INFO>> found parameters: " << nf->parameters() << std::endl;
308 309 310 311 312 313 314 315 316 317 318 319

		return true;
	}
	else
	{
		return false;
	}
}

void nonlinear_fitter_ipopt::set_parameters(const arguments& args)
{
}