gsl_matrix* GaussianMatrix ( gsl_vector *v, float sigma ) { gsl_vector_add_constant ( v, -1 ); gsl_vector_scale ( v, 0.5 ); int siz1 = gsl_vector_get ( v, 0 ); int siz2 = gsl_vector_get ( v, 1 ); gsl_matrix *x = gsl_matrix_alloc ( siz1*2+1, siz2*2+1 ); gsl_matrix *y = gsl_matrix_alloc ( siz1*2+1, siz2*2+1 ); for ( int i=-siz2; i<=siz2; i++ ) { for ( int j=-siz1; j<=siz1; j++ ) { gsl_matrix_set ( x, i+siz2, j+siz1, j ); gsl_matrix_set ( y, i+siz2, j+siz1, i ); } } gsl_matrix_mul_elements ( x, x ); gsl_matrix_mul_elements ( y, y ); gsl_matrix_add ( x, y ); gsl_matrix_scale ( x, -1/(2*sigma*sigma) ); float sum = 0; for ( int i=0; i<x->size1; i++ ) { for ( int j=0; j<x->size2; j++ ) { gsl_matrix_set ( x, i, j, exp(gsl_matrix_get ( x, i, j )) ); sum += gsl_matrix_get ( x, i, j ); } } if ( sum != 0 ) gsl_matrix_scale ( x, 1/sum ); gsl_matrix_free ( y ); return x; }
static REAL8 fContact (REAL8 x, void *params) { fContactWorkSpace *p = (fContactWorkSpace *)params; gsl_permutation *p1 = p->p1; gsl_vector *tmpV = p->tmpV; gsl_matrix *C = p->C; gsl_matrix *A = p->tmpA; gsl_matrix *B = p->tmpB; INT4 s1; REAL8 result; gsl_matrix_memcpy ( A, p->invQ1); gsl_matrix_memcpy ( B, p->invQ2); gsl_matrix_scale (B, x); gsl_matrix_scale (A, (1.0L-x)); gsl_matrix_add (A, B); gsl_linalg_LU_decomp( A, p1, &s1 ); gsl_linalg_LU_invert( A, p1, C ); /* Evaluate the product C x r_AB */ gsl_blas_dsymv (CblasUpper, 1.0, C, p->r_AB, 0.0, tmpV); /* Now evaluate transpose(r_AB) x (C x r_AB) */ gsl_blas_ddot (p->r_AB, tmpV, &result); result *= (x*(1.0L-x)); return (-result); }
static long double fixed_wishart_ll(apop_data *in, apop_model *m){ //Let the mean of the input covariances be CM. //We need to estimate the df via MLE. //However, the right value of the wishart covariance grid is CM/df. //So, for a value of df that we're trying, scale CM appropriately. gsl_matrix_scale(m->parameters->matrix, 1./m->parameters->vector->data[0]); double out = wishart_ll(in, m); gsl_matrix_scale(m->parameters->matrix, m->parameters->vector->data[0]); return out; }
void momentum_update(par* p, gsl_vector** biases, gsl_matrix** weights, double step) { double mu = p->contract_momentum; for (int i = 0; i < p->num_layers-1; i++){ //gsl_vector_scale(p->biases_momentum[i], mu); //gsl_blas_daxpy(step, biases[i], p->biases_momentum[i]); gsl_vector_add(p->biases[i], p->biases_momentum[i]); gsl_matrix_scale(p->weights_momentum[i], mu); gsl_matrix_scale(weights[i],step); gsl_matrix_add(p->weights_momentum[i],weights[i]); gsl_matrix_add(p->weights[i], p->weights_momentum[i]); } }
int main(void) { // test bias objects initiation and ranodmization test_bias_object(false); test_bias_object(true); // test sigmoid test_sigmoid(); // test weights objects initiation and randomization test_weight_object(false); test_weight_object(true); // test Neural Nets forward sweep test_forward_propagation(); const gsl_rng_type* T; gsl_rng* r; gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc(T); gsl_matrix* a, * b; a = gsl_matrix_alloc(3,3); b = gsl_matrix_alloc(3,3); for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++){ gsl_matrix_set(a,i,j,i+j); gsl_matrix_set(b,i,j,i+j); } gsl_matrix_scale(b,10.0); gsl_matrix_add(a,b); for (int i = 0; i < 3; i++) for (int j = 0; j <3; j++) printf("m(%d,%d) = %g\n",i,j, gsl_matrix_get(a,i,j)); gsl_matrix_free(a); gsl_matrix_free(b); }
// measurement update (correction) bool ContinuousKalmanFilter::updateMeasurement(const double time, const gsl_vector *actualMeasurement, const gsl_vector *Du) // Du(t) = D(t) * u(t) { #if 0 if (!x_hat_ || /*!y_hat_ ||*/ !P_ || !K_) return false; const gsl_matrix *C = doGetOutputMatrix(time, x_hat_); #if 0 const gsl_matrix *V = doGetMeasurementNoiseCouplingMatrix(time); const gsl_matrix *R = doGetMeasurementNoiseCovarianceMatrix(time); // R(t) #else const gsl_matrix *Rd = doGetMeasurementNoiseCovarianceMatrix(time); // Rd(t) = V(t) * R(t) * V(t)^T #endif const gsl_vector *Du = doGetMeasurementInput(time, x_hat_); // Du(t) = D(t) * u(t) const gsl_vector *actualMeasurement = doGetMeasurement(time, x_hat_); // actual measurement if (!C || !Rd || !Du || !actualMeasurement) return false; // 1. calculate Kalman gain: K(t) = P(t) * C(t)^T * Rd(t)^-1 where Rd(t) = V(t) * R(t) * V(t)^T // 2. update measurement: dx(t)/dt = A(t) * x(t) + B(t) * u(t) + K(t) * (y_tilde(t) - y_hat(t)) where y_hat(t) = C(t) * x(t) + D(t) * u(t) // 3. update covariance: // dP(t)/dt = A(t) * P(t) + P(t) * A(t)^T + Qd(t) - P(t) * C(t)^T * Rd(t)^-1 * C(t) * P(t) : the matrix Riccati differential equation // = A(t) * P(t) + P(t) * A(t)^T + Qd(t) - K(t) * Rd(t) * K(t)^T // preserve symmetry of P gsl_matrix_transpose_memcpy(M_, P_); gsl_matrix_add(P_, M_); gsl_matrix_scale(P_, 0.5); return true; #else throw std::runtime_error("Not yet implemented"); #endif }
static int _equalf(CMATRIX *a, double f) { bool result; if (COMPLEX(a)) { if (f == 0.0) return gsl_matrix_complex_isnull(CMAT(a)); gsl_matrix_complex *m = gsl_matrix_complex_alloc(WIDTH(a), HEIGHT(a)); gsl_matrix_complex_set_identity(m); gsl_matrix_complex_scale(m, gsl_complex_rect(f, 0)); result = gsl_matrix_complex_equal(CMAT(a), m); gsl_matrix_complex_free(m); } else { if (f == 0.0) return gsl_matrix_isnull(MAT(a)); gsl_matrix *m = gsl_matrix_alloc(WIDTH(a), HEIGHT(a)); gsl_matrix_set_identity(m); gsl_matrix_scale(m, f); result = gsl_matrix_equal(MAT(a), m); gsl_matrix_free(m); } return result; }
// Measurement update (correction). bool ContinuousExtendedKalmanFilter::updateMeasurement(const double time, const gsl_vector *actualMeasurement, const gsl_vector *input) { #if 0 if (!x_hat_ || /*!y_hat_ ||*/ !P_ || !K_) return false; const gsl_vector *h_eval = system_.evaluateMeasurementEquation(step, x_hat_, input, NULL); // h = h(t, x(t), u(t), v(t)) const gsl_matrix *C = doGetOutputMatrix(time, x_hat_); // C(t) = dh(t, x(t), u(t), 0)/dx #if 0 const gsl_matrix *V = doGetMeasurementNoiseCouplingMatrix(time); // V(t) = dh(t, x(t), u(t), 0)/dv const gsl_matrix *R = doGetMeasurementNoiseCovarianceMatrix(time); // R(t) #else const gsl_matrix *Rd = doGetMeasurementNoiseCovarianceMatrix(time); // Rd(t) = V(t) * R(t) * V(t)^T #endif if (!C || !Rd || !h_eval || !actualMeasurement) return false; // 1. calculate Kalman gain: K(t) = P(t) * C(t)^T * Rd(t)^-1 where C(t) = dh(t, x(t), u(t), 0)/dx, Rd(t) = V(t) * R(t) * V(t)^T, V(t) = dh(t, x(t), u(t), 0)/dv // 2. update measurement: dx(t)/dt = f(t, x(t), u(t), 0) + K(t) * (y_tilde(t) - y_hat(t)) where y_hat(t) = h(t, x(t), u(t), 0) ??? // 3. update covariance: // dP(t)/dt = A(t) * P(t) + P(t) * A(t)^T + Qd(t) - P(t) * C(t)^T * Rd(t)^-1 * C(t) * P(t) : the matrix Riccati differential equation // = A(t) * P(t) + P(t) * A(t)^T + Qd(t) - K(t) * Rd(t) * K(t)^T // preserve symmetry of P gsl_matrix_transpose_memcpy(M_, P_); gsl_matrix_add(P_, M_); gsl_matrix_scale(P_, 0.5); return true; #else throw std::runtime_error("Not yet implemented"); #endif }
// time update (prediction) bool ContinuousKalmanFilter::updateTime(const double time, const gsl_vector *Bu) // Bu(t) = B(t) * u(t) { #if 0 if (!x_hat_ || /*!y_hat_ ||*/ !P_ || !K_) return false; const gsl_matrix *A = doGetSystemMatrix(time, x_hat_); #if 0 const gsl_matrix *W = doGetProcessNoiseCouplingMatrix(time); const gsl_matrix *Q = doGetProcessNoiseCovarianceMatrix(time); // Q(t) #else const gsl_matrix *Qd = doGetProcessNoiseCovarianceMatrix(time); // Qd(t) = W(t) * Q(t) * W(t)^T #endif //const gsl_vector *Bu = doGetControlInput(time, x_hat_); // Bu(t) = B(t) * u(t) if (!A || !Qd || !Bu) return false; // 1. propagate time // dx(t)/dt = A(t) * x(t) + B(t) * u(t) // dP(t)/dt = A(t) * P(t) + P(t) * A(t)^T + Qd where Qd(t) = W(t) * Q(t) * W(t)^T // preserve symmetry of P gsl_matrix_transpose_memcpy(M_, P_); gsl_matrix_add(P_, M_); gsl_matrix_scale(P_, 0.5); return true; #else throw std::runtime_error("Not yet implemented"); #endif }
/** * Adapted from: Multivariate Normal density function and random * number generator Using GSL from Ralph dos Santos Silva * Copyright (C) 2006 * * multivariate normal density function * * @param n dimension of the random vetor * @param mean vector of means of size n * @param var variance matrix of dimension n x n */ double ssm_dmvnorm(const int n, const gsl_vector *x, const gsl_vector *mean, const gsl_matrix *var, double sd_fac) { int s; double ax,ay; gsl_vector *ym, *xm; gsl_matrix *work = gsl_matrix_alloc(n,n), *winv = gsl_matrix_alloc(n,n); gsl_permutation *p = gsl_permutation_alloc(n); gsl_matrix_memcpy( work, var ); //scale var with sd_fac^2 gsl_matrix_scale(work, sd_fac*sd_fac); gsl_linalg_LU_decomp( work, p, &s ); gsl_linalg_LU_invert( work, p, winv ); ax = gsl_linalg_LU_det( work, s ); gsl_matrix_free( work ); gsl_permutation_free( p ); xm = gsl_vector_alloc(n); gsl_vector_memcpy( xm, x); gsl_vector_sub( xm, mean ); ym = gsl_vector_alloc(n); gsl_blas_dsymv(CblasUpper,1.0,winv,xm,0.0,ym); gsl_matrix_free( winv ); gsl_blas_ddot( xm, ym, &ay); gsl_vector_free(xm); gsl_vector_free(ym); ay = exp(-0.5*ay)/sqrt( pow((2*M_PI),n)*ax ); return ay; }
void Testwishart(CuTest* tc) { /*set a non-trivial location matrix*/ gsl_matrix* V = gsl_matrix_alloc(DIM, DIM); gsl_matrix_set_identity(V); gsl_matrix_scale(V, V0); for(size_t i=0; i<DIM; i++) for(size_t j=i+1; j < DIM; j++) { gsl_matrix_set(V, i, j, 1.0); gsl_matrix_set(V, j, i, 1.0); } p = mcmclib_wishart_lpdf_alloc(V, P); x = gsl_vector_alloc(DIM * DIM); gsl_matrix_view X_v = gsl_matrix_view_vector(x, DIM, DIM); gsl_matrix* X = &(X_v.matrix); gsl_matrix_set_all(X, 0.2); for(size_t i=0; i<DIM; i++) gsl_matrix_set(X, i, i, 1.0); CuAssertDblEquals(tc, -7.152627, lpdf(1.0), TOL); CuAssertDblEquals(tc, -29.549142, lpdf(0.5), TOL); CuAssertDblEquals(tc, 13.380252, lpdf(2.0), TOL); mcmclib_wishart_lpdf_free(p); gsl_vector_free(x); gsl_matrix_free(V); }
// matrix multiplication by a constant Matrix Matrix::operator*( const double c ) const { Matrix result( *this ); gsl_matrix_scale( result.data, c ); return result; }
// time update (prediction) bool ContinuousExtendedKalmanFilter::updateTime(const double time, const gsl_vector *input) { #if 0 if (!x_hat_ || /*!y_hat_ ||*/ !P_ || !K_) return false; const gsl_vector *f_eval = system_.evaluatePlantEquation(time, x_hat_, input, NULL); // f = f(t, x(t), u(t), w(t)) const gsl_matrix *A = doGetStateTransitionMatrix(time, x_hat_); // A(t) = df(t, x(t), u(t), 0)/dx #if 0 const gsl_matrix *W = doGetProcessNoiseCouplingMatrix(time); // W(t) = df(t, x(t), u(t), 0)/dw const gsl_matrix *Q = doGetProcessNoiseCovarianceMatrix(time); // Q(t) #else const gsl_matrix *Qd = doGetProcessNoiseCovarianceMatrix(time); // Qd(t) = W * Q(t) * W(t)^T #endif if (!A || !Qd || !f_eval) return false; // 1. Propagate time. // dx(t)/dt = f(t, x(t), u(t), 0) // dP(t)/dt = A(t) * P(t) + P(t) * A(t)^T + Qd(t) where A(t) = df(t, x(t), u(t), 0)/dx, Qd(t) = W(t) * Q(t) * W(t)^T, W(t) = df(t, x(t), u(t), 0)/dw // Preserve symmetry of P. gsl_matrix_transpose_memcpy(M_, P_); gsl_matrix_add(P_, M_); gsl_matrix_scale(P_, 0.5); return true; #else throw std::runtime_error("Not yet implemented"); #endif }
RateModel makeDiscretizedGammaModel (const RateModel& model, int bins, double shape) { Assert (model.components() == 1, "Can't make a discretized gamma model from a model that is already a mixture model"); RateModel gammaModel (model.alphabet, bins); gammaModel.copyIndelParams (model); vguard<double> rateMultiplier (bins); double total = 0; for (int c = 0; c < bins; ++c) { const double q = ((double) (c + 1)) / ((double) (bins + 1)); rateMultiplier[c] = gsl_cdf_gamma_Pinv (q, shape, shape); total += rateMultiplier[c]; } // adjust so mean rate multiplier = 1 const double mean = total / (double) bins; for (auto& r: rateMultiplier) r /= mean; LogThisAt(5,"Discretized-gamma rate multipliers: (" << to_string_join(rateMultiplier) << ")" << endl); for (int c = 0; c < bins; ++c) { CheckGsl (gsl_vector_memcpy (gammaModel.insProb[c], model.insProb[0])); CheckGsl (gsl_matrix_memcpy (gammaModel.subRate[c], model.subRate[0])); CheckGsl (gsl_matrix_scale (gammaModel.subRate[c], rateMultiplier[c])); } return gammaModel; }
/** alloc a new at7_gamma object. Input arguments are copied @internal */ static at7_gamma* at7_gamma_alloc(const gsl_vector* beta, gsl_vector** mu, gsl_matrix** Sigma) { at7_gamma* ans = (at7_gamma*) malloc(sizeof(at7_gamma)); const size_t K = beta->size; const size_t dim = mu[0]->size; ans->beta = gsl_vector_alloc(K); gsl_vector_memcpy(ans->beta, beta); ans->mu = (gsl_vector**) malloc(K * sizeof(gsl_vector*)); ans->Sigma = (gsl_matrix**) malloc(K * sizeof(gsl_matrix*)); ans->pik = (mcmclib_mvnorm_lpdf**) malloc(K * sizeof(mcmclib_mvnorm_lpdf*)); ans->tmpMean = gsl_vector_alloc(dim); ans->qVariances = (gsl_matrix**) malloc(K * sizeof(gsl_matrix*)); ans->qdk = (mcmclib_mvnorm_lpdf**) malloc(K * sizeof(mcmclib_mvnorm_lpdf*)); for(size_t k=0; k < K; k++) { ans->mu[k] = gsl_vector_alloc(dim); gsl_vector_memcpy(ans->mu[k], mu[k]); ans->Sigma[k] = gsl_matrix_alloc(dim, dim); gsl_matrix_memcpy(ans->Sigma[k], Sigma[k]); ans->pik[k] = mcmclib_mvnorm_lpdf_alloc(ans->mu[k], ans->Sigma[k]->data); ans->qVariances[k] = gsl_matrix_alloc(dim, dim); ans->qdk[k] = mcmclib_mvnorm_lpdf_alloc(ans->tmpMean, ans->qVariances[k]->data); } gsl_vector_memcpy(ans->beta, beta); ans->pi = mcmclib_mixnorm_lpdf_alloc(ans->beta, ans->pik); ans->Sigma_eps = gsl_matrix_alloc(dim, dim); gsl_matrix_set_identity(ans->Sigma_eps); gsl_matrix_scale(ans->Sigma_eps, 0.001); ans->scaling_factors = gsl_vector_alloc(K); gsl_vector_set_all(ans->scaling_factors, 2.38*2.38 / (double) dim); ans->weights = gsl_vector_alloc(K); gsl_vector_set_all(ans->weights, 0.0); at7_gamma_update_Sigma(ans); return ans; }
double mcmclib_mcar_model_phi_fcond(mcmclib_mcar_model* in_p, size_t i, gsl_vector* x) { mcmclib_mcar_tilde_lpdf* lpdf = in_p->lpdf; const size_t p = lpdf->p; if(x->size != p) { static char msg[1024]; sprintf(msg, "'x' vector size is %zd, it should be %zd", x->size, p); GSL_ERROR(msg, GSL_FAILURE); } assert(x->size == p); gsl_matrix* W = lpdf->M; const double mi = 1.0 / gsl_vector_get(lpdf->m, i); gsl_matrix* Lambdaij = lpdf->Lambda_ij; gsl_vector* mean = gsl_vector_alloc(p); gsl_vector_set_zero(mean); for(size_t j=0; j < lpdf->n; j++) { if(gsl_matrix_get(W, i, j) == 1.0) { gsl_vector_view phij_v = gsl_vector_subvector(in_p->e, j*p, p); gsl_blas_dgemv(CblasNoTrans, mi, Lambdaij, &phij_v.vector, 1.0, mean); } } gsl_matrix* Gammai = lpdf->Gammai; gsl_matrix_memcpy(Gammai, lpdf->Gamma); gsl_matrix_scale(Gammai, mi); mcmclib_mvnorm_lpdf* tmp = mcmclib_mvnorm_lpdf_alloc(mean, Gammai->data); double ans = mcmclib_mvnorm_lpdf_compute(tmp, x); gsl_vector_free(mean); mcmclib_mvnorm_lpdf_free(tmp); return ans; }
static void matrix_add_identity(gsl_matrix *m, double f) { gsl_matrix *id = gsl_matrix_alloc(m->size1, m->size2); gsl_matrix_set_identity(id); gsl_matrix_scale(id, f); gsl_matrix_add(m, id); gsl_matrix_free(id); }
static int do_rrmul(lua_State *L, mMatReal *a, double b) { mMatReal *r = qlua_newMatReal(L, a->l_size, a->r_size); gsl_matrix_memcpy(r->m, a->m); gsl_matrix_scale(r->m, b); return 1; }
int Matrix::divideScalar(double aVal) { if(aVal==0) { return -1; } gsl_matrix_scale(matrix,1/aVal); return 0; }
static apop_data *colmeans(apop_data *in){ Get_vmsizes(in); //maxsize apop_data *sums = apop_data_summarize(in); Apop_col_tv(sums, "mean", means); apop_data *out = apop_matrix_to_data(apop_vector_to_matrix(means, 'r')); apop_name_stack(out->names, in->names, 'c', 'c'); apop_data *cov = apop_data_add_page(out, apop_data_covariance(in), "<Covariance>"); gsl_matrix_scale(cov->matrix, 1/sqrt(maxsize)); return out; }
/** Division operator (double) */ matrix<double> matrix<double>::operator/(const double& a) { matrix<double> m1(_matrix); if (gsl_matrix_scale(m1.as_gsl_type_ptr(), 1./a)) { std::cout << "\n Error in matrix<double> / (double)" << std::endl; exit(EXIT_FAILURE); } return m1; }
/** Unary minus */ matrix<double> matrix<double>::operator-() const { matrix<double> m1(_matrix); if (gsl_matrix_scale(m1.as_gsl_type_ptr(), -1.)) { std::cout << "\n Error in matrix<double> unary -" << std::endl; exit(EXIT_FAILURE); } return m1; }
double *Fit::fitGslMultimin(int &iterations, int &status) { double *result = new double[d_p]; // declare input data struct FitData data = {static_cast<size_t>(d_n), static_cast<size_t>(d_p), d_x, d_y, d_y_errors, this}; gsl_multimin_function f; f.f = d_fsimplex; f.n = d_p; f.params = &data; // step size (size of the simplex) // can be increased for faster convergence gsl_vector *ss = gsl_vector_alloc(f.n); gsl_vector_set_all(ss, 10.0); // initialize minimizer const gsl_multimin_fminimizer_type *T = gsl_multimin_fminimizer_nmsimplex; gsl_multimin_fminimizer *s_min = gsl_multimin_fminimizer_alloc(T, f.n); gsl_multimin_fminimizer_set(s_min, &f, d_param_init, ss); // iterate minimization algorithm for (iterations = 0; iterations < d_max_iterations; iterations++) { status = gsl_multimin_fminimizer_iterate(s_min); if (status) break; double size = gsl_multimin_fminimizer_size(s_min); status = gsl_multimin_test_size(size, d_tolerance); if (status != GSL_CONTINUE) break; } // grab results for (int i = 0; i < d_p; i++) result[i] = gsl_vector_get(s_min->x, i); chi_2 = s_min->fval; gsl_matrix *J = gsl_matrix_alloc(d_n, d_p); d_df(s_min->x, (void *)f.params, J); gsl_multifit_covar(J, 0.0, covar); if (d_y_error_source == UnknownErrors) { // multiply covar by variance of residuals, which is used as an estimate for // the // statistical errors (this relies on the Y errors being set to 1.0) gsl_matrix_scale(covar, chi_2 / (d_n - d_p)); } // free previously allocated memory gsl_matrix_free(J); gsl_multimin_fminimizer_free(s_min); gsl_vector_free(ss); return result; }
void matrix_cov(gsl_matrix *input, gsl_matrix *cov){ /*Compute matrix covariance The input is a matrix with an observation per row The function assumes the matrix is demeaned Note: This can be optimized to exploid matrix symmetry */ gsl_blas_dgemm (CblasNoTrans, CblasTrans, 1.0, input, input, 0.0, cov); gsl_matrix_scale(cov, 1.0/(double)(input->size2)); }
void regularisation(par* p, gsl_vector** biases, gsl_matrix** weights) { for (int i = 0; i < p->num_layers-1; i++){ //gsl_blas_daxpy(p->penalty, p->biases[i], biases[i]); gsl_matrix* temp = gsl_matrix_alloc((*weights[i]).size1,(*weights[i]).size2); gsl_matrix_memcpy(temp, p->weights[i]); gsl_matrix_scale(temp, p->penalty); gsl_matrix_add(weights[i],temp); gsl_matrix_free(temp); } }
void CRebuildGraph::printingCompareMatrixResults(float delta, gsl_matrix *F, gsl_matrix* matrixA ){ CFuncTrace lFuncTrace(false,"CRebuildGraph::printingCompareMatrixResults"); lFuncTrace.trace(CTrace::TRACE_DEBUG,"DIFERENCIA (delta) -> %f",delta); //Per presentar-la, definim positiva i normalitzem la matriu F if(gsl_matrix_min(F)<0) gsl_matrix_add_constant (F, -gsl_matrix_min(F)); if(gsl_matrix_max(F)>0) gsl_matrix_scale (F, 1/gsl_matrix_max(F)); FILE *out; out=fopen("sortida.txt","w"); lFuncTrace.trace(CTrace::TRACE_DEBUG,"Resultats en sortida.txt"); fprintf(out, "DIFERENCIA (delta) -> %f\n\n",delta); for(int i=0; i<matrixA->size1; i++){ for(int j=0; j<matrixA->size1; j++){ if(gsl_matrix_get(matrixA,i,j)==0){ fprintf(out," "); }else if(gsl_matrix_get(matrixA,i,j)==1){ fprintf(out,"#"); }else{ printf("\nERROR-Matriu no valida %f",gsl_matrix_get(matrixA,i,j)); exit(1); } } fprintf(out,"\t|\t"); for(int j=0; j<matrixA->size1; j++){ if(gsl_matrix_get(F,i,j)<0.2) fprintf(out," "); else if(gsl_matrix_get(F,i,j)<0.4) fprintf(out,"∑"); else if(gsl_matrix_get(F,i,j)<0.6) fprintf(out,"^"); else if(gsl_matrix_get(F,i,j)<0.8) fprintf(out,"-"); else if(gsl_matrix_get(F,i,j)<0.95) fprintf(out,"/"); else fprintf(out,"#"); } fprintf(out,"\n"); } fclose(out); }
void updateCovariance_particle_arr(particle_arr *part) { int d = part->d; int p = part->p; gsl_matrix *cov = part->cov; double *meanArr = part->mean->array; double w_tot = 0.0; double w_sq_tot = 0.0; double mean_i, mean_j, sum; particle_t *pa; int k; for (k=0; k<p; k++) { w_tot += part->array[k]->weight; w_sq_tot += pow(part->array[k]->weight, 2); } int i, j; for (j=0; j<d; j++) { for (i=0; i<d; i++) { sum = 0.0; if (i < j) { gsl_matrix_set(cov, i, j, gsl_matrix_get(cov, j, i)); continue; } mean_i = meanArr[i]; mean_j = meanArr[j]; for (k=0; k<p; k++) { pa = part->array[k]; sum += pa->weight * (pa->param[i] - mean_i) * (pa->param[j] - mean_j); } sum *= w_tot / (pow(w_tot, 2) - w_sq_tot); gsl_matrix_set(cov, i, j, sum); } } //-- Make a copy, because the invertion will destroy cov gsl_matrix_memcpy(part->cov2, cov); //-- Make LU decomposition and invert int s; gsl_linalg_LU_decomp(part->cov2, part->perm, &s); gsl_linalg_LU_invert(part->cov2, part->perm, part->invCov); //-- Debias the C_{ij}^{-1} //-- C^-1_unbiased = (p - d - 2) / (p - 1) * C^-1_biased double factor = (p - d -2) / (double)(p - 1); gsl_matrix_scale(part->invCov, factor); return; }
int ComputeHermitianMatrix(const gsl_matrix *const M, gsl_matrix_complex * const E, gsl_matrix *const S, gsl_matrix *const N) { unsigned int i, j; gsl_complex z; // S = (M + M^T)/2 gsl_matrix_memcpy(S, M); gsl_matrix_transpose(S); gsl_matrix_add(S, M); gsl_matrix_scale(S, 0.5); // N = (M - M^T)/2 gsl_matrix_memcpy(N, M); gsl_matrix_transpose(N); gsl_matrix_scale(N, -1); gsl_matrix_add(N, M); gsl_matrix_scale(N, 0.5); for(i = 0; i < M->size1; i++) { for(j = 0 ; j < M->size2; j++) { GSL_SET_COMPLEX(&z, gsl_matrix_get(S, i, j), gsl_matrix_get(N, i, j)); gsl_matrix_complex_set(E, i, j, z); } } return GSL_SUCCESS; }
int sigma_adapt(apop_mcmc_proposal_s *ps, apop_mcmc_settings *ms){ apop_model *m = ps->proposal; //accept rate. Add 1% * target to numerator; 1% to denominator, to slow early jumps double ar = (ps->accept_count + .01*ms->periods *ms->target_accept_rate) /(ps->accept_count + ps->reject_count + .01*ms->periods); /* double std_dev_scale= (ar > ms->target_accept_rate) ? (2 - (1.-ar)/(1.-ms->target_accept_rate)) : (1/(2-((ar+0.0)/ms->target_accept_rate))); */ double scale = ar/ms->target_accept_rate; scale = 1+ (scale-1)/100.; //gsl_matrix_scale(m->parameters->matrix, scale > .1? ( scale < 10 ? scale : 10) : .1); gsl_matrix_scale(m->parameters->matrix, scale); return 0; }
void predict_proj_lambda(double* x, LEARN_A_MODEL model,void (*J_func)(const double*,const int,double*),double* centres,double variance,double* Iu, double*A){ gsl_matrix* Rn = gsl_matrix_alloc(model.dim_r,model.dim_r); memcpy(Rn->data,Iu,model.dim_r*model.dim_r*sizeof(double)); gsl_matrix* lambda = gsl_matrix_alloc(model.dim_k,model.dim_r); gsl_matrix_set_all(lambda,0); int k; double * BX, *W_BX,*W_BX_T,*theta,*alpha,*J_x; BX = malloc(model.dim_b*1*sizeof(double)); theta = malloc(1*model.dim_t*sizeof(double)); alpha = malloc(1*model.dim_r*sizeof(double)); gsl_vector* lambda_vec = gsl_vector_alloc(model.dim_r); for (k=1;k<model.dim_k+1;k++){ W_BX = malloc((model.dim_u-k)*1*sizeof(double)); W_BX_T = malloc(1*(model.dim_u-k)*sizeof(double)); ccl_gaussian_rbf(x,model.dim_x,1,centres,model.dim_x,model.dim_b,variance,BX); ccl_dot_product(model.w[k-1],model.dim_u-k,model.dim_b,BX,model.dim_b,1,W_BX); ccl_mat_transpose(W_BX,model.dim_u-k,1,W_BX_T); free(W_BX); if (k ==1){ memcpy(theta,W_BX_T,1*(model.dim_u-k)*sizeof(double)); free(W_BX_T); } else{ gsl_matrix* ones = gsl_matrix_alloc(1,k); gsl_matrix_set_all(ones,1); gsl_matrix_scale(ones,M_PI/2); mat_hotz_app(ones->data,1,k,W_BX_T,model.dim_n,model.dim_u-k,theta); free(W_BX_T); gsl_matrix_free(ones); } ccl_get_unit_vector_from_matrix(theta,1,model.dim_t,alpha); ccl_dot_product(alpha,k,model.dim_r,Rn->data,model.dim_r,model.dim_r,lambda_vec->data); gsl_matrix_set_row(lambda,k-1,lambda_vec); ccl_get_rotation_matrix(theta,Rn->data,&model,k-1,Rn->data); } memcpy(A,lambda->data,model.dim_k*model.dim_r*sizeof(double)); J_x = malloc(model.dim_r*model.dim_x*sizeof(double)); // J_func(x,model.dim_x,J_x); // print_mat_d(alpha,1,model.dim_r); // ccl_dot_product(lambda->data,model.dim_k,model.dim_r,J_x,model.dim_r,model.dim_x,A); free(BX); free(theta); free(alpha); free(J_x); gsl_vector_free(lambda_vec); gsl_matrix_free(lambda); gsl_matrix_free(Rn); }