Exemple #1
0
double polynomialfit(int obs, int degree, double *dx, double *dy, double *store) {
    gsl_multifit_linear_workspace *ws;
    gsl_matrix *cov, *X;
    gsl_vector *y, *c;
    double chisq;

    int i, j;

    X = gsl_matrix_alloc(obs, degree);
    y = gsl_vector_alloc(obs);
    c = gsl_vector_alloc(degree);
    cov = gsl_matrix_alloc(degree, degree);

    for(i=0; i < obs; i++) {
        gsl_matrix_set(X, i, 0, 1.0);
        for(j=0; j < degree; j++) {
            gsl_matrix_set(X, i, j, pow(dx[i], j));
        }
        gsl_vector_set(y, i, dy[i]);
    }

    ws = gsl_multifit_linear_alloc(obs, degree);
    gsl_multifit_linear(X, y, c, cov, &chisq, ws);

    for(i=0; i < degree; i++) {
        store[i] = gsl_vector_get(c, i);
    }

    gsl_multifit_linear_free(ws);
    gsl_matrix_free(X);
    gsl_matrix_free(cov);
    gsl_vector_free(y);
    gsl_vector_free(c);
    return chisq; // return error
}
 void TransformationModelBSpline::computeFit_()
 {
   // construct the fit matrix:
   gsl_matrix * fit_matrix = gsl_matrix_alloc(size_, ncoeffs_);
   bsplines_ = gsl_vector_alloc(ncoeffs_);
   for (size_t i = 0; i < size_; ++i)
   {
     double xi = gsl_vector_get(x_, i);
     gsl_bspline_eval(xi, bsplines_, workspace_);
     for (size_t j = 0; j < ncoeffs_; ++j)
     {
       double bspline = gsl_vector_get(bsplines_, j);
       gsl_matrix_set(fit_matrix, i, j, bspline);
     }
   }
   // do the fit:
   gsl_multifit_linear_workspace * multifit = gsl_multifit_linear_alloc(
     size_, ncoeffs_);
   coeffs_ = gsl_vector_alloc(ncoeffs_);
   cov_ = gsl_matrix_alloc(ncoeffs_, ncoeffs_);
   double chisq;
   gsl_multifit_wlinear(fit_matrix, w_, y_, coeffs_, cov_, &chisq, multifit);
   // clean-up:
   gsl_matrix_free(fit_matrix);
   gsl_multifit_linear_free(multifit);
   // for linear extrapolation (natural spline):
   computeLinear_(xmin_, slope_min_, offset_min_, sd_err_left_);
   computeLinear_(xmax_, slope_max_, offset_max_, sd_err_right_);
 }
Exemple #3
0
QVector<Quadric2D> fittingGLOBAL_flivre(gsl_matrix * A, gsl_vector * B)
{

    gsl_matrix *cov = gsl_matrix_alloc (A->size2, A->size2);
    gsl_vector * x = gsl_vector_alloc(A->size2);

    gsl_multifit_linear_workspace * work = gsl_multifit_linear_alloc (A->size1,A->size2);
    real chisq = 0.0;
    real tol = 0.000001 ;
    size_t rank = 0 ;
    gsl_multifit_linear_svd( A,B, tol, &rank, x, cov, &chisq, work);
    //gsl_multifit_linear(A,B, x, cov, &chisq, work);
    gsl_multifit_linear_free (work);

    //qDebug() << chisq;
    //qDebug() << rank ;

    QVector<Quadric2D> resp;
    for(unsigned int i = 0; i < A->size2/6; ++i)
    {
        float x1 = gsl_vector_get(x, i*6);
        float x2 = gsl_vector_get(x, i*6 + 1);// b/2
        float x3 = gsl_vector_get(x, i*6 + 2);// c/2
        float x4 = gsl_vector_get(x, i*6 + 3);
        float x5 = gsl_vector_get(x, i*6 + 4);// e/2
        float x6 = gsl_vector_get(x, i*6 + 5);

        resp.push_back(Quadric2D(x1,x2,x3,x4,x5,x6));
    }

    gsl_vector_free (x);
    gsl_matrix_free (cov);

    return resp;
}
Exemple #4
0
//--------------------------------------------------------------
bool polynomialfit(int obs, int degree, double *dx, double *dy, double *store){ /* n, p */
  gsl_multifit_linear_workspace *ws;
  gsl_matrix *cov, *X;
  gsl_vector *y, *c;
  double chisq;

  X = gsl_matrix_alloc(obs, degree);
  y = gsl_vector_alloc(obs);
  c = gsl_vector_alloc(degree);
  cov = gsl_matrix_alloc(degree, degree);

  for(int i=0; i<obs; i++){
    gsl_matrix_set(X, i, 0, 1.0);
    for(int j=0; j<degree; j++){
        gsl_matrix_set(X, i, j, pow(dx[i], j));
    }
    gsl_vector_set(y, i, dy[i]);
  }

  ws = gsl_multifit_linear_alloc(obs, degree);
  gsl_multifit_linear(X, y, c, cov, &chisq, ws);

  /* store result ... */
  for(int i=0; i< degree; i++){
    store[i] = gsl_vector_get(c, i);
  }

  gsl_multifit_linear_free(ws);
  gsl_matrix_free(X);
  gsl_matrix_free(cov);
  gsl_vector_free(y);
  gsl_vector_free(c);
  return true; /* we do not "analyse" the result (cov matrix mainly)
		  to know if the fit is "good" */
}
Exemple #5
0
/** \brief Estimate by ML the effect size of the genotype, the std deviation 
 *  of the errors and the std error of the estimated effect size in the 
 *  multiple linear regression Y = XB + E with E~MVN(0,sigma^2I)
 *  \note genotype supposed to be 2nd column of X
 */
  void FitSingleGeneWithSingleSnp(const gsl_matrix * X,
				  const gsl_vector * y,
				  double & pve,
				  double & sigmahat,
				  double & betahat_geno,
				  double & sebetahat_geno,
				  double & betapval_geno)
  {
    size_t N = X->size1, P = X->size2, rank;
    double rss;
    gsl_vector * Bhat = gsl_vector_alloc(P);
    gsl_matrix * covBhat = gsl_matrix_alloc(P, P);
    gsl_multifit_linear_workspace * work = gsl_multifit_linear_alloc(N, P);
    gsl_multifit_linear_svd(X, y, GSL_DBL_EPSILON, &rank, Bhat, covBhat,
			    &rss, work);
    pve = 1 - rss / gsl_stats_tss(y->data, y->stride, y->size);
    sigmahat = sqrt(rss / (double)(N-rank));
    betahat_geno = gsl_vector_get(Bhat, 1);
    sebetahat_geno = sqrt(gsl_matrix_get (covBhat, 1, 1));
    betapval_geno = 2 * gsl_cdf_tdist_Q(fabs(betahat_geno / sebetahat_geno),
					N-rank);
    gsl_vector_free(Bhat);
    gsl_matrix_free(covBhat);
    gsl_multifit_linear_free(work);
  }
