Dear All, I am testing alglib.
I started from the fitting example, that I modified to fit a sinusoid over sine-like data (See attached picture)
And honnestly, it does not work at all.
I am fitting a y = A*sin(2 \pi Bx +C) +D function (So a very classic one, that we meet daily in physics/engineering/signal processing or whatever else) and it seems that the fitting procedure set A to a very small value and then fails to converge
Here is my source code, does someone knows what I made wrong and what I have to do to get it working
Code:
ude <cstdlib>
#include <cstdio>
#include <cmath>
#include <string>
#include <vector>
#include <fstream>
#include <iostream>
#include "interpolation.h"
using namespace alglib;
void function_cx_1_func(const real_1d_array &c, const real_1d_array &x, double &func, void *ptr)
{
// this callback calculates f(c,x)=exp(-c0*sqr(x0))
// where x is a position on X-axis and c is adjustable parameter
func = c[0] * sin( 2 * 3.14159 * c[1] * x[0] + c[2]) + c[3];
}
int main(int argc, char **argv)
{
//
using std::cout;
using std::endl;
const std::string infile="/path/to/data";
std::vector<double> vx;
std::vector<double> vy;
std::ifstream data(infile.c_str());
while (!data.eof() || !data.fail()) {
double xx(0),yy(0);
data >> xx >> yy ;
if (data.fail()) break;
vx.push_back(xx);
vy.push_back(yy);
}
data.close();
real_1d_array c = "[2.5, 0.5, 0., 0.]"; //this is a rough guess but shouldn't be so wrong
//Setting parameters from input file too x,y array, I don't know the lib but I am confident I did it the right way
real_2d_array x;
x.setcontent(vx.size(), 1, &vx.front());
real_1d_array y;
y.setcontent(vy.size(), &vy.front());
double epsf = 0;
double epsx = 0.0001;
ae_int_t maxits = 0;
ae_int_t info;
lsfitstate state;
lsfitreport rep;
double diffstep = 0.0001;
//
// Fitting without weights
//
lsfitcreatef(x, y, c, 0.01, state); //played with params
lsfitsetcond(state, epsf, epsx, maxits);
alglib::lsfitfit(state, function_cx_1_func);
lsfitresults(state, info, c, rep);
cout << info << endl;
// cout << x.tostring(1) << endl;
// cout << y.tostring(1) << endl;
std::cout << c[0] << "* sin (2 pi " << c[1] <<"x + " << c[2] << ") + " << c[3] <<std::endl;
std::cout << rep.errpar[0] << " " << rep.errpar[1] << " " << rep.errpar[2] << " " << rep.errpar[3] << std::endl;
return 0;
}
[img]testALG.png[/img]