fitter.cpp 7.82 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 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 36 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 117 118 119 120 121 122 123
#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 <QTime>

#include <core/common.h>

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

class altaNLP : public Ipopt::TNLP
{
	public:
		altaNLP(nonlinear_function* f, const data* d) : TNLP(), _f(f), _d(d)
		{
		}

		// 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];
				}

				// Compute the difference vector and add its
				// components to the obj_value
				vec _y = _di - (*_f)(_x);
				for(int i=0; i<_f->dimY(); ++i)
				{
					obj_value += abs(_y[i]);
				}
			}

			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
124 125 126 127 128
			// Update the parameters vector
			vec _p(n);
			for(int i=0; i<n; ++i) { _p[i] = x[i]; }
			_f->setParameters(_p);

129 130 131 132 133 134 135
			// 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
136 137 138 139 140 141 142 143 144 145 146
				
				// 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];
				}

				// Compute the difference vector and add its
				// components to the obj_value
				vec _y = _di - (*_f)(_x);
147 148 149 150 151 152 153 154 155 156 157 158

				// Get the jacobian of the function at position x_i for the current
				// set of parameters (set prior to function call)
				vec _jac = _f->parametersJacobian(_x);

				// 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)
					{
Laurent Belcour's avatar
Laurent Belcour committed
159 160 161 162 163 164 165 166
						if(_y[i] > 0.0)
						{
							grad_f[j] += -_jac[i*_f->nbParameters() + j];
						}
						else
						{
							grad_f[j] += _jac[i*_f->nbParameters() + j];
						}
167 168 169 170 171 172 173 174 175 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
					}
				}
			}

			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
205 206 207 208
			// Update the parameters vector
			vec _p(n);
			for(int i=0; i<n; ++i) { _p[i] = x[i]; }
			_f->setParameters(_p);
209
		}
Laurent Belcour's avatar
Laurent Belcour committed
210

211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
	protected:

		const data* _d;
		nonlinear_function* _f;
};

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

bool nonlinear_fitter_ipopt::fit_data(const data* d, function* fit, const arguments &args)
{
	// 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
	if(dynamic_cast<nonlinear_function*>(fit) == NULL)
	{
		std::cerr << "<<ERROR>> the function is not a non-linear function" << std::endl;
		return false;
	}
	nonlinear_function* nf = dynamic_cast<nonlinear_function*>(fit);
	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");
268 269 270 271 272
#ifdef DEBUG
	app->Options()->SetIntegerValue("print_level", 5);
#else
	app->Options()->SetIntegerValue("print_level", 0);
#endif
273 274 275

	// Solver's options
	app->Options()->SetIntegerValue("max_iter", args.get_int("ipopt-max-iter", 10));
276
	app->Options()->SetStringValue("linear_solver", args.get_string("ipopt-solver", "mumps"));
277 278 279 280 281 282 283 284
	

	// 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
285 286 287 288 289 290 291 292 293 294 295 296
		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;
297
#endif
Laurent Belcour's avatar
Laurent Belcour committed
298
		std::cout << "<<INFO>> found parameters: " << nf->parameters() << std::endl;
299 300 301 302 303 304 305 306 307 308 309 310

		return true;
	}
	else
	{
		return false;
	}
}

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