Exemple #6
0
void quadratic_fit(void) {

	int i, n;
	double xi, yi, ei, chisq;
	gsl_matrix *X, *cov;
	gsl_vector *y, *w, *c;

	n = 7;
	double x_vec[] = { 0, 100, 200, 300, 400, 500, 600 };
	double y_vec[] = { 0, 12.5, 50.0, 112.5, 200.0, 312.5, 450.0 };
	double e_vec[] = { 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1 };

	X = gsl_matrix_alloc(n, 3);
	y = gsl_vector_alloc(n);
	w = gsl_vector_alloc(n);

	c = gsl_vector_alloc(3);
	cov = gsl_matrix_alloc(3, 3);

	for (i = 0; i < n; i++) {
		xi = x_vec[i];
		yi = y_vec[i];
		ei = e_vec[i];

		printf("%g %g +/- %g\n", xi, yi, ei);

		gsl_matrix_set(X, i, 0, 1.0);
		gsl_matrix_set(X, i, 1, xi);
		gsl_matrix_set(X, i, 2, xi * xi);

		gsl_vector_set(y, i, yi);
		gsl_vector_set(w, i, 1.0 / (ei * ei));
	}

	{
		gsl_multifit_linear_workspace * work = gsl_multifit_linear_alloc(n, 3);
		gsl_multifit_wlinear(X, w, y, c, cov, &chisq, work);
		gsl_multifit_linear_free(work);
	}

#define C(i) (gsl_vector_get(c,(i)))
#define COV(i,j) (gsl_matrix_get(cov,(i),(j)))

	{
		printf("# best fit: Y = %g + %g X + %g X^2\n", C(0), C(1), C(2));

		printf("# covariance matrix:\n");
		printf("[ %+.5e, %+.5e, %+.5e  \n", COV(0,0), COV(0,1), COV(0,2));
		printf("  %+.5e, %+.5e, %+.5e  \n", COV(1,0), COV(1,1), COV(1,2));
		printf("  %+.5e, %+.5e, %+.5e ]\n", COV(2,0), COV(2,1), COV(2,2));
		printf("# chisq = %g\n", chisq);
	}

	gsl_matrix_free(X);
	gsl_vector_free(y);
	gsl_vector_free(w);
	gsl_vector_free(c);
	gsl_matrix_free(cov);
}
Exemple #7
0
int curve_fit_quad(uint8_t count, FittingData f_data[], double *aa, double *bb, double *cc)
{
    int i, n;
    double xi, yi, chisq;
    gsl_matrix *X, *cov;
    gsl_vector *y, *c;

    n = count;

    X = gsl_matrix_alloc (n, 3);
    y = gsl_vector_alloc (n);

    c = gsl_vector_alloc (3);
    cov = gsl_matrix_alloc (3, 3);

    for (i = 0; i < n; i++)
    {
        xi = f_data[i].x;
        yi = f_data[i].y;

        ////printf ("%g %g\n", xi, yi);

        gsl_matrix_set (X, i, 0, 1.0);
        gsl_matrix_set (X, i, 1, xi);
        gsl_matrix_set (X, i, 2, xi*xi);

        gsl_vector_set (y, i, yi);
    }

    gsl_multifit_linear_workspace * work
          = gsl_multifit_linear_alloc (n, 3);
    gsl_multifit_linear (X, y, c, cov,
                          &chisq, work);
    gsl_multifit_linear_free (work);

    //printf ("# best fit: Y = %g + %g X + %g X^2\n",
    //        C(0), C(1), C(2));

    //printf ("# covariance matrix:\n");
    //printf ("[ %+.5e, %+.5e, %+.5e  \n",
    //           COV(0,0), COV(0,1), COV(0,2));
    //printf ("  %+.5e, %+.5e, %+.5e  \n",
    //           COV(1,0), COV(1,1), COV(1,2));
    //printf ("  %+.5e, %+.5e, %+.5e ]\n",
    //           COV(2,0), COV(2,1), COV(2,2));
    //printf ("# chisq = %g\n", chisq);

    *aa = C(0);
    *bb = C(1);
    *cc = C(2);

    gsl_matrix_free (X);
    gsl_vector_free (y);
    gsl_vector_free (c);
    gsl_matrix_free (cov);

    return 0;
}
Exemple #8
0
QVector<Quadric2D> processa(const QMatrix4x4& vInverse)
{
    gsl_matrix * A = gsl_matrix_calloc (n, 3*5);
    real bary[3];

    for (int i = 0; i < n; ++i)
    {
        QVector4D b(points[0][i], points[1][i], 1.0, 1.0);
        b = vInverse * b;
        bary[0] = b.x();
        bary[1] = b.y();
        bary[2] = b.z();
        for (int j = 0; j < 3; ++j)
        {
            gsl_matrix_set (A, i, j*5    ,     points[0][i]*points[0][i]*bary[j]); //x^2
            gsl_matrix_set (A, i, j*5 + 1, 2.0*points[0][i]*points[1][i]*bary[j]); //2xy
            gsl_matrix_set (A, i, j*5 + 2, 2.0*points[0][i]             *bary[j]); //2x
            gsl_matrix_set (A, i, j*5 + 3,     points[1][i]*points[1][i]*bary[j]); //y^2
            gsl_matrix_set (A, i, j*5 + 4, 2.0*points[1][i]             *bary[j]); //2y
        }
    }

    gsl_matrix *cov = gsl_matrix_alloc (15, 15);
    gsl_vector * B = gsl_vector_alloc(n);
    gsl_vector * x = gsl_vector_alloc(15);
    gsl_vector_set_all(B, 1.0);

    gsl_multifit_linear_workspace * work = gsl_multifit_linear_alloc (n,15);
    real chisq = 0.0;
//    gsl_multifit_linear (A, B, x, cov, &chisq, work);
    real tol = 0.0001 ;
    size_t rank = 0 ;
    gsl_multifit_linear_svd( A,B, tol, &rank, x, cov, &chisq, work);
    gsl_multifit_linear_free (work);

    //qDebug() << chisq;
    //qDebug() << rank ;

    QVector<Quadric2D> resp;
    for(int i = 0; i < 3; ++i)
    {
        float x1 = gsl_vector_get(x, i*5);
        float x2 = gsl_vector_get(x, i*5 + 1);
        float x3 = gsl_vector_get(x, i*5 + 2);
        float x4 = gsl_vector_get(x, i*5 + 3);
        float x5 = gsl_vector_get(x, i*5 + 4);

        resp.push_back(Quadric2D(x1,x2,x3,x4,x5,-1.0));
    }

    gsl_matrix_free (A);
    gsl_vector_free (B);
    gsl_vector_free (x);
    gsl_matrix_free (cov);

    return resp;
}
void BSplineInterpolation::fitFromData(const Samples &samples) {

    /* preprocess samples and extract some info */
    Samples ssamples = samples;
    std::sort(ssamples.begin(), ssamples.end());
    const int numSamples = ssamples.size();
    const float minSampleX = ssamples[0].first;
    const float maxSampleX = ssamples.back().first;

    /* prepare fitting data */
    gsl_vector *x = gsl_vector_alloc(ssamples.size());
    gsl_vector *y = gsl_vector_alloc(ssamples.size());

    for (int i=0; i<ssamples.size(); i++) {
        gsl_vector_set(x, i, ssamples[i].first);
        gsl_vector_set(y, i, ssamples[i].second);
    }

    /* uniform knots distributed in sample range */
    gsl_bspline_knots_uniform(minSampleX, maxSampleX, bSplineWorkspace);

    /* construct a fit matrix */
    gsl_matrix *fitMatrix = gsl_matrix_alloc(numSamples, nCoeffs);
    for (int i=0; i<numSamples; i++) {
        /* compute B_j(xi) for all j */
        double xi = gsl_vector_get(x, i);
        gsl_bspline_eval(xi, bSpline, bSplineWorkspace);

        /* fill in row i */
        for (int j=0; j<nCoeffs; j++) {
            double Bj = gsl_vector_get(bSpline, j);
            gsl_matrix_set(fitMatrix, i, j, Bj);
        }
    }

    /* fit spline to data */
    gsl_multifit_linear_workspace *mws = 
        gsl_multifit_linear_alloc(numSamples, nCoeffs);
    double chisq;
    size_t rank;
    double tol = 0.1;
    gsl_multifit_linear(fitMatrix, y, cParameters, covMatrix, &chisq, mws);
    //gsl_multifit_linear_svd(fitMatrix, y, tol,
    //        &rank, cParameters, covMatrix, &chisq, mws);

    splineMinX = minSampleX;
    splineMaxX = maxSampleX;

    /* clean up */
    gsl_vector_free(x);
    gsl_vector_free(y);
    gsl_matrix_free(fitMatrix);
    gsl_multifit_linear_free(mws);
    
}
Exemple #10
0
Fichier : fit.c Projet : boada/ICD
int
fit(double image1[], double image2[], double error[], float factors[],
    int n)
{
/*
    if (gsl_fit_wlinear
	(image1, 1, error, 1, image2, 1, n, &beta, &alpha, &cov00, &cov01,
	 &cov11, &chisq)) {
	fprintf(stderr, "Linear Fitting Failed!\n");
	return (1);
    }

    factors[0] = alpha;
    factors[1] = beta;
*/
/*SECOND SET OF VARIABLES!!!*/
    int i;
    double chisq;
    gsl_matrix *X, *cov;
    gsl_vector *y, *w, *c;
	
    X = gsl_matrix_alloc(n, 2);
    y = gsl_vector_alloc(n);
    w = gsl_vector_alloc(n);
    c = gsl_vector_alloc(2);
    cov = gsl_matrix_alloc(2, 2);
	
    for (i = 0; i < n; i++) {
	gsl_matrix_set(X, i, 0, 1.0);
	gsl_matrix_set(X, i, 1, image1[i]);
	gsl_vector_set(y, i, image2[i]);
	gsl_vector_set(w, i, error[i]);
    }
	
    gsl_multifit_linear_workspace *work = gsl_multifit_linear_alloc(n, 2);
    gsl_multifit_wlinear(X, w, y, c, cov, &chisq, work);
    gsl_multifit_linear_free(work);

#define C(i) (gsl_vector_get(c,(i)))

//  printf("# best fit: Y = %g + %g X\n", C(0), C(1));

    gsl_matrix_free(X);
    gsl_vector_free(y);
    gsl_vector_free(w);
    gsl_vector_free(c);
    gsl_matrix_free(cov);

    factors[0] = C(1);
    factors[1] = C(0);
	return 0;
}
Exemple #11
0
const QVector<double> TimeSeriesMotion::baselineFit( const int term, const QVector<double> & series ) const
{
    Q_ASSERT(term >= 3);
    // Create the matrix of terms.  The first column is x_i^0 (1), second
    // column is x_i^1 (x), third is x_i^2, etc.
    gsl_matrix* X = gsl_matrix_alloc(series.size(), term);
    gsl_vector* y = gsl_vector_alloc(series.size());

    for (int i = 0; i < series.size(); ++i) {
        gsl_vector_set( y, i, series.at(i));

        for (int j = 0; j < term; ++j) {
            if ( j < 2 ) {
                // Don't use the first two terms in the fitting
                gsl_matrix_set(X, i, j, 0);
            } else {
                gsl_matrix_set(X, i, j, pow(m_timeStep * i, j));
            }
        }
    }

    // Co-variance matrix
    gsl_matrix * cov = gsl_matrix_alloc(term, term);

    // Coefficients
    gsl_vector * c = gsl_vector_alloc(term);

    // Fit the data series
    gsl_multifit_linear_workspace * work = gsl_multifit_linear_alloc(series.size(), term);

    double chisq = 0;
    gsl_multifit_linear(X, y, c, cov, &chisq, work);

    // Copy coefficients over to m_coeffs
    QVector<double> coeffs(term);

    for ( int i = 0; i < term; ++i )
        coeffs[i] = gsl_vector_get(c, i);

    // Clear the variables
    gsl_matrix_free(X);
    gsl_vector_free(y);
    gsl_vector_free(c);
    gsl_matrix_free(cov);
    
    gsl_multifit_linear_free (work);

    return coeffs;
}
Exemple #12
0
 gsl_vector* simpleFitting(gsl_matrix * A, gsl_vector * B)
{
    gsl_matrix *cov = gsl_matrix_alloc (A->size2, A->size2);
    gsl_vector * x = gsl_vector_alloc(A->size2);

    gsl_multifit_linear_workspace * work = gsl_multifit_linear_alloc (A->size1,A->size2);
    real chisq = 0.0;
    real tol = 0.000001 ;
    size_t rank = 0 ;
    gsl_multifit_linear_svd( A,B, tol, &rank, x, cov, &chisq, work);
    qDebug() << "rank: " << rank << ", chisq: " << chisq;
    //gsl_multifit_linear(A,B, x, cov, &chisq, work);
    gsl_multifit_linear_free (work);

    return x;
}
sonar_quadfit::sonar_quadfit(int nn)
{
	n=nn; //n needs to be odd!!!
	if(n%2 == 0)  //if not odd,  at least reduce it to something better
        {
            cerr<<"n = "<<n<<", which is not odd in quadfit!";
		n=n-1;
        }

	workspace = gsl_multifit_linear_alloc(n, 3);
	X = gsl_matrix_alloc(n, 3);
	for(int k=0;k<n; k++)
		gsl_matrix_set(X,k,0,1); //it is 1 for all cases
	c = gsl_vector_alloc(3);
	cov = gsl_matrix_alloc(3, 3);
	chisq = new double;
}
Exemple #14
0
/*
 * adapted from http://rosettacode.org/wiki/Polynomial_regression
 *
 * @return m_coeffs[0] + m_coeffs[1]*x + m_coeffs[2]*x^2 + ...
 *
 */
