curve fitting - Problems with MPFIT and user-defined derivatives -
i trying use optimization library mpfit fit gaussian function data. code part of example code comes mpfit library. original code automatically calculates internally derivatives of function numerically , works perfectly. mpfit library allows user provide function derivatives. problem starts. here function used calculate residuals , function's first order partial derivatives.
int gaussfunc(int m, int n, double *p, double *dy, double **derivs, void *vars) { int i,j; struct vars_struct *v = (struct vars_struct *) vars; double *x, *y, *ey; double = p[1]; double b = p[2]; double c = p[3]; double d = p[0]; x = v->x; y = v->y; ey = v->ey; (i=0; i<m; i++) { dy[i] = (y[i] - (a*exp(-(x[i]-b)*(x[i]-b)/(2*c*c))+d))/ey[i]; } // code below point code added calculate derivatives. if(derivs) { for(j = 0; j < n; j++) { if (derivs[j]) { (i = 0; < m; i++) { double da = exp(-(x[i]-b)*(x[i]-b)/(2*c*c)); double db = * exp(-(x[i]-b)*(x[i]-b)/(2*c*c)) * (x[i]-b)/(c*c); double dc = * exp(-(x[i]-b)*(x[i]-b)/(2*c*c)) * (x[i]-b)*(x[i]-b)/(c*c*c); double dd = 1; double foo; if (j == 0) foo = dd; else if(j == 1) foo = da; else if(j == 2) foo = db; else if(j == 3) foo = dc; derivs[j][i] = foo; } } } } return 0; } the code above line 'if (derivs)' original 1 refactored , code below code computing derivatives. believe maths correct, , verified https://math.stackexchange.com/questions/716545/calculating-the-first-order-partial-derivatives-of-the-gaussian-function/716553
has encountered same problem while using mpfit user-defined derivatives?
thank you.
because calculation of residuals (data-model)/sigma, derivatives should be:
[-d(model)/d(param)]/sigma.
so, line:
derivs[j][i] = foo; becomes:
derivs[j][i] = -foo/ey[i]; problem solved! thanks!
Comments
Post a Comment