int test_beta(gsl_vector *obs, gsl_vector *expected, gsl_matrix *A, gsl_matrix *B, const char *obsname, const char *expname) { size_t N = expected->size; size_t i, k; double max, max_abserr, max_relerr; max = 0.0; max_abserr = 0.0; max_relerr = 0.0; k = 0; for (i = 0; i < N; ++i) { double z = gsl_vector_get(expected, i); max = GSL_MAX_DBL(max, fabs(z)); } for (i = 0; i < N; ++i) { double v_obs = gsl_vector_get(obs, i); double v_exp = gsl_vector_get(expected, i); double abserr = fabs(v_obs - v_exp); double noise = max * GSL_DBL_EPSILON * N * N; max_abserr = GSL_MAX_DBL(max_abserr, abserr); if (abserr < noise) continue; if (abserr > 1.0e-6) ++k; } if (k) { printf("==== CASE %lu ===========================\n\n", count); print_matrix(A, "A"); print_matrix(B, "B"); printf("=== beta - %s ===\n", expname); printf("%s = [\n", expname); gsl_vector_fprintf(stdout, expected, "%.12e"); printf("]\n"); printf("=== beta - %s ===\n", obsname); printf("%s = [\n", obsname); gsl_vector_fprintf(stdout, obs, "%.12e"); printf("]\n"); printf("max abserr = %g max relerr = %g\n", max_abserr, max_relerr); printf("=========================================\n\n"); } return k; } /* test_beta() */
int test_f(const char * desc, gsl_multimin_function *f, initpt_function initpt, const gsl_multimin_fminimizer_type *T) { int status; size_t i, iter = 0; gsl_vector *x = gsl_vector_alloc (f->n); gsl_vector *step_size = gsl_vector_alloc (f->n); gsl_multimin_fminimizer *s; fcount = 0; gcount = 0; (*initpt) (x); for (i = 0; i < f->n; i++) gsl_vector_set (step_size, i, 1); s = gsl_multimin_fminimizer_alloc(T, f->n); gsl_multimin_fminimizer_set (s, f, x, step_size); #ifdef DEBUG printf("x "); gsl_vector_fprintf (stdout, s->x, "%g"); #endif do { iter++; status = gsl_multimin_fminimizer_iterate(s); #ifdef DEBUG printf("%i: \n",iter); printf("x "); gsl_vector_fprintf (stdout, s->x, "%g"); printf("f(x) %g\n", gsl_multimin_fminimizer_minimum (s)); printf("size: %g\n", gsl_multimin_fminimizer_size (s)); printf("\n"); #endif status = gsl_multimin_test_size (gsl_multimin_fminimizer_size (s), 1e-3); } while (iter < 5000 && status == GSL_CONTINUE); status |= (fabs(s->fval) > 1e-5); gsl_test(status, "%s, on %s: %d iter (fn=%d), f(x)=%g", gsl_multimin_fminimizer_name(s),desc, iter, fcount, s->fval); gsl_multimin_fminimizer_free(s); gsl_vector_free(x); gsl_vector_free(step_size); return status; }
int test_fdf(const char * desc, gsl_multimin_function_fdf *f, initpt_function initpt, const gsl_multimin_fdfminimizer_type *T) { int status; size_t iter = 0; double step_size; gsl_vector *x = gsl_vector_alloc (f->n); gsl_multimin_fdfminimizer *s; fcount = 0; gcount = 0; (*initpt) (x); step_size = 0.1 * gsl_blas_dnrm2 (x); s = gsl_multimin_fdfminimizer_alloc(T, f->n); gsl_multimin_fdfminimizer_set (s, f, x, step_size, 0.1); #ifdef DEBUG printf("x "); gsl_vector_fprintf (stdout, s->x, "%g"); printf("g "); gsl_vector_fprintf (stdout, s->gradient, "%g"); #endif do { iter++; status = gsl_multimin_fdfminimizer_iterate(s); #ifdef DEBUG printf("%i: \n",iter); printf("x "); gsl_vector_fprintf (stdout, s->x, "%g"); printf("g "); gsl_vector_fprintf (stdout, s->gradient, "%g"); printf("f(x) %g\n",s->f); printf("dx %g\n",gsl_blas_dnrm2(s->dx)); printf("\n"); #endif status = gsl_multimin_test_gradient(s->gradient,1e-3); } while (iter < 5000 && status == GSL_CONTINUE); status |= (fabs(s->f) > 1e-5); gsl_test(status, "%s, on %s: %i iters (fn+g=%d+%d), f(x)=%g", gsl_multimin_fdfminimizer_name(s),desc, iter, fcount, gcount, s->f); gsl_multimin_fdfminimizer_free(s); gsl_vector_free(x); return status; }
void find_eigens2(gsl_matrix *m, gsl_vector *eval,gsl_matrix *evec) { gsl_eigen_symmv_workspace * w = gsl_eigen_symmv_alloc (3); gsl_eigen_symmv (m, eval, evec, w); gsl_eigen_symmv_free (w); gsl_eigen_symmv_sort (eval, evec,GSL_EIGEN_SORT_ABS_ASC); { int i; for (i = 0; i < 3; i++) { double eval_i= gsl_vector_get (eval, i); gsl_vector_view evec_i= gsl_matrix_column (evec, i); gsl_vector_fprintf (stdout,&evec_i.vector, "%g"); } } gsl_vector_free (eval); gsl_matrix_free (evec); }
void printf_vector(const char* filename, gsl_vector* v) { FILE* fileptr; fileptr = fopen(filename, "w"); gsl_vector_fprintf(fileptr, v, "%f"); fclose(fileptr); }
int pca_write_S(const char *filename, const size_t nmax, const size_t mmax, const double freq_cpd, const double window_size, const double window_shift, const gsl_vector *S) { int s = 0; FILE *fp; fp = fopen(filename, "w"); if (!fp) { fprintf(stderr, "pca_write_S: unable to open %s: %s\n", filename, strerror(errno)); return -1; } fprintf(fp, "%% Singular values\n"); fprintf(fp, "%% nmax: %zu\n", nmax); fprintf(fp, "%% mmax: %zu\n", mmax); fprintf(fp, "%% Frequency: %.6f [cpd]\n", freq_cpd); fprintf(fp, "%% window size: %g [days]\n", window_size); fprintf(fp, "%% window slide: %g [days]\n", window_shift); gsl_vector_fprintf(fp, S, "%.12e"); fclose(fp); return s; }
int main () { double a_data[] = { 0.18, 0.60, 0.57, 0.96, 0.41, 0.24, 0.99, 0.58, 0.14, 0.30, 0.97, 0.66, 0.51, 0.13, 0.19, 0.85 }; double b_data[] = { 1.0, 2.0, 3.0, 4.0 }; gsl_matrix_view m = gsl_matrix_view_array (a_data, 4, 4); gsl_vector_view b = gsl_vector_view_array (b_data, 4); gsl_vector *x = gsl_vector_alloc (4); int s; gsl_permutation * p = gsl_permutation_alloc (4); gsl_linalg_LU_decomp (&m.matrix, p, &s); gsl_linalg_LU_solve (&m.matrix, p, &b.vector, x); printf ("x = \n"); gsl_vector_fprintf (stdout, x, "%g"); gsl_permutation_free (p); gsl_vector_free (x); return 0; }
void population_fprintf (const Population *pop, FILE *stream) { int i; for (i = 0; i < pop->n_e; i++){ gsl_vector_fprintf(stream, pop->y[i], "%f"); gsl_matrix_fprintf(stream, pop->b[i], "%f"); } fprintf(stream, "%d", pop->current_gen); }
/** *Displays the content of a tracestruct structure to *FILE */ void tracestruct_fprintf(FILE * file, tracestruct * trace) { fprintf(file, "Trace ID: %d\n", trace->ID); fprintf(file, "Trace detector location: %f %f\n", trace->cpoint.x, trace->cpoint.y); gsl_vector_fprintf(file, trace->pol, "Trace pol: %f"); fprintf(file, "Trace xoff: %f\n", trace->offset.x); fprintf(file, "Trace yoff: %f\n", trace->offset.y); fprintf(file, "Trace file: %s\n", trace->file); }
void vct_fprintf(const char* filename, gsl_vector* v) { // outlog( "writing %ld vector to %s", v->size, filename); FILE* fileptr; fileptr = fopen(filename, "w"); if (!fileptr) { outlog("Error opening file %s. Failing.", filename); exit(1); } gsl_vector_fprintf(fileptr, v, "%20.17e"); fclose(fileptr); }
int save_vector(gsl_vector *v, const char *file){ FILE *f = fopen(file, "w+"); if(f){ gsl_vector_fprintf(f, v, "%f"); } else{ perror("fopen"); return EXIT_FAILURE; } return EXIT_SUCCESS; }
int PyGSL_multiroot_function_wrap(const gsl_vector *x, void *params, gsl_vector *f) { int flag; PyGSL_solver *p = (PyGSL_solver *) params; FUNC_MESS_BEGIN(); if(PyGSL_DEBUG_LEVEL() > 2){ gsl_vector_fprintf(stderr, x, "x = %d"); } flag = PyGSL_function_wrap_Op_On(x, f, p->cbs[0], p->args, x->size, x->size, __FUNCTION__); FUNC_MESS_END(); return flag; }
int main() { int i,j; srand(42); for (i=0;i<dimension;i++) { for (j=0;j<dimension;j++) { a_data[i*dimension+j]=(rand()%100)/100.0; /* if ((rand()%2)) a_data[i*dimension+j]+=0.2; else a_data[i*dimension+j]-=0.5; //printf("%g ",a_data[i*dimension+j]); */ } //printf("\n"); b_data[i]=(rand()%15)+4; } gsl_matrix_view m = gsl_matrix_view_array (a_data, dimension, dimension); gsl_vector_view b = gsl_vector_view_array (b_data, dimension); gsl_vector *x = gsl_vector_alloc (dimension); int s; gsl_permutation * p = gsl_permutation_alloc (dimension); gsl_linalg_LU_decomp (&m.matrix, p, &s); gsl_linalg_LU_solve (&m.matrix, p, &b.vector, x); if (PRINT_RES) { printf ("x = \n"); gsl_vector_fprintf (stdout, x, "%g"); } gsl_permutation_free (p); gsl_vector_free (x); return 0; }
int main (void) { double data[] = { 1.0 , 1/2.0, 1/3.0, 1/4.0, 1/2.0, 1/3.0, 1/4.0, 1/5.0, 1/3.0, 1/4.0, 1/5.0, 1/6.0, 1/4.0, 1/5.0, 1/6.0, 1/7.0 }; gsl_matrix_view m = gsl_matrix_view_array (data, 4, 4); gsl_vector *eval = gsl_vector_alloc (4); gsl_matrix *evec = gsl_matrix_alloc (4, 4); gsl_eigen_symmv_workspace * w = gsl_eigen_symmv_alloc (4); gsl_eigen_symmv (&m.matrix, eval, evec, w); gsl_eigen_symmv_free (w); gsl_eigen_symmv_sort (eval, evec, GSL_EIGEN_SORT_ABS_ASC); { int i; for (i = 0; i < 4; i++) { double eval_i = gsl_vector_get (eval, i); gsl_vector_view evec_i = gsl_matrix_column (evec, i); printf ("eigenvalue = %g\n", eval_i); printf ("eigenvector = \n"); gsl_vector_fprintf (stdout, &evec_i.vector, "%g"); } } gsl_vector_free (eval); gsl_matrix_free (evec); return 0; }
int main(int argc, char * argv[]) { gsl_vector * vec = gsl_vector_calloc(3); gsl_vector_set(vec, 0, 10.0); gsl_vector_set(vec, 1, 20.0); gsl_vector_set(vec, 2, 30.0); int i = 0; for(i=0 ; i<3 ; i++) fprintf(stdout, "%f\n", gsl_vector_get(vec, i)); gsl_vector_fprintf(stdout, vec, "%f"); gsl_vector_free(vec); exit(EXIT_SUCCESS); }
int main() { const gsl_rng_type* T; gsl_rng* r; gsl_vector* v; v = gsl_vector_alloc(NUM); gsl_rng_env_setup(); T = gsl_rng_mt19937; r = gsl_rng_alloc(T); int i; for(i=0; i<NUM; i++) { // double tmp = gsl_rng_uniform(r); double tmp = gsl_ran_gaussian(r, 2); gsl_vector_set(v, i, tmp); } FILE* f = fopen("./vecV", "w"); gsl_vector_fprintf(f, v, "%f"); fclose(f); printf("Done.\n"); gsl_rng_free(r); }
double siman(gsl_vector * vec, void * params, gsl_rng * rng) { block * myblock = block_alloc(vec->size); gsl_vector_memcpy(myblock->vec, vec); myblock->ptr = params; gsl_siman_params_t siman_params = {N_TRIES, ITERS_FIXED_T, STEP_SIZE, K, T_INITIAL, MU_T, T_MIN}; gsl_siman_solve(rng, myblock, E1, S1, M1, P1, block_copy, block_copy_construct, block_destroy, 0, siman_params); gsl_vector_fprintf(stdout, myblock->vec, "%g"); printf("siman llik: %g\n", -E1(myblock) ); P1(myblock); return -E1(myblock); }
static int iterate (void *vstate, gsl_multifit_function_fdf * fdf, gsl_vector * x, gsl_vector * f, gsl_matrix * J, gsl_vector * dx, int scale) { lmder_state_t *state = (lmder_state_t *) vstate; gsl_matrix *r = state->r; gsl_vector *tau = state->tau; gsl_vector *diag = state->diag; gsl_vector *qtf = state->qtf; gsl_vector *x_trial = state->x_trial; gsl_vector *f_trial = state->f_trial; gsl_vector *rptdx = state->rptdx; gsl_vector *newton = state->newton; gsl_vector *gradient = state->gradient; gsl_vector *sdiag = state->sdiag; gsl_vector *w = state->w; gsl_vector *work1 = state->work1; gsl_permutation *perm = state->perm; double prered, actred; double pnorm, fnorm1, fnorm1p, gnorm; double ratio; double dirder; int iter = 0; double p1 = 0.1, p25 = 0.25, p5 = 0.5, p75 = 0.75, p0001 = 0.0001; if (state->fnorm == 0.0) { return GSL_SUCCESS; } /* Compute qtf = Q^T f */ gsl_vector_memcpy (qtf, f); gsl_linalg_QR_QTvec (r, tau, qtf); /* Compute norm of scaled gradient */ compute_gradient_direction (r, perm, qtf, diag, gradient); { size_t iamax = gsl_blas_idamax (gradient); gnorm = fabs(gsl_vector_get (gradient, iamax) / state->fnorm); } /* Determine the Levenberg-Marquardt parameter */ lm_iteration: iter++ ; { int status = lmpar (r, perm, qtf, diag, state->delta, &(state->par), newton, gradient, sdiag, dx, w); if (status) return status; } /* Take a trial step */ gsl_vector_scale (dx, -1.0); /* reverse the step to go downhill */ compute_trial_step (x, dx, state->x_trial); pnorm = scaled_enorm (diag, dx); if (state->iter == 1) { if (pnorm < state->delta) { #ifdef DEBUG printf("set delta = pnorm = %g\n" , pnorm); #endif state->delta = pnorm; } } /* Evaluate function at x + p */ /* return immediately if evaluation raised error */ { int status = GSL_MULTIFIT_FN_EVAL_F (fdf, x_trial, f_trial); if (status) return status; } fnorm1 = enorm (f_trial); /* Compute the scaled actual reduction */ actred = compute_actual_reduction (state->fnorm, fnorm1); #ifdef DEBUG printf("lmiterate: fnorm = %g fnorm1 = %g actred = %g\n", state->fnorm, fnorm1, actred); printf("r = "); gsl_matrix_fprintf(stdout, r, "%g"); printf("perm = "); gsl_permutation_fprintf(stdout, perm, "%d"); printf("dx = "); gsl_vector_fprintf(stdout, dx, "%g"); #endif /* Compute rptdx = R P^T dx, noting that |J dx| = |R P^T dx| */ compute_rptdx (r, perm, dx, rptdx); #ifdef DEBUG printf("rptdx = "); gsl_vector_fprintf(stdout, rptdx, "%g"); #endif fnorm1p = enorm (rptdx); /* Compute the scaled predicted reduction = |J dx|^2 + 2 par |D dx|^2 */ { double t1 = fnorm1p / state->fnorm; double t2 = (sqrt(state->par) * pnorm) / state->fnorm; prered = t1 * t1 + t2 * t2 / p5; dirder = -(t1 * t1 + t2 * t2); } /* compute the ratio of the actual to predicted reduction */ if (prered > 0) { ratio = actred / prered; } else { ratio = 0; } #ifdef DEBUG printf("lmiterate: prered = %g dirder = %g ratio = %g\n", prered, dirder,ratio); #endif /* update the step bound */ if (ratio > p25) { #ifdef DEBUG printf("ratio > p25\n"); #endif if (state->par == 0 || ratio >= p75) { state->delta = pnorm / p5; state->par *= p5; #ifdef DEBUG printf("updated step bounds: delta = %g, par = %g\n", state->delta, state->par); #endif } } else { double temp = (actred >= 0) ? p5 : p5*dirder / (dirder + p5 * actred); #ifdef DEBUG printf("ratio < p25\n"); #endif if (p1 * fnorm1 >= state->fnorm || temp < p1 ) { temp = p1; } state->delta = temp * GSL_MIN_DBL (state->delta, pnorm/p1); state->par /= temp; #ifdef DEBUG printf("updated step bounds: delta = %g, par = %g\n", state->delta, state->par); #endif } /* test for successful iteration, termination and stringent tolerances */ if (ratio >= p0001) { gsl_vector_memcpy (x, x_trial); gsl_vector_memcpy (f, f_trial); /* return immediately if evaluation raised error */ { int status; if (fdf->df) status = GSL_MULTIFIT_FN_EVAL_DF (fdf, x_trial, J); else status = gsl_multifit_fdfsolver_dif_df(x_trial, fdf, f_trial, J); if (status) return status; } /* wa2_j = diag_j * x_j */ state->xnorm = scaled_enorm(diag, x); state->fnorm = fnorm1; state->iter++; /* Rescale if necessary */ if (scale) { update_diag (J, diag); } { int signum; gsl_matrix_memcpy (r, J); gsl_linalg_QRPT_decomp (r, tau, perm, &signum, work1); } return GSL_SUCCESS; } else if (fabs(actred) <= GSL_DBL_EPSILON && prered <= GSL_DBL_EPSILON && p5 * ratio <= 1.0) { return GSL_ETOLF ; } else if (state->delta <= GSL_DBL_EPSILON * state->xnorm) { return GSL_ETOLX; } else if (gnorm <= GSL_DBL_EPSILON) { return GSL_ETOLG; } else if (iter < 10) { /* Repeat inner loop if unsuccessful */ goto lm_iteration; } return GSL_ENOPROG; }
void make_cof(points_t *pts, coefficients_t *cof) { gsl_matrix *A, *A_inverse, *BF, *wsp; gsl_permutation * perm, *permtest; gsl_vector *wspt, *bf; double *x = pts->x; double *y = pts->y; double a = x[0]; double b = x[pts->n - 1]; int m = pts->n - 2 > 10 ? 10 : pts->n - 2; int i, j, k; double tmp; char *mEnv = getenv("APPROX_BASE_SIZE"); if (mEnv != NULL && atoi(mEnv) > 0) m = atoi(mEnv); m++; wspt = gsl_vector_alloc(m); bf = gsl_vector_alloc(m); permtest = gsl_permutation_alloc(m); gsl_vector_set_zero (bf); for (i = 0; i < m; i++) { tmp = 0.0; for (k = 0; k < pts->n; k++) tmp += legendre(i, x[k]) * y[k]; gsl_vector_set(bf, i, tmp); //printf("%g\n", gsl_vector_get(bf, i)); } A = gsl_matrix_alloc(m, m); A_inverse = gsl_matrix_alloc(m, m); perm = gsl_permutation_alloc(m); BF = gsl_matrix_alloc(m, 1); wsp = gsl_matrix_alloc(m, 1); gsl_matrix_set_zero (A); for (i = 0; i < m; i++) { for (j = 0; j < m; j++) { for (k = 0; k < pts->n; k++) { A->data[i * A->tda + j] += legendre(i, x[k]) * legendre(j, x[k]); } } } gsl_linalg_LU_decomp(A, permtest, &i); gsl_linalg_LU_solve(A, permtest, bf, wspt); gsl_vector_fprintf(stdout, wspt, "%g"); //macierz odwrotna gsl_linalg_LU_decomp(A, perm, &i); gsl_linalg_LU_invert(A, perm, A_inverse); gsl_matrix_free(A); gsl_permutation_free(perm); gsl_matrix_set_zero (BF); for (i = 0; i < m; i++) { for (k = 0; k < pts->n; k++) BF->data[i * BF->tda + 0] += legendre(i, x[k]) * y[k]; } //mnozenie macierzy gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, A_inverse, BF, 0.0, wsp); gsl_matrix_free(A_inverse); gsl_matrix_free(BF); if (alloc_cof(cof, m) == 0) { for (i = 0; i < cof->base; i++) cof->coefficients[i] = gsl_matrix_get(wsp, i, 0); } return; }
// for debugging void dump_vector(gsl_vector *m, char *filename) { FILE *f = fopen(filename, "w"); gsl_vector_fprintf(f, m, "%.16g"); fclose(f); }
static void minimize (gsl_multimin_function_fdf * fdf, const gsl_vector * x, const gsl_vector * p, double lambda, double stepa, double stepb, double stepc, double fa, double fb, double fc, double tol, gsl_vector * x1, gsl_vector * dx1, gsl_vector * x2, gsl_vector * dx2, gsl_vector * gradient, double * step, double * f, double * gnorm) { /* Starting at (x0, f0) move along the direction p to find a minimum f(x0 - lambda * p), returning the new point x1 = x0-lambda*p, f1=f(x1) and g1 = grad(f) at x1. */ double u = stepb; double v = stepa; double w = stepc; double fu = fb; double fv = fa; double fw = fc; double old2 = fabs(w - v); double old1 = fabs(v - u); double stepm, fm, pg, gnorm1; int iter = 0; gsl_vector_memcpy (x2, x1); gsl_vector_memcpy (dx2, dx1); *f = fb; *step = stepb; *gnorm = gsl_blas_dnrm2 (gradient); mid_trial: iter++; if (iter > 10) { return; /* MAX ITERATIONS */ } { double dw = w - u; double dv = v - u; double du = 0.0; double e1 = ((fv - fu) * dw * dw + (fu - fw) * dv * dv); double e2 = 2.0 * ((fv - fu) * dw + (fu - fw) * dv); if (e2 != 0.0) { du = e1 / e2; } if (du > 0.0 && du < (stepc - stepb) && fabs(du) < 0.5 * old2) { stepm = u + du; } else if (du < 0.0 && du > (stepa - stepb) && fabs(du) < 0.5 * old2) { stepm = u + du; } else if ((stepc - stepb) > (stepb - stepa)) { stepm = 0.38 * (stepc - stepb) + stepb; } else { stepm = stepb - 0.38 * (stepb - stepa); } } take_step (x, p, stepm, lambda, x1, dx1); fm = GSL_MULTIMIN_FN_EVAL_F (fdf, x1); #ifdef DEBUG printf ("trying stepm = %g fm = %.18e\n", stepm, fm); #endif if (fm > fb) { if (fm < fv) { w = v; v = stepm; fw = fv; fv = fm; } else if (fm < fw) { w = stepm; fw = fm; } if (stepm < stepb) { stepa = stepm; fa = fm; } else { stepc = stepm; fc = fm; } goto mid_trial; } else if (fm <= fb) { old2 = old1; old1 = fabs(u - stepm); w = v; v = u; u = stepm; fw = fv; fv = fu; fu = fm; gsl_vector_memcpy (x2, x1); gsl_vector_memcpy (dx2, dx1); GSL_MULTIMIN_FN_EVAL_DF (fdf, x1, gradient); gsl_blas_ddot (p, gradient, &pg); gnorm1 = gsl_blas_dnrm2 (gradient); #ifdef DEBUG printf ("p: "); gsl_vector_fprintf(stdout, p, "%g"); printf ("g: "); gsl_vector_fprintf(stdout, gradient, "%g"); printf ("gnorm: %.18e\n", gnorm1); printf ("pg: %.18e\n", pg); printf ("orth: %g\n", fabs (pg * lambda/ gnorm1)); #endif *f = fm; *step = stepm; *gnorm = gnorm1; if (fabs (pg * lambda / gnorm1) < tol) { #ifdef DEBUG printf("ok!\n"); #endif return; /* SUCCESS */ } if (stepm < stepb) { stepc = stepb; fc = fb; stepb = stepm; fb = fm; } else { stepa = stepb; fa = fb; stepb = stepm; fb = fm; } goto mid_trial; } }
static int vector_bfgs_iterate (void *vstate, gsl_multimin_function_fdf * fdf, gsl_vector * x, double *f, gsl_vector * gradient, gsl_vector * dx) { vector_bfgs_state_t *state = (vector_bfgs_state_t *) vstate; gsl_vector *x1 = state->x1; gsl_vector *dx1 = state->dx1; gsl_vector *x2 = state->x2; gsl_vector *p = state->p; gsl_vector *g0 = state->g0; gsl_vector *x0 = state->x0; double pnorm = state->pnorm; double g0norm = state->g0norm; double fa = *f, fb, fc; double dir; double stepa = 0.0, stepb, stepc = state->step, tol = state->tol; double g1norm; double pg; if (pnorm == 0.0 || g0norm == 0.0) { gsl_vector_set_zero (dx); return GSL_ENOPROG; } /* Determine which direction is downhill, +p or -p */ gsl_blas_ddot (p, gradient, &pg); dir = (pg >= 0.0) ? +1.0 : -1.0; /* Compute new trial point at x_c= x - step * p, where p is the current direction */ take_step (x, p, stepc, dir / pnorm, x1, dx); /* Evaluate function and gradient at new point xc */ fc = GSL_MULTIMIN_FN_EVAL_F (fdf, x1); if (fc < fa) { /* Success, reduced the function value */ state->step = stepc * 2.0; *f = fc; gsl_vector_memcpy (x, x1); GSL_MULTIMIN_FN_EVAL_DF (fdf, x1, gradient); return GSL_SUCCESS; } #ifdef DEBUG printf ("got stepc = %g fc = %g\n", stepc, fc); #endif /* Do a line minimisation in the region (xa,fa) (xc,fc) to find an intermediate (xb,fb) satisifying fa > fb < fc. Choose an initial xb based on parabolic interpolation */ intermediate_point (fdf, x, p, dir / pnorm, pg, stepa, stepc, fa, fc, x1, dx1, gradient, &stepb, &fb); if (stepb == 0.0) { return GSL_ENOPROG; } minimize (fdf, x, p, dir / pnorm, stepa, stepb, stepc, fa, fb, fc, tol, x1, dx1, x2, dx, gradient, &(state->step), f, &g1norm); gsl_vector_memcpy (x, x2); /* Choose a new direction for the next step */ state->iter = (state->iter + 1) % x->size; if (state->iter == 0) { gsl_vector_memcpy (p, gradient); state->pnorm = g1norm; } else { /* This is the BFGS update: */ /* p' = g1 - A dx - B dg */ /* A = - (1+ dg.dg/dx.dg) B + dg.g/dx.dg */ /* B = dx.g/dx.dg */ gsl_vector *dx0 = state->dx0; gsl_vector *dg0 = state->dg0; double dxg, dgg, dxdg, dgnorm, A, B; /* dx0 = x - x0 */ gsl_vector_memcpy (dx0, x); gsl_blas_daxpy (-1.0, x0, dx0); /* dg0 = g - g0 */ gsl_vector_memcpy (dg0, gradient); gsl_blas_daxpy (-1.0, g0, dg0); gsl_blas_ddot (dx0, gradient, &dxg); gsl_blas_ddot (dg0, gradient, &dgg); gsl_blas_ddot (dx0, dg0, &dxdg); dgnorm = gsl_blas_dnrm2 (dg0); if (dxdg != 0) { B = dxg / dxdg; A = -(1.0 + dgnorm * dgnorm / dxdg) * B + dgg / dxdg; } else { B = 0; A = 0; } gsl_vector_memcpy (p, gradient); gsl_blas_daxpy (-A, dx0, p); gsl_blas_daxpy (-B, dg0, p); state->pnorm = gsl_blas_dnrm2 (p); } gsl_vector_memcpy (g0, gradient); gsl_vector_memcpy (x0, x); state->g0norm = gsl_blas_dnrm2 (g0); #ifdef DEBUG printf ("updated directions\n"); printf ("p: "); gsl_vector_fprintf (stdout, p, "%g"); printf ("g: "); gsl_vector_fprintf (stdout, gradient, "%g"); #endif return GSL_SUCCESS; }
int main(int argc, char *argv[]) { // Declaring variables. gsl_vector *z, *new_z; int opt; unsigned n; double c; char out_file[20]; // Default values. sprintf(out_file, "%s", "out.dat"); // GNU getopt in action. while ((opt = getopt(argc, argv, "n:c:i:")) != -1) { switch (opt) { case 'n': n = atoi(optarg); break; case 'c': c = atof(optarg); break; case 'i': sprintf(out_file, "%s", optarg); break; default: exit(EXIT_FAILURE); } } z = gsl_vector_alloc(3 * n + 3); new_z = gsl_vector_alloc(6 * n + 3); FILE *f = fopen(out_file, "r"); gsl_vector_fscanf(f, z); fclose(f); gsl_vector_set(new_z, 2 * n - 1, (gsl_vector_get(z, 0) + gsl_vector_get(z, n - 1)) / 2); gsl_vector_set(new_z, 2 * n - 2, gsl_vector_get(z, n - 2)); for (unsigned i = 0; i < n - 1; i ++) { gsl_vector_set(new_z, 2 * i, gsl_vector_get(z, i)); gsl_vector_set(new_z, 2 * i + 1, (gsl_vector_get(z, i) + gsl_vector_get(z, i + 1)) / 2); } gsl_vector_set(new_z, 2 * n, gsl_vector_get(z, n) / 2); gsl_vector_set(new_z, 2 * n + 1, gsl_vector_get(z, n)); gsl_vector_set(new_z, 4 * n - 2, gsl_vector_get(z, 2 * n - 2) / 2); gsl_vector_set(new_z, 4 * n - 3, gsl_vector_get(z, 2 * n - 2)); for (unsigned i = 1; i < n - 1; i ++) { gsl_vector_set(new_z, 2 * (n + i) + 1, gsl_vector_get(z, n + i)); gsl_vector_set(new_z, 2 * (n + i) , (gsl_vector_get(z, n + i - 1) + gsl_vector_get(z, n + i)) / 2); } gsl_vector_set(new_z, 4 * n - 1, gsl_vector_get(z, 2 * n -1)); gsl_vector_set(new_z, 4 * n, gsl_vector_get(z, 2 * n)); for (unsigned i = 0; i < n; i++) { gsl_vector_set(new_z, 4 * n + 1 + 2 * i, gsl_vector_get(z, 2 * n + 1 + i)); gsl_vector_set(new_z, 4 * n + 2 + 2 * i, gsl_vector_get(z, 2 * n + 1 + i)); } gsl_vector_set(new_z, 6 * n + 1, gsl_vector_get(z, 3 * n + 1)); gsl_vector_set(new_z, 6 * n + 2, gsl_vector_get(z, 3 * n + 2)); int result; result = domain_minimize_fixed(new_z, 2 * n, c, 1e-8, 0.00001, 5000, 4, 2); if (result) printf("Converging failed."); else { FILE *fout = fopen(out_file, "w"); gsl_vector_fprintf(fout, new_z, "%.10g"); fclose(fout); } gsl_vector_free(z); gsl_vector_free(new_z); }
static int dogleg (const gsl_matrix * r, const gsl_vector * qtf, const gsl_vector * diag, double delta, gsl_vector * newton, gsl_vector * gradient, gsl_vector * p) { double qnorm, gnorm, sgnorm, bnorm, temp; newton_direction (r, qtf, newton); #ifdef DEBUG printf("newton = "); gsl_vector_fprintf(stdout, newton, "%g"); printf("\n"); #endif qnorm = scaled_enorm (diag, newton); if (qnorm <= delta) { gsl_vector_memcpy (p, newton); #ifdef DEBUG printf("took newton (qnorm = %g <= delta = %g)\n", qnorm, delta); #endif return GSL_SUCCESS; } gradient_direction (r, qtf, diag, gradient); #ifdef DEBUG printf("grad = "); gsl_vector_fprintf(stdout, gradient, "%g"); printf("\n"); #endif gnorm = enorm (gradient); if (gnorm == 0) { double alpha = delta / qnorm; double beta = 0; scaled_addition (alpha, newton, beta, gradient, p); #ifdef DEBUG printf("took scaled newton because gnorm = 0\n"); #endif return GSL_SUCCESS; } minimum_step (gnorm, diag, gradient); compute_Rg (r, gradient, p); /* Use p as temporary space to compute Rg */ #ifdef DEBUG printf("mingrad = "); gsl_vector_fprintf(stdout, gradient, "%g"); printf("\n"); printf("Rg = "); gsl_vector_fprintf(stdout, p, "%g"); printf("\n"); #endif temp = enorm (p); sgnorm = (gnorm / temp) / temp; if (sgnorm > delta) { double alpha = 0; double beta = delta; scaled_addition (alpha, newton, beta, gradient, p); #ifdef DEBUG printf("took gradient\n"); #endif return GSL_SUCCESS; } bnorm = enorm (qtf); { double bg = bnorm / gnorm; double bq = bnorm / qnorm; double dq = delta / qnorm; double dq2 = dq * dq; double sd = sgnorm / delta; double sd2 = sd * sd; double t1 = bg * bq * sd; double u = t1 - dq; double t2 = t1 - dq * sd2 + sqrt (u * u + (1-dq2) * (1 - sd2)); double alpha = dq * (1 - sd2) / t2; double beta = (1 - alpha) * sgnorm; #ifdef DEBUG printf("bnorm = %g\n", bnorm); printf("gnorm = %g\n", gnorm); printf("qnorm = %g\n", qnorm); printf("delta = %g\n", delta); printf("alpha = %g beta = %g\n", alpha, beta); printf("took scaled combination of newton and gradient\n"); #endif scaled_addition (alpha, newton, beta, gradient, p); } return GSL_SUCCESS; }
void vct_fprintf(const char* filename, gsl_vector* v) { FILE* fileptr; fileptr = fopen(filename, "w"); gsl_vector_fprintf(fileptr, v, "%20.17e"); fclose(fileptr); }
void print_orth_with_spin() { if (!initialized) return; gsl_vector_fprintf(stdout, uv_orth_w_spin, "%f"); }
static int conjugate_fr_iterate (void *vstate, gsl_multimin_function_fdf * fdf, gsl_vector * x, double *f, gsl_vector * gradient, gsl_vector * dx) { conjugate_fr_state_t *state = (conjugate_fr_state_t *) vstate; gsl_vector *x1 = state->x1; gsl_vector *dx1 = state->dx1; gsl_vector *x2 = state->x2; gsl_vector *p = state->p; gsl_vector *g0 = state->g0; double pnorm = state->pnorm; double g0norm = state->g0norm; double fa = *f, fb, fc; double dir; double stepa = 0.0, stepb, stepc = state->step, tol = state->tol; double g1norm; double pg; if (pnorm == 0.0 || g0norm == 0.0) { gsl_vector_set_zero (dx); return GSL_ENOPROG; } /* Determine which direction is downhill, +p or -p */ gsl_blas_ddot (p, gradient, &pg); dir = (pg >= 0.0) ? +1.0 : -1.0; /* Compute new trial point at x_c= x - step * p, where p is the current direction */ take_step (x, p, stepc, dir / pnorm, x1, dx); /* Evaluate function and gradient at new point xc */ fc = GSL_MULTIMIN_FN_EVAL_F (fdf, x1); if (fc < fa) { /* Success, reduced the function value */ state->step = stepc * 2.0; *f = fc; gsl_vector_memcpy (x, x1); GSL_MULTIMIN_FN_EVAL_DF (fdf, x1, gradient); return GSL_SUCCESS; } #ifdef DEBUG printf ("got stepc = %g fc = %g\n", stepc, fc); #endif /* Do a line minimisation in the region (xa,fa) (xc,fc) to find an intermediate (xb,fb) satisifying fa > fb < fc. Choose an initial xb based on parabolic interpolation */ intermediate_point (fdf, x, p, dir / pnorm, pg, stepa, stepc, fa, fc, x1, dx1, gradient, &stepb, &fb); if (stepb == 0.0) { return GSL_ENOPROG; } minimize (fdf, x, p, dir / pnorm, stepa, stepb, stepc, fa, fb, fc, tol, x1, dx1, x2, dx, gradient, &(state->step), f, &g1norm); gsl_vector_memcpy (x, x2); /* Choose a new conjugate direction for the next step */ state->iter = (state->iter + 1) % x->size; if (state->iter == 0) { gsl_vector_memcpy (p, gradient); state->pnorm = g1norm; } else { /* p' = g1 - beta * p */ double beta = -pow (g1norm / g0norm, 2.0); gsl_blas_dscal (-beta, p); gsl_blas_daxpy (1.0, gradient, p); state->pnorm = gsl_blas_dnrm2 (p); } state->g0norm = g1norm; gsl_vector_memcpy (g0, gradient); #ifdef DEBUG printf ("updated conjugate directions\n"); printf ("p: "); gsl_vector_fprintf (stdout, p, "%g"); printf ("g: "); gsl_vector_fprintf (stdout, gradient, "%g"); #endif return GSL_SUCCESS; }
int main (int argc, char *argv[]) { /* Local variables */ int i, j, k, l; /* Indices and counters */ int nr; /* Matrix dimensions, rows */ int nc; /* Matrix dimensions, columns */ int s; /* Sign of the permutation */ if(argc==2) { /* Declare FILE variable */ FILE* inputFile; /* Attempt to open file provided in cmdline arg */ inputFile=fopen(argv[1],"r"); if(inputFile==NULL) { /* Alert user file was not opened properly */ fprintf(stdout,"\nFile was not opened properly\n"); return 2; } /* Scan in nr and nc */ fscanf(inputFile,"%d %d", &nr,&nc); /* Declare and allocate matrix and vector variables */ gsl_matrix *A = gsl_matrix_calloc (nr,nc) ; /* Coefficient Matrix */ gsl_vector *b = gsl_vector_calloc (nr) ; /* Coefficient Vector */ gsl_vector *x = gsl_vector_calloc (nc); /* Solution Vector */ gsl_permutation *p = gsl_permutation_alloc (nr); /* Permutation Vector for LU */ double a_data[nr*nc]; double b_data[nr]; for(i=0; i<nr; i++) { double coefValue; for(j=0; j<nc; j++) { // scan, add to a //index is i*j + j double matValue; fscanf(inputFile, " %lf ", &matValue); a_data[(i*j)+j]=matValue; } //scan, add to b //index is i fscanf(inputFile, " %lf ", &coefValue); b_data[i]=coefValue; } /* double a_data[nr*nc]; a_data[0]=2.0; a_data[1]=3.0; a_data[2]=4.0; a_data[3]=-6.0; double b_data[nr]; b_data[0]=5.0; b_data[1]=-3.0; */ /* Initialize coefficient matrix (A) and vector (b) */ k = 0 ; l = 0 ; /* set counters to zero */ for (i=0; i<nr; i++) { for (j=0; j<nc; j++) { gsl_matrix_set(A,i,j,a_data[k]) ; k++ ; } /* for j */ gsl_vector_set(b,i,b_data[l]) ; l++ ; } /* for i */ /* Print entries of A */ /* do not use gsl_matrix_fprintf */ printf("Solution of the system Ax=b via PLU factorizations\n"); printf("Matrix A:\n"); for (i = 0; i < nr; i++) { for (j = 0; j < nc; j++) printf ("%7.2g ", gsl_matrix_get (A, i, j)); putchar('\n'); } /* for i */ /* Print entries of vector b */ printf("Vector b:\n"); gsl_vector_fprintf (stdout, b,"%7.2g") ; /* Perform (inplace) PLU factorization: overwrites A */ gsl_linalg_LU_decomp (A, p, &s); /* A is overwritten */ /* Now solve using the data in A and p found above and b */ gsl_linalg_LU_solve (A, p, b, x); /* x returns retuls */ /* Print solution x */ printf("Solution x:\n"); gsl_vector_fprintf (stdout, x, "%7.2g"); /* free up memory dynamically allocated */ gsl_matrix_free (A); gsl_vector_free (b); gsl_permutation_free (p); gsl_vector_free (x); } return 0; } /* main */
int main(int argc, char **argv) { gsl_matrix *Original; gsl_matrix *Mtr_Cov; FILE *input; int num_lineas; int i,j,k; double var; /*--------------------------------------------------------- Verifica cuales archivos fueron usados como input y se asegura de que solo haya cargado uno. -----------------------------------------------------------*/ printf("Este programa se ejecutó con %d argumento(s):\n",argc-1); for(i=1;i<argc;i++){ printf("%s\n", argv[i]); } if(argc!=2){ printf("se necesita 1 argumento además del nombre del ejecutable!,\n EXIT!\n"); exit(1); } else{ printf("El archivo a usar es %s\n", argv[1]); } //-------------------------------------------------------- input=fopen(argv[1],"r"); if(!input){ printf("surgió un problema abriendo el archivo\n"); exit(1); } /*--------------------------------------------------------- toma como archivo base el primer argumento y cuenta sus lineas -----------------------------------------------------------*/ num_lineas=0; while ((var = fgetc(input)) != EOF){ if (var =='\n') ++num_lineas; } //printf("Número de lineas del archivo:\n -->%d\n",num_lineas); /*--------------------------------------------------------- Data allocation -----------------------------------------------------------*/ rewind(input); Original=gsl_matrix_alloc((num_lineas),24); // printf("\nOriginal\n"); gsl_matrix_fscanf(input,Original); //gsl_matrix_fprintf (stdout, Original, "%g"); //CheckPoint //printf("matriz escaneada\n"); /*--------------------------------------------------------- Promedio -----------------------------------------------------------*/ float *prom; int y; prom=malloc((num_lineas) * sizeof(float)); //printf("...\n"); for(k=0;k<num_lineas;k++){ float suma=0.0; for(y=0;y<24;y++){ suma+=gsl_matrix_get(Original,k,y); } prom[k]=suma/24.0; } printf("Checkpoint... Promedios\n"); /*--------------------------------------------------------- Efectos en la matriz -----------------------------------------------------------*/ Mtr_Cov=gsl_matrix_alloc(num_lineas,num_lineas); //printf("...\n"); int l,n,m; double sprite=0; for(l=0;l<num_lineas;l++){ for(m=0;m<num_lineas;m++){ for(n=1;n<24;n++){ double flan=gsl_matrix_get(Original,m,n); double agua=prom[m]; double frutino=gsl_matrix_get(Original,l,n); double tang=prom[l]; double jarra1=(flan-agua); double jarra2=(frutino-tang); //printf("%g %g\n",jarra1,jarra2); sprite=sprite+(jarra1*jarra2)/24; } gsl_matrix_set(Mtr_Cov,m,l,sprite); sprite=0; }} /*--------------------------------------------------------- Matriz de covarianza creada; sacar vectores y valores propios de la matriz. -----------------------------------------------------------*/ /* int pa,po; double can; for(pa=0;pa<num_lineas;pa++){ for(po=0;po<num_lineas;po++){ can=gsl_matrix_get(Mtr_Cov,po,pa); printf("%f ",can); } printf("\n"); } */ gsl_eigen_symmv_workspace * w = gsl_eigen_symmv_alloc (num_lineas); gsl_vector *eval = gsl_vector_alloc (num_lineas); gsl_matrix *evec = gsl_matrix_alloc (num_lineas,num_lineas); gsl_eigen_symmv (Mtr_Cov, eval, evec, w); gsl_eigen_symmv_sort (eval, evec,GSL_EIGEN_SORT_ABS_ASC); /*--------------------------------------------------------- PON ESA COSA HORROROSA AHI O VERAS!!! -----------------------------------------------------------*/ FILE *Out1; FILE *Out2; Out1 = fopen("JorgeHayek_eigenvalues.dat", "w"); Out2 = fopen("JorgeHayek_eigenvectors.dat", "w"); fprintf(Out1,"EigenValues:\n"); fprintf(Out2,"EigenVectors:\n"); for (i = 0; i < num_lineas; i++) { double eval_i = gsl_vector_get (eval, i); fprintf (Out1,"%g\n", eval_i); } for (i = 0; i < 11; i++) {fprintf(Out2,"--------------------------------------------\nVector %d\n--------------------------------------------\n",i); gsl_vector_view evec_i = gsl_matrix_column (evec, i); gsl_vector_fprintf (Out2, &evec_i.vector, "%g"); } /*--------------------------------------------------------- FIN -----------------------------------------------------------*/ gsl_vector_free (eval); gsl_matrix_free (evec); gsl_matrix_free(Original); fclose(input); return 0; }
/* print function */ void P1(void *xp) { block * myblock = (block *) xp; gsl_vector_fprintf(stdout, myblock->vec, "%g"); }