std::vector<double> polynomialfit(int degree, std::vector<double> dx,
		std::vector<double> dy) {

	std::vector<double> store(degree);
	gsl_multifit_linear_workspace *ws;
	gsl_matrix *cov, *X;
	gsl_vector *y, *c;
	double chisq;

	int i, j;

	if (dx.size() != dx.size())
		throw;

	int obs = dx.size(); // number of values

	X = gsl_matrix_alloc(obs, degree);
	y = gsl_vector_alloc(obs);
	c = gsl_vector_alloc(degree);
	cov = gsl_matrix_alloc(degree, degree);

	for (i = 0; i < obs; i++) {
		gsl_matrix_set(X, i, 0, 1.0);
		for (j = 0; j < degree; j++) {
			gsl_matrix_set(X, i, j, pow(dx[i], j));
		}
		gsl_vector_set(y, i, dy[i]);
	}

	ws = gsl_multifit_linear_alloc(obs, degree);
	gsl_multifit_linear(X, y, c, cov, &chisq, ws);

	/* store result ... */
	for (i = 0; i < degree; i++) {
		store[i] = gsl_vector_get(c, i);
	}

	gsl_multifit_linear_free(ws);
	gsl_matrix_free(X);
	gsl_matrix_free(cov);
	gsl_vector_free(y);
	gsl_vector_free(c);
	return store;
}
Exemple #15
0
QVector<Quadric2D> processaQUAD()
{
    gsl_matrix * A = gsl_matrix_alloc (n, 5);

    for (int i = 0; i < n; ++i)
    {
        gsl_matrix_set (A, i, 0,     points[0][i]*points[0][i]); //x^2
        gsl_matrix_set (A, i, 1, 2.0*points[0][i]*points[1][i]); //2xy
        gsl_matrix_set (A, i, 2, 2.0*points[0][i]             ); //2x
        gsl_matrix_set (A, i, 3,     points[1][i]*points[1][i]); //y^2
        gsl_matrix_set (A, i, 4, 2.0*points[1][i]             ); //2y
    }

    gsl_matrix *cov = gsl_matrix_alloc (5, 5);
    gsl_vector * B = gsl_vector_alloc(n);
    gsl_vector * x = gsl_vector_alloc(5);
    gsl_vector_set_all(B, 1.0);

    real chisq = 0.0;
    gsl_multifit_linear_workspace * work = gsl_multifit_linear_alloc (n,5);
    gsl_multifit_linear (A, B, x, cov, &chisq, work);
    gsl_multifit_linear_free (work);

    //qDebug() << chisq;

    QVector<Quadric2D> resp;

    float x1 = gsl_vector_get(x, 0);
    float x2 = gsl_vector_get(x, 1);
    float x3 = gsl_vector_get(x, 2);
    float x4 = gsl_vector_get(x, 3);
    float x5 = gsl_vector_get(x, 4);

    resp.push_back(Quadric2D(x1,x2,x3,x4,x5,-1.0));
    resp.push_back(Quadric2D(x1,x2,x3,x4,x5,-1.0));
    resp.push_back(Quadric2D(x1,x2,x3,x4,x5,-1.0));

    gsl_matrix_free (A);
    gsl_vector_free (B);
    gsl_vector_free (x);
    gsl_matrix_free (cov);

    return resp;
}
Exemple #16
0
void
linear_fit_quadratic(const std::vector<double> &Xin,
		     const std::vector<double> &Yin,
		     double &c_0, double &c_1, double &c_2)
{
  assert (Xin.size() == Yin.size());

  int i, n;
  double xi, yi, ei, chisq;
  gsl_matrix *X, *cov;
  gsl_vector *y, *c;
  
  n = Xin.size();     
  X = gsl_matrix_alloc (n, 3);
  y = gsl_vector_alloc (n);
  c = gsl_vector_alloc (3);
  cov = gsl_matrix_alloc (3, 3);
  
  for (i = 0; i < n; i++)
    {
      double xi = Xin[i], yi = Yin[i];
      gsl_matrix_set (X, i, 0, 1.0);
      gsl_matrix_set (X, i, 1, xi);
      gsl_matrix_set (X, i, 2, xi*xi);           
      gsl_vector_set (y, i, yi);
    }
  
  // do the actual fitting
  gsl_multifit_linear_workspace * work 
    = gsl_multifit_linear_alloc (n, 3);
  gsl_multifit_linear (X,  y, c, cov,
		       &chisq, work);
  gsl_multifit_linear_free (work);
  
  c_0 = gsl_vector_get(c,0);
  c_1 = gsl_vector_get(c,1);
  c_2 = gsl_vector_get(c,2);
  
  gsl_matrix_free (X);
  gsl_vector_free (y);
  gsl_vector_free (c);
  gsl_matrix_free (cov);
}
void PolynomialFit::fit()
{
    if (d_init_err)
        return;

	if (d_p > d_n){
  		QMessageBox::critical((ApplicationWindow *)parent(), tr("QtiPlot - Fit Error"),
  	    tr("You need at least %1 data points for this fit operation. Operation aborted!").arg(d_p));
  		return;
  	}

	gsl_matrix *X = gsl_matrix_alloc (d_n, d_p);

	for (int i = 0; i <d_n; i++){
		for (int j= 0; j < d_p; j++)
			gsl_matrix_set (X, i, j, pow(d_x[i],j));
	}

	gsl_vector_view y = gsl_vector_view_array (d_y, d_n);
	gsl_vector_view w = gsl_vector_view_array (d_w, d_n);
	gsl_multifit_linear_workspace * work = gsl_multifit_linear_alloc (d_n, d_p);

	if (d_weighting == NoWeighting)
		gsl_multifit_linear (X, &y.vector, d_param_init, covar, &chi_2, work);
	else
		gsl_multifit_wlinear (X, &w.vector, &y.vector, d_param_init, covar, &chi_2, work);

	for (int i = 0; i < d_p; i++)
		d_results[i] = gsl_vector_get(d_param_init, i);

	gsl_multifit_linear_free (work);
	gsl_matrix_free (X);

	generateFitCurve();

	if (show_legend)
		showLegend();

	ApplicationWindow *app = (ApplicationWindow *)parent();
	if (app->writeFitResultsToLog)
		app->updateLog(logFitInfo(0, 0));
}
Exemple #18
0
void gslpolyfit(double *x,double *y0,int n,int d,double *c0)

    {
#ifdef HAVE_GSL_LIB
    int i;
    double chisq;
    gsl_matrix *X,*cov;
    gsl_vector *y,*w,*c;
    gsl_multifit_linear_workspace *work;

    X=gsl_matrix_alloc(n,d+1);
    y=gsl_vector_alloc(n);
    w=gsl_vector_alloc(n);
    c=gsl_vector_alloc(d+1);
    cov=gsl_matrix_alloc(d+1,d+1);
    for (i=0;i<n;i++)
        {
        int j;
        double xi;

        for (j=0,xi=1.;j<=d;j++,xi*=x[i])
            gsl_matrix_set(X,i,j,xi);
        gsl_vector_set(y,i,y0[i]);
        gsl_vector_set(w,i,1.0);
        }
    work = gsl_multifit_linear_alloc(n,d+1);
    gsl_multifit_wlinear(X,w,y,c,cov,&chisq,work);
    gsl_multifit_linear_free(work);
    for (i=0;i<=d;i++)
        c0[i]=gsl_vector_get(c,i);
    gsl_matrix_free(cov);
    gsl_vector_free(c);
    gsl_vector_free(w);
    gsl_vector_free(y);
    gsl_matrix_free(X);
#else
    printf("\n\n\a*** Support for Gnu Scientic Library required but not available! ***\n\n"
           "*** Contact author. ***\n\n");
    exit(10);
#endif
    }
Exemple #19
0
// Linear 2D fit
void lfit2d(float *x,float *y,float *z,int n,float *a)
{
  int i,j,m;
  double chisq;
  gsl_matrix *X,*cov;
  gsl_vector *yy,*w,*c;

  X=gsl_matrix_alloc(n,3);
  yy=gsl_vector_alloc(n);
  w=gsl_vector_alloc(n);

  c=gsl_vector_alloc(3);
  cov=gsl_matrix_alloc(3,3);

  // Fill matrices
  for(i=0;i<n;i++) {
    gsl_matrix_set(X,i,0,1.0);
    gsl_matrix_set(X,i,1,x[i]);
    gsl_matrix_set(X,i,2,y[i]);
    
    gsl_vector_set(yy,i,z[i]);
    gsl_vector_set(w,i,1.0);
  }

  // Do fit
  gsl_multifit_linear_workspace *work=gsl_multifit_linear_alloc(n,3);
  gsl_multifit_wlinear(X,w,yy,c,cov,&chisq,work);
  gsl_multifit_linear_free(work);

  // Save parameters
  for (i=0;i<3;i++)
    a[i]=gsl_vector_get(c,(i));

  gsl_matrix_free(X);
  gsl_vector_free(yy);
  gsl_vector_free(w);
  gsl_vector_free(c);
  gsl_matrix_free(cov);

  return;
}
double *LinearModelFitTwoIndependentWeighted(int n, double *y, double *x1, double *x2, double *weights)
{
	#define NPARAMS 2

	// Allocate
	gsl_matrix *matrixX = gsl_matrix_alloc(n, NPARAMS);
	gsl_vector *vectorW = gsl_vector_alloc(n);
	gsl_vector *vectorY = gsl_vector_alloc(n);
	gsl_vector *vectorC = gsl_vector_alloc(1 + NPARAMS);

	// Copy data
	int i;
	for (i = 0; i < n; i++)
	{
		// NPARAMS
		gsl_matrix_set(matrixX, i, 0, x1[i]);
		gsl_matrix_set(matrixX, i, 1, x2[i]);
		gsl_vector_set(vectorW, i, weights[i]);
		gsl_vector_set(vectorY, i, y[i]);
	}

	
	// Compute
	gsl_multifit_linear_workspace *work = gsl_multifit_linear_alloc(n, NPARAMS);
	int ret = gsl_multifit_wlinear(matrixX, vectorW, vectorY, vectorC, /*gsl_matrix * cov*/ NULL, /*double * chisq*/ NULL, work);
	gsl_multifit_linear_free(work);

	static double coef[NPARAMS + 1];
	// NPARAMS+1
	coef[0] = gsl_vector_get(vectorC, 0);
	coef[1] = gsl_vector_get(vectorC, 1);
	coef[2] = gsl_vector_get(vectorC, 2);

	// Free
	gsl_matrix_free(matrixX);
	gsl_vector_free(vectorW);
	gsl_vector_free(vectorY);
	gsl_vector_free(vectorC);

	return coef;
}
Exemple #21
0
void MlSldaState::InitializeRegression() {
  regression_space_.space_.reset
    (gsl_multifit_linear_alloc(corpus_->num_train(), num_topics_),
     gsl_multifit_linear_free);
  regression_space_.covariance_.reset(gsl_matrix_alloc(num_topics_,
                                                       num_topics_),
                                      gsl_matrix_free);
  regression_space_.x_.reset(gsl_matrix_alloc(corpus_->num_train(),
                                              num_topics_),
                            gsl_matrix_free);
  // This initialization of chi_quared_ makes it so the first estimator of
  // sigma_squared_ is 1.0
  regression_space_.chi_squared_ = corpus_->num_train() - num_topics_;
  nu_.reset(gsl_vector_alloc(num_topics_));

  double increment = 2.0 / (double)num_topics_;
  double current_nu = -1.0;
  for (int ii = 0; ii < num_topics_; ++ii) {
    gsl_vector_set(nu_.get(), ii, current_nu);
    current_nu += increment;
  }
  sigma_squared_ = FLAGS_variance;
}
void linfit_order(int order, int n, float *x, float *y, float *w, float **params) {
    int i,j;
    double chisq;
    gsl_matrix *X, *cov;
    gsl_vector *Y, *W, *c;
    gsl_multifit_linear_workspace *work;

    X = gsl_matrix_alloc(n, order);
    Y = gsl_vector_alloc(n);
    W = gsl_vector_alloc(n);

    c = gsl_vector_alloc(order);
    cov = gsl_matrix_alloc(order, order);

    for (i=0; i<n; i++) {
        for (j=0; j<order; j++) {
            gsl_matrix_set(X, i, j, pow((double)x[i], (double)j));
        }
        gsl_vector_set(Y, i, (double)y[i]);
        gsl_vector_set(W, i, (double)w[i]);
    }

    work = gsl_multifit_linear_alloc(n, order);
    gsl_multifit_wlinear(X, W, Y, c, cov, &chisq, work);

    *params = malloc(order * sizeof(float));
    for (j=0; j<order; j++) {
        (*params)[j] = (float)(gsl_vector_get(c, j));
    }

    gsl_matrix_free(X);
    gsl_vector_free(Y);
    gsl_vector_free(W);
    gsl_vector_free(c);
    gsl_matrix_free(cov);
}
Exemple #23
0
pure_expr* wrap_gsl_multifit_linear(gsl_matrix* X, gsl_matrix* y)
{
  int i;
  double chisq;
  pure_expr *cx[X->size1];
  double *p;

  gsl_vector* c = gsl_vector_alloc(X->size1);
  gsl_vector* yt = gsl_vector_alloc(X->size1);
  gsl_matrix_get_row(yt, y, 0);
  gsl_matrix* cov = gsl_matrix_alloc(X->size1, X->size2);
  gsl_multifit_linear_workspace* w;
  w = gsl_multifit_linear_alloc(X->size1, X->size2);
  gsl_multifit_linear(X, yt, c, cov, &chisq, w);
  gsl_multifit_linear_free(w);
  gsl_vector_free(yt);
  p = c->data;
  for (i = 0; i < X->size1; ++i) {
    cx[i] = pure_double(*p);
    ++p;
  }
  return pure_listl(3, pure_matrix_columnsv(X->size1, cx),
		    pure_double_matrix(cov), pure_double(chisq));
}
Exemple #24
0
void
test_pontius ()
{
  size_t i, j;
  gsl_multifit_linear_workspace * work = 
    gsl_multifit_linear_alloc (pontius_n, pontius_p);

  gsl_multifit_robust_workspace * work_rob = 
    gsl_multifit_robust_alloc (gsl_multifit_robust_ols, pontius_n, pontius_p);

  gsl_matrix * X = gsl_matrix_alloc (pontius_n, pontius_p);
  gsl_vector_view y = gsl_vector_view_array (pontius_y, pontius_n);
  gsl_vector * c = gsl_vector_alloc (pontius_p);
  gsl_vector * r = gsl_vector_alloc (pontius_n);
  gsl_matrix * cov = gsl_matrix_alloc (pontius_p, pontius_p);

  double chisq, chisq_res;

  double expected_c[3] = { 0.673565789473684E-03,
                           0.732059160401003E-06,
                          -0.316081871345029E-14};

  double expected_sd[3] = { 0.107938612033077E-03,
                            0.157817399981659E-09,
                            0.486652849992036E-16 };

  double expected_chisq = 0.155761768796992E-05;

  gsl_vector_view diag = gsl_matrix_diagonal (cov);
  gsl_vector_view exp_c = gsl_vector_view_array(expected_c, pontius_p);
  gsl_vector_view exp_sd = gsl_vector_view_array(expected_sd, pontius_p);

  for (i = 0 ; i < pontius_n; i++) 
    {
      for (j = 0; j < pontius_p; j++) 
        {
          gsl_matrix_set(X, i, j, pow(pontius_x[i], j));
        }
    }

  /* test unweighted least squares */
  gsl_multifit_linear (X, &y.vector, c, cov, &chisq, work);
  gsl_multifit_linear_residuals(X, &y.vector, c, r);
  gsl_blas_ddot(r, r, &chisq_res);

  test_pontius_results("pontius gsl_multifit_linear",
                       c, &exp_c.vector,
                       &diag.vector, &exp_sd.vector,
                       chisq, chisq_res, expected_chisq);

  /* test robust least squares */
  gsl_multifit_robust (X, &y.vector, c, cov, work_rob);

  test_pontius_results("pontius gsl_multifit_robust",
                       c, &exp_c.vector,
                       &diag.vector, &exp_sd.vector,
                       1.0, 1.0, 1.0);

  /* test weighted least squares */
  {
    gsl_vector * w = gsl_vector_alloc (pontius_n);

    double expected_cov[3][3] ={ 
      {2.76754385964916e-01 , -3.59649122807024e-07,   9.74658869395731e-14},
      {-3.59649122807024e-07,   5.91630591630603e-13,  -1.77210703526497e-19},
      {9.74658869395731e-14,  -1.77210703526497e-19,   5.62573661988878e-26} };

    gsl_vector_set_all (w, 1.0);

    gsl_multifit_wlinear (X, w, &y.vector, c, cov, &chisq, work);
    gsl_multifit_linear_residuals(X, &y.vector, c, r);
    gsl_blas_ddot(r, r, &chisq_res);

    test_pontius_results("pontius gsl_multifit_wlinear",
                         c, &exp_c.vector,
                         NULL, NULL,
                         chisq, chisq_res, expected_chisq);

    for (i = 0; i < pontius_p; i++) 
      {
        for (j = 0; j < pontius_p; j++)
          {
            gsl_test_rel (gsl_matrix_get(cov,i,j), expected_cov[i][j], 1e-10, 
                          "pontius gsl_multifit_wlinear cov(%d,%d)", i, j) ;
          }
      }

    gsl_vector_free(w);
  }

  gsl_vector_free(c);
  gsl_vector_free(r);
  gsl_matrix_free(cov);
  gsl_matrix_free(X);
  gsl_multifit_linear_free (work);
  gsl_multifit_robust_free (work_rob);
}
Exemple #25
0
int
main (void)
{
  const size_t n = N;
  const size_t ncoeffs = NCOEFFS;
  const size_t nbreak = NBREAK;
  size_t i, j;
  gsl_bspline_workspace *bw;
  gsl_vector *B;
  double dy;
  gsl_rng *r;
  gsl_vector *c, *w;
  gsl_vector *x, *y;
  gsl_matrix *X, *cov;
  gsl_multifit_linear_workspace *mw;
  double chisq;
  double Rsq;
  double dof;

  gsl_rng_env_setup();
  r = gsl_rng_alloc(gsl_rng_default);

  /* allocate a cubic bspline workspace (k = 4) */
  bw = gsl_bspline_alloc(4, nbreak);
  B = gsl_vector_alloc(ncoeffs);

  x = gsl_vector_alloc(n);
  y = gsl_vector_alloc(n);
  X = gsl_matrix_alloc(n, ncoeffs);
  c = gsl_vector_alloc(ncoeffs);
  w = gsl_vector_alloc(n);
  cov = gsl_matrix_alloc(ncoeffs, ncoeffs);
  mw = gsl_multifit_linear_alloc(n, ncoeffs);

  printf("#m=0,S=0\n");
  /* this is the data to be fitted */
  for (i = 0; i < n; ++i)
    {
      double sigma;
      double xi = (15.0 / (N - 1)) * i;
      double yi = cos(xi) * exp(-0.1 * xi);

      sigma = 0.1 * yi;
      dy = gsl_ran_gaussian(r, sigma);
      yi += dy;

      gsl_vector_set(x, i, xi);
      gsl_vector_set(y, i, yi);
      gsl_vector_set(w, i, 1.0 / (sigma * sigma));

      printf("%f %f\n", xi, yi);
    }

  /* use uniform breakpoints on [0, 15] */
  gsl_bspline_knots_uniform(0.0, 15.0, bw);

  /* construct the fit matrix X */
  for (i = 0; i < n; ++i)
    {
      double xi = gsl_vector_get(x, i);

      /* compute B_j(xi) for all j */
      gsl_bspline_eval(xi, B, bw);

      /* fill in row i of X */
      for (j = 0; j < ncoeffs; ++j)
        {
          double Bj = gsl_vector_get(B, j);
          gsl_matrix_set(X, i, j, Bj);
        }
    }

  /* do the fit */
  gsl_multifit_wlinear(X, w, y, c, cov, &chisq, mw);

  dof = n - ncoeffs;
  Rsq = 1.0 - chisq / gsl_stats_wtss(w->data, 1, y->data, 1, y->size);

  fprintf(stderr, "chisq/dof = %e, Rsq = %f\n", chisq / dof, Rsq);

  /* output the smoothed curve */
  {
    double xi, yi, yerr;

    printf("#m=1,S=0\n");
    for (xi = 0.0; xi < 15.0; xi += 0.1)
      {
        gsl_bspline_eval(xi, B, bw);
        gsl_multifit_linear_est(B, c, cov, &yi, &yerr);
        printf("%f %f\n", xi, yi);
      }
  }

  gsl_rng_free(r);
  gsl_bspline_free(bw);
  gsl_vector_free(B);
  gsl_vector_free(x);
  gsl_vector_free(y);
  gsl_matrix_free(X);
  gsl_vector_free(c);
  gsl_vector_free(w);
  gsl_matrix_free(cov);
  gsl_multifit_linear_free(mw);

  return 0;
} /* main() */
Exemple #26
0
  void LowessSmoothing::smoothData(const DoubleVector & input_x, const DoubleVector & input_y, DoubleVector & smoothed_output)
  {
    if (input_x.size() != input_y.size())
    {
      throw Exception::InvalidValue(__FILE__, __LINE__, __PRETTY_FUNCTION__, "Sizes of x and y values not equal! Aborting... ", String(input_x.size()));
    }

    // unable to smooth over 2 or less data points (we need at least 3)
    if (input_x.size() <= 2)
    {
      smoothed_output = input_y;
      return;
    }

    Size input_size = input_y.size();
    // alpha_ = 1 / ( input_size / window_size_ );

    // const Size q = floor( input_size * alpha );
    const Size q = (window_size_ < input_size) ? window_size_ : input_size - 1;

    DoubleVector distances(input_size, 0.0);
    DoubleVector sortedDistances(input_size, 0.0);

    // DoubleVector smooth_yvals_Vec(input_size);

    gsl_matrix * X = gsl_matrix_alloc(input_size, 3);
    gsl_matrix * cov = gsl_matrix_alloc(3, 3);

    gsl_vector * weights = gsl_vector_alloc(input_size);
    gsl_vector * c = gsl_vector_alloc(3);
    gsl_vector * x = gsl_vector_alloc(3);
    gsl_vector * yvals_ = gsl_vector_alloc(input_size);

    DoubleReal y, yErr, chisq;

    // Setup the model matrix X for a quadratic fit.
    // yvals_ = new double[input_size];
    // Size idx = 0;

    for (Size p_idx = 0; p_idx < input_y.size(); ++p_idx)
    {
      DoubleReal rt = input_x[p_idx];

      gsl_matrix_set(X, p_idx, 0, 1.0);
      gsl_matrix_set(X, p_idx, 1, rt);
      gsl_matrix_set(X, p_idx, 2, rt * rt);

      gsl_vector_set(yvals_, p_idx, input_y[p_idx]);

      // ++idx;
    }



    //for(DoubleVector::const_iterator outer_peak_it = input_y.begin(); outer_peak_it != input_y.end(); ++outer_peak_it )
    for (Size outer_idx = 0; outer_idx < input_y.size(); ++outer_idx)
    {
      // Compute distances.
      // Size inner_idx = 0;
      for (Size inner_idx = 0; inner_idx < input_y.size(); ++inner_idx)
      {
        distances[inner_idx] = std::fabs(input_x[outer_idx] - input_x[inner_idx]);
        sortedDistances[inner_idx] = distances[inner_idx];
        // ++inner_idx;
      }

      // Sort distances in order from smallest to largest.
      // std::sort(sortedDistances, sortedDistances + input_size);
      std::sort(sortedDistances.begin(), sortedDistances.end());


      // Compute weights.
      for (Size inner_idx = 0; inner_idx < input_size; ++inner_idx)
      {
        gsl_vector_set(weights, inner_idx, tricube_(distances[inner_idx], sortedDistances[q]));
      }


      gsl_multifit_linear_workspace * work = gsl_multifit_linear_alloc(input_size, 3);
      gsl_multifit_wlinear(X, weights, yvals_, c, cov, &chisq, work);
      gsl_multifit_linear_free(work);


      DoubleReal rt = input_x[outer_idx];
      gsl_vector_set(x, 0, 1.0);
      gsl_vector_set(x, 1, rt);
      gsl_vector_set(x, 2, rt * rt);

      gsl_multifit_linear_est(x, c, cov, &y, &yErr);

      smoothed_output.push_back(y);
    }

    gsl_matrix_free(X);
    gsl_vector_free(weights);
    gsl_vector_free(c);
    gsl_matrix_free(cov);

    return;
  }
Exemple #27
0
int
main()
{
  const size_t n = 1000; /* number of observations */
  const size_t p = 2;    /* number of model parameters */
  size_t i;
  gsl_rng *r = gsl_rng_alloc(gsl_rng_default);
  gsl_matrix *X = gsl_matrix_alloc(n, p);
  gsl_vector *y = gsl_vector_alloc(n);

  for (i = 0; i < n; ++i)
    {
      /* generate first random variable u */
      double ui = 5.0 * gsl_ran_gaussian(r, 1.0);

      /* set v = u + noise */
      double vi = ui + gsl_ran_gaussian(r, 0.001);

      /* set y = u + v + noise */
      double yi = ui + vi + gsl_ran_gaussian(r, 1.0);

      /* since u =~ v, the matrix X is ill-conditioned */
      gsl_matrix_set(X, i, 0, ui);
      gsl_matrix_set(X, i, 1, vi);

      /* rhs vector */
      gsl_vector_set(y, i, yi);
    }

  {
    const size_t nL = 200;                   /* number of points on L-curve */
    gsl_multifit_linear_workspace *w =
      gsl_multifit_linear_alloc(n, p);
    gsl_vector *c = gsl_vector_alloc(p);     /* OLS solution */
    gsl_vector *c_reg = gsl_vector_alloc(p); /* regularized solution */
    gsl_vector *reg_param = gsl_vector_alloc(nL);
    gsl_vector *rho = gsl_vector_alloc(nL);  /* residual norms */
    gsl_vector *eta = gsl_vector_alloc(nL);  /* solution norms */
    double lambda;                           /* optimal regularization parameter */
    size_t reg_idx;                          /* index of optimal lambda */
    double chisq, rnorm, snorm;

    /* compute SVD of X */
    gsl_multifit_linear_svd(X, w);

    /* unregularized (standard) least squares fit, lambda = 0 */
    gsl_multifit_linear_solve(0.0, X, y, c, &rnorm, &snorm, w);
    chisq = pow(rnorm, 2.0);

    fprintf(stderr, "=== Unregularized fit ===\n");
    fprintf(stderr, "best fit: y = %g u + %g v\n",
      gsl_vector_get(c, 0), gsl_vector_get(c, 1));
    fprintf(stderr, "chisq/dof = %g\n", chisq / (n - p));

    /* calculate L-curve and find its corner */
    gsl_multifit_linear_lcurve(y, reg_param, rho, eta, w);
    gsl_multifit_linear_lcorner(rho, eta, &reg_idx);

    /* store optimal regularization parameter */
    lambda = gsl_vector_get(reg_param, reg_idx);

    /* output L-curve */
    for (i = 0; i < nL; ++i)
      printf("%f %f\n", gsl_vector_get(rho, i), gsl_vector_get(eta, i));

    /* output L-curve corner point */
    printf("\n\n%f %f\n",
           gsl_vector_get(rho, reg_idx),
           gsl_vector_get(eta, reg_idx));

    /* regularize with lambda */
    gsl_multifit_linear_solve(lambda, X, y, c_reg, &rnorm, &snorm, w);
    chisq = pow(rnorm, 2.0) + pow(lambda * snorm, 2.0);

    fprintf(stderr, "=== Regularized fit ===\n");
    fprintf(stderr, "optimal lambda: %g\n", lambda);
    fprintf(stderr, "best fit: y = %g u + %g v\n",
            gsl_vector_get(c_reg, 0), gsl_vector_get(c_reg, 1));
    fprintf(stderr, "chisq/dof = %g\n", chisq / (n - p));

    gsl_multifit_linear_free(w);
    gsl_vector_free(c);
    gsl_vector_free(c_reg);
    gsl_vector_free(reg_param);
    gsl_vector_free(rho);
    gsl_vector_free(eta);
  }

  gsl_rng_free(r);
  gsl_matrix_free(X);
  gsl_vector_free(y);

  return 0;
}
// ${LSHKIT_HOME}/tools/fitdata.cpp
void fitdata_example()
{
    const std::string data_file("./data/search_algorithm/lshkit/audio.data");
    const unsigned N = 0;  // number of points to use.
    const unsigned P = 50000;  // number of pairs to sample.
    unsigned Q = 1000;  // number of queries to sample.
    unsigned K = 100;  // search for K nearest neighbors.
    const unsigned F = 10;  // divide the sample to F folds.

    // load matrix.
    lshkit::Matrix<float> data(data_file);

    std::vector<unsigned> idx(data.getSize());
    for (unsigned i = 0; i < idx.size(); ++i) idx[i] = i;
    random_shuffle(idx.begin(), idx.end());

    if (N > 0 && N < data.getSize()) idx.resize(N);

    lshkit::metric::l2sqr<float> l2sqr(data.getDim());

    lshkit::DefaultRng rng;
    boost::variate_generator<lshkit::DefaultRng &, lshkit::UniformUnsigned> gen(rng, lshkit::UniformUnsigned(0, idx.size()-1));

    double gM = 0.0;
    double gG = 0.0;
    {
        // sample P pairs of points
        for (unsigned k = 0; k < P; ++k)
        {
            double dist, logdist;
            for (;;)
            {
                unsigned i = gen();
                unsigned j = gen();
                if (i == j) continue;
                dist = l2sqr(data[idx[i]], data[idx[j]]);
                logdist = std::log(dist);
                if (local::is_good_value(logdist)) break;
            }
            gM += dist;
            gG += logdist;
        }
        gM /= P;
        gG /= P;
        gG = std::exp(gG);
    }

    if (Q > idx.size()) Q = idx.size();
    if (K > idx.size() - Q) K = idx.size() - Q;
    // sample query.
    std::vector<unsigned> qry(Q);

    lshkit::SampleQueries(&qry, idx.size(), rng);

    // do the queries.
    std::vector<lshkit::Topk<unsigned> > topks(Q);
    for (unsigned i = 0; i < Q; ++i) topks[i].reset(K);

    /* ... */
    gsl_matrix *X = gsl_matrix_alloc(F * K, 3);
    gsl_vector *yM = gsl_vector_alloc(F * K);
    gsl_vector *yG = gsl_vector_alloc(F * K);
    gsl_vector *pM = gsl_vector_alloc(3);
    gsl_vector *pG = gsl_vector_alloc(3);
    gsl_matrix *cov = gsl_matrix_alloc(3,3);

    std::vector<double> M(K);
    std::vector<double> G(K);

    boost::progress_display progress(F, std::cerr);
    unsigned m = 0;
    for (unsigned l = 0; l < F; l++)
    {
        // Scan
        for (unsigned i = l; i< idx.size(); i += F)
        {
            for (unsigned j = 0; j < Q; j++)
            {
                int id = qry[j];
                if (i != id)
                {
                    float d = l2sqr(data[idx[id]], data[idx[i]]);
                    if (local::is_good_value(std::log(double(d)))) topks[j] << lshkit::Topk<unsigned>::Element(i, d);
                }
            }
        }

        std::fill(M.begin(), M.end(), 0.0);
        std::fill(G.begin(), G.end(), 0.0);

        for (unsigned i = 0; i < Q; i++)
        {
            for (unsigned k = 0; k < K; k++)
            {
                M[k] += topks[i][k].dist;
                G[k] += std::log(topks[i][k].dist);
            }
        }

        for (unsigned k = 0; k < K; k++)
        {
            M[k] = std::log(M[k]/Q);
            G[k] /= Q;
            gsl_matrix_set(X, m, 0, 1.0);
            gsl_matrix_set(X, m, 1, std::log(double(data.getSize() * (l + 1)) / double(F)));
            gsl_matrix_set(X, m, 2, std::log(double(k + 1)));
            gsl_vector_set(yM, m, M[k]);
            gsl_vector_set(yG, m, G[k]);
            ++m;
        }

        ++progress;
    }

    gsl_multifit_linear_workspace *work = gsl_multifit_linear_alloc(F * K, 3);

    double chisq;

    gsl_multifit_linear(X, yM, pM, cov, &chisq, work);
    gsl_multifit_linear(X, yG, pG, cov, &chisq, work);

    std::cout << gM << '\t' << gG << std::endl;
    std::cout << gsl_vector_get(pM, 0) << '\t'
         << gsl_vector_get(pM, 1) << '\t'
         << gsl_vector_get(pM, 2) << std::endl;
    std::cout << gsl_vector_get(pG, 0) << '\t'
         << gsl_vector_get(pG, 1) << '\t'
         << gsl_vector_get(pG, 2) << std::endl;

    gsl_matrix_free(X);
    gsl_matrix_free(cov);
    gsl_vector_free(pM);
    gsl_vector_free(pG);
    gsl_vector_free(yM);
    gsl_vector_free(yG);
}
bool Reference::recalculateStationHeadingCurvature()
{
    if (this->numOfPoints <= 1) { return false; }

    // Recalculate s
    for(int i = 0; i < this->numOfPoints ; i++) {
        if(i == 0) { this->s[0] = 0; }
        else {
            double ds = hypot(this->x[i] - this->x[i-1], this->y[i] - this->y[i-1]);
            this->s[i] = this->s[i-1] + ds;
        }
    }

    // Recalculate theta, k and dk
    if(this->numOfPoints < NUM_FIT_FRONT + NUM_FIT_BACK + 1) {
        int i = 0;
        for( i = 0; i < this->numOfPoints; i++) {
            if(i == this->numOfPoints - 1) {
                this->theta[i] = this->theta[i-1];
                this->k[i] = 0;
                break;
            }
            this->theta[i] = atan2(this->y[i+1] - this->y[i], this->x[i+1] - this->x[i]);
            this->k[i] = 0;
        }
    }
    else {
        for(int i = 0; i < this->numOfPoints; i++) {
            int id0 = (i-NUM_FIT_FRONT >= 0) ? (i-NUM_FIT_FRONT):(0);
            int id1 = (i+NUM_FIT_BACK < this->numOfPoints) ? (i+NUM_FIT_BACK):(this->numOfPoints-1);
            double si, xi, yi, /*ei,*/ chisq;

            gsl_matrix *S, *cov;
            gsl_vector *x, *y, *w, *cx, *cy;

            int n = id1-id0+1;
            S = gsl_matrix_alloc (n, 3);
            x = gsl_vector_alloc (n);
            y = gsl_vector_alloc (n);
            w = gsl_vector_alloc (n);

            cx = gsl_vector_alloc (3);
            cy = gsl_vector_alloc (3);
            cov = gsl_matrix_alloc (3, 3);

            for (int j = 0; j < n; j++) {
                si = this->s[id0+j];
                xi = this->x[id0+j];
                yi = this->y[id0+j];

                gsl_matrix_set (S, j, 0, 1.0);
                gsl_matrix_set (S, j, 1, si);
                gsl_matrix_set (S, j, 2, si*si);

                gsl_vector_set (x, j, xi);
                gsl_vector_set (y, j, yi);
                gsl_vector_set (w, j, 1.0);
            }

            gsl_multifit_linear_workspace * work = gsl_multifit_linear_alloc (n, 3);
            gsl_multifit_wlinear (S, w, x, cx, cov, &chisq, work);
            gsl_multifit_linear_free (work);

            work = gsl_multifit_linear_alloc (n, 3);
            gsl_multifit_wlinear (S, w, y, cy, cov, &chisq, work);
            gsl_multifit_linear_free (work);

#define Cx(i) (gsl_vector_get(cx,(i)))
#define Cy(i) (gsl_vector_get(cy,(i)))

            double s_ = this->s[i];
            //        double x_ = Cx(2) * s_ * s_ + Cx(1) * s_ + Cx(0);
            double xd_ = 2 * Cx(2) * s_ + Cx(1);
            double xdd_ = 2 * Cx(2);
            //        double y_ = Cy(2) * s_ * s_ + Cy(1) * s_ + Cy(0);
            double yd_ = 2 * Cy(2) * s_ + Cy(1);
            double ydd_ = 2 * Cy(2);

            this->theta[i] = atan2(yd_, xd_);
            this->k[i] = (xd_ * ydd_ - yd_ * xdd_)
                    / ( sqrt( (xd_*xd_ + yd_*yd_)*(xd_*xd_ + yd_*yd_)*(xd_*xd_ + yd_*yd_) ) );

            gsl_matrix_free(S);
            gsl_vector_free (x);
            gsl_vector_free (y);
            gsl_vector_free (w);

            gsl_vector_free (cx);
            gsl_vector_free (cy);
            gsl_matrix_free (cov);
        }
    }

    return true;
}
Exemple #30
0
/** Executes the algorithm
 *
 */
void SplineBackground::exec()
{

  API::MatrixWorkspace_sptr inWS = getProperty("InputWorkspace");
  int spec = getProperty("WorkspaceIndex");

  if (spec > static_cast<int>(inWS->getNumberHistograms()))
    throw std::out_of_range("WorkspaceIndex is out of range.");

  const MantidVec& X = inWS->readX(spec);
  const MantidVec& Y = inWS->readY(spec);
  const MantidVec& E = inWS->readE(spec);
  const bool isHistogram = inWS->isHistogramData();

  const int ncoeffs = getProperty("NCoeff");
  const int k = 4; // order of the spline + 1 (cubic)
  const int nbreak = ncoeffs - (k - 2);

  if (nbreak <= 0)
    throw std::out_of_range("Too low NCoeff");

  gsl_bspline_workspace *bw;
  gsl_vector *B;

  gsl_vector *c, *w, *x, *y;
  gsl_matrix *Z, *cov;
  gsl_multifit_linear_workspace *mw;
  double chisq;

  int n = static_cast<int>(Y.size());
  bool isMasked = inWS->hasMaskedBins(spec);
  std::vector<int> masked(Y.size());
  if (isMasked)
  {
    for(API::MatrixWorkspace::MaskList::const_iterator it=inWS->maskedBins(spec).begin();it!=inWS->maskedBins(spec).end();++it)
      masked[it->first] = 1;
    n -= static_cast<int>(inWS->maskedBins(spec).size());
  }

  if (n < ncoeffs)
  {
    g_log.error("Too many basis functions (NCoeff)");
    throw std::out_of_range("Too many basis functions (NCoeff)");
  }

  /* allocate a cubic bspline workspace (k = 4) */
  bw = gsl_bspline_alloc(k, nbreak);
  B = gsl_vector_alloc(ncoeffs);

  x = gsl_vector_alloc(n);
  y = gsl_vector_alloc(n);
  Z = gsl_matrix_alloc(n, ncoeffs);
  c = gsl_vector_alloc(ncoeffs);
  w = gsl_vector_alloc(n);
  cov = gsl_matrix_alloc(ncoeffs, ncoeffs);
  mw = gsl_multifit_linear_alloc(n, ncoeffs);

  /* this is the data to be fitted */
  int j = 0;
  for (MantidVec::size_type i = 0; i < Y.size(); ++i)
  {
    if (isMasked && masked[i]) continue;
    gsl_vector_set(x, j, (isHistogram ? (0.5*(X[i]+X[i+1])) : X[i])); // Middle of the bins, if a histogram
    gsl_vector_set(y, j, Y[i]);
    gsl_vector_set(w, j, E[i]>0.?1./(E[i]*E[i]):0.);

    ++j;
  }

  if (n != j)
  {
    gsl_bspline_free(bw);
    gsl_vector_free(B);
    gsl_vector_free(x);
    gsl_vector_free(y);
    gsl_matrix_free(Z);
    gsl_vector_free(c);
    gsl_vector_free(w);
    gsl_matrix_free(cov);
    gsl_multifit_linear_free(mw);

    throw std::runtime_error("Assertion failed: n != j");
  }

  double xStart = X.front();
  double xEnd =   X.back();

  /* use uniform breakpoints */
  gsl_bspline_knots_uniform(xStart, xEnd, bw);

  /* construct the fit matrix X */
  for (int i = 0; i < n; ++i)
  {
    double xi=gsl_vector_get(x, i);

    /* compute B_j(xi) for all j */
    gsl_bspline_eval(xi, B, bw);

    /* fill in row i of X */
    for (j = 0; j < ncoeffs; ++j)
    {
      double Bj = gsl_vector_get(B, j);
      gsl_matrix_set(Z, i, j, Bj);
    }
  }

  /* do the fit */
  gsl_multifit_wlinear(Z, w, y, c, cov, &chisq, mw);

  /* output the smoothed curve */
  API::MatrixWorkspace_sptr outWS = WorkspaceFactory::Instance().create(inWS,1,X.size(),Y.size());
  {
    outWS->getAxis(1)->setValue(0, inWS->getAxis(1)->spectraNo(spec));
    double xi, yi, yerr;
    for (MantidVec::size_type i=0;i<Y.size();i++)
    {
      xi = X[i];
      gsl_bspline_eval(xi, B, bw);
      gsl_multifit_linear_est(B, c, cov, &yi, &yerr);
      outWS->dataY(0)[i] = yi;
      outWS->dataE(0)[i] = yerr;
    }
    outWS->dataX(0) = X;
  }

  gsl_bspline_free(bw);
  gsl_vector_free(B);
  gsl_vector_free(x);
  gsl_vector_free(y);
  gsl_matrix_free(Z);
  gsl_vector_free(c);
  gsl_vector_free(w);
  gsl_matrix_free(cov);
  gsl_multifit_linear_free(mw);

  setProperty("OutputWorkspace",outWS);

}