int main (void){ int i, j, k = 0; gsl_matrix *m = gsl_matrix_alloc (10, 10); gsl_matrix *a = gsl_matrix_alloc (10, 10); for (i = 0; i < 10; i++){ for (j = 0; j < 10; j++){ gsl_matrix_set (m, i, j, i*10+j); } } FILE *f = fopen ("test.dat", "w"); gsl_matrix_fwrite (f, m); fclose (f); FILE *F = fopen ("test.dat", "r"); gsl_matrix_fread (F, a); fclose (F); for (i = 0; i < 10; i++) for (j = 0; j < 10; j++){ double mij = gsl_matrix_get (m, i, j); double aij = gsl_matrix_get (a, i, j); if (mij != aij) k++; } gsl_matrix_free (m); gsl_matrix_free (a); printf ("differences = %d (should be zero)\n", k); return (k > 0); }
int main (void) { int i, j, k = 0; gsl_matrix * m = gsl_matrix_alloc (100, 100); gsl_matrix * a = gsl_matrix_alloc (100, 100); for (i = 0; i < 100; i++) for (j = 0; j < 100; j++) gsl_matrix_set (m, i, j, 0.23 + i + j); { FILE * f = fopen ("test.dat", "wb"); gsl_matrix_fwrite (f, m); fclose (f); } { FILE * f = fopen ("test.dat", "rb"); gsl_matrix_fread (f, a); fclose (f); } for (i = 0; i < 100; i++) for (j = 0; j < 100; j++) { double mij = gsl_matrix_get (m, i, j); double aij = gsl_matrix_get (a, i, j); if (mij != aij) k++; } printf ("differences = %d (should be zero)\n", k); return (k > 0); }
void chapeau_savestate ( chapeau * ch, int timestep, char * filename ) { int N=ch->N; int m=ch->m; FILE *ofs; ofs=fopen(filename,"w"); fwrite(×tep,sizeof(int),1,ofs); fwrite(ch, sizeof(*ch), 1, ofs); fwrite(ch->hits,sizeof(*(ch->hits)),m,ofs); fwrite(ch->mask,sizeof(*(ch->mask)),N,ofs); //fwrite(ch->s,sizeof(***(ch->s)),m*N*3,ofs); gsl_matrix_fwrite(ofs,ch->A); gsl_vector_fwrite(ofs,ch->b); gsl_matrix_fwrite(ofs,ch->Afull); gsl_vector_fwrite(ofs,ch->bfull); gsl_vector_fwrite(ofs,ch->lam); fclose(ofs); }
int lls_save(const char *filename, lls_workspace *w) { int s = 0; FILE *fp; fp = fopen(filename, "w"); if (!fp) { fprintf(stderr, "lls_save: unable to open %s: %s\n", filename, strerror(errno)); return GSL_FAILURE; } fwrite(&(w->bTb), sizeof(double), 1, fp); s += gsl_matrix_fwrite(fp, w->ATA); s += gsl_vector_fwrite(fp, w->ATb); fclose(fp); return s; } /* lls_save() */
int pca_write_matrix(const char *filename, const gsl_matrix * m) { int s; FILE *fp; fp = fopen(filename, "w"); if (!fp) { fprintf(stderr, "pca_write_matrix: unable to open %s: %s\n", filename, strerror(errno)); return -1; } fwrite(&(m->size1), sizeof(size_t), 1, fp); fwrite(&(m->size2), sizeof(size_t), 1, fp); s = gsl_matrix_fwrite(fp, m); fclose(fp); return s; }
//Computes binned coupling matrix // fname_mask (in) : path to fits file containing the mask // n_lbin (in) : number of multipoles per l-bin // nside (out) : mask resolution // lmax (out) : maximum l used (3*nside-1) // nbins (out) : number of l-bins // coupling_matrix_b_out (out) : LU decomposition of the coupling matrix // perm (out) : permutation used in the LU decomposition // mask_out (out) : mask map void compute_coupling_matrix(flouble *cl_mask,int n_lbin, long nside_in,int lmax_in,int nbins_in, gsl_matrix **coupling_matrix_b_out, gsl_permutation **perm_out,char *write_matrix, int pol1,int pol2) { int sig,ib2,ib3,l2,l3; double *cl_mask_bad_ub,**coupling_matrix_ub; gsl_matrix *coupling_matrix_b; gsl_permutation *perm; int n_cl; if(pol1) { if(pol2) n_cl=4; else n_cl=2; } else { if(pol2) n_cl=2; else n_cl=1; } cl_mask_bad_ub=my_malloc((lmax_in+1)*sizeof(double)); for(l2=0;l2<=lmax_in;l2++) cl_mask_bad_ub[l2]=cl_mask[l2]*(2*l2+1.); //Compute coupling matrix coupling_matrix_ub=my_malloc(n_cl*(lmax_in+1)*(sizeof(double *))); for(l2=0;l2<n_cl*(lmax_in+1);l2++) coupling_matrix_ub[l2]=my_calloc(n_cl*(lmax_in+1),(sizeof(double))); printf("Computing unbinned coupling matrix\n"); #pragma omp parallel default(none) \ shared(lmax_in,cl_mask_bad_ub,coupling_matrix_ub,n_cl) { int ll2,ll3; double *wigner_00,*wigner_22; int lstart=0; if((n_cl==1) || (n_cl==2)) wigner_00=my_malloc(2*(lmax_in+1)*sizeof(double)); if((n_cl==2) || (n_cl==4)) wigner_22=my_malloc(2*(lmax_in+1)*sizeof(double)); if(n_cl>1) lstart=2; #pragma omp for schedule(dynamic) for(ll2=lstart;ll2<=lmax_in;ll2++) { for(ll3=lstart;ll3<=lmax_in;ll3++) { int jj,l1,lmin_here,lmax_here; int lmin_here_00=0,lmax_here_00=2*(lmax_in+1)+1; int lmin_here_22=0,lmax_here_22=2*(lmax_in+1)+1; if((n_cl==1) || (n_cl==2)) drc3jj(ll2,ll3,0,0,&lmin_here_00,&lmax_here_00,wigner_00,2*(lmax_in+1)); if((n_cl==2) || (n_cl==4)) drc3jj(ll2,ll3,2,-2,&lmin_here_22,&lmax_here_22,wigner_22,2*(lmax_in+1)); lmin_here=COM_MAX(lmin_here_00,lmin_here_22); lmax_here=COM_MIN(lmax_here_00,lmax_here_22); for(l1=lmin_here;l1<=lmax_here;l1++) { if(l1<=lmax_in) { double wfac; int j00=l1-lmin_here_00; int j22=l1-lmin_here_22; if(n_cl==1) { wfac=cl_mask_bad_ub[l1]*wigner_00[j00]*wigner_00[j00]; coupling_matrix_ub[1*ll2+0][1*ll3+0]+=wfac; //TT,TT } if(n_cl==2) { wfac=cl_mask_bad_ub[l1]*wigner_00[j00]*wigner_22[j22]; coupling_matrix_ub[2*ll2+0][2*ll3+0]+=wfac; //TE,TE coupling_matrix_ub[2*ll2+1][2*ll3+1]+=wfac; //TB,TB } if(n_cl==4) { int suml=l1+ll2+ll3; wfac=cl_mask_bad_ub[l1]*wigner_22[j22]*wigner_22[j22]; if(suml & 1) { //Odd sum coupling_matrix_ub[4*ll2+0][4*ll3+3]+=wfac; //EE,BB coupling_matrix_ub[4*ll2+1][4*ll3+2]-=wfac; //EB,BE coupling_matrix_ub[4*ll2+2][4*ll3+1]-=wfac; //BE,EB coupling_matrix_ub[4*ll2+3][4*ll3+0]+=wfac; //BB,EE } else { coupling_matrix_ub[4*ll2+0][4*ll3+0]+=wfac; //EE,EE coupling_matrix_ub[4*ll2+1][4*ll3+1]+=wfac; //EB,EB coupling_matrix_ub[4*ll2+2][4*ll3+2]+=wfac; //BE,BE coupling_matrix_ub[4*ll2+3][4*ll3+3]+=wfac; //BB,BB } } } } for(jj=0;jj<n_cl;jj++) { int kk; for(kk=0;kk<n_cl;kk++) coupling_matrix_ub[n_cl*ll2+jj][n_cl*ll3+kk]*=(2*ll3+1.)/(4*M_PI); } } } //end omp for if((n_cl==1) || (n_cl==2)) free(wigner_00); if((n_cl==2) || (n_cl==4)) free(wigner_22); } //end omp parallel free(cl_mask_bad_ub); coupling_matrix_b=gsl_matrix_alloc(n_cl*nbins_in,n_cl*nbins_in); int icl_a; for(icl_a=0;icl_a<n_cl;icl_a++) { int icl_b; for(icl_b=0;icl_b<n_cl;icl_b++) { for(ib2=0;ib2<nbins_in;ib2++) { int l20=2+ib2*n_lbin; for(ib3=0;ib3<nbins_in;ib3++) { int l30=2+ib3*n_lbin; double coupling_b=0; for(l2=l20;l2<l20+n_lbin;l2++) { for(l3=l30;l3<l30+n_lbin;l3++) { coupling_b+=coupling_matrix_ub[n_cl*l2+icl_a][n_cl*l3+icl_b]*weigh_l(l2)/weigh_l(l3); } } coupling_b/=n_lbin; gsl_matrix_set(coupling_matrix_b,n_cl*ib2+icl_a,n_cl*ib3+icl_b,coupling_b); } } } } for(l2=0;l2<n_cl*(lmax_in+1);l2++) free(coupling_matrix_ub[l2]); free(coupling_matrix_ub); //Write matrix if required if(strcmp(write_matrix,"none")) { FILE *fo=my_fopen(write_matrix,"wb"); gsl_matrix_fwrite(fo,coupling_matrix_b); fclose(fo); } //Get LU decomposition perm=gsl_permutation_alloc(n_cl*nbins_in); gsl_linalg_LU_decomp(coupling_matrix_b,perm,&sig); *coupling_matrix_b_out=coupling_matrix_b; *perm_out=perm; }
void c_ctr::stochastic_learn_map_estimate(const c_data* users, const c_data* items, const c_corpus* c, const ctr_hyperparameter* param, const char* directory) { // init model parameters printf("\nrunning stochastic learning ...\n"); printf("initializing the model ...\n"); init_model(param->ctr_run); // filename char name[500]; // start time time_t start, current; time(&start); int elapsed = 0; int iter = 0; double likelihood = -exp(50), likelihood_old; double converge = 1.0; double learning_rate = param->learning_rate; /// create the state log file sprintf(name, "%s/state.log", directory); FILE* file = fopen(name, "w"); fprintf(file, "iter time likelihood converge\n"); /* alloc auxiliary variables */ gsl_vector* x = gsl_vector_alloc(m_num_factors); gsl_matrix* phi = NULL; gsl_matrix* word_ss = NULL; gsl_matrix* log_beta = NULL; gsl_vector* gamma = NULL; if (param->ctr_run && param->theta_opt) { int max_len = c->max_corpus_length(); phi = gsl_matrix_calloc(max_len, m_num_factors); word_ss = gsl_matrix_calloc(m_num_factors, c->m_size_vocab); log_beta = gsl_matrix_calloc(m_num_factors, c->m_size_vocab); gsl_matrix_memcpy(log_beta, m_beta); mtx_log(log_beta); gamma = gsl_vector_alloc(m_num_factors); } /* tmp variables for indexes */ int i, j, m, n, l, k, ll, jj; int* item_ids; bool positive = true; double result, inner; int active_num_items = 0; for (j = 0; j < m_num_items; ++j) { if (items->m_vec_len[j] > 0) active_num_items++; } int* idx_base = new int[active_num_items]; l = 0; for (j = 0; j < m_num_items; ++j) { if (items->m_vec_len[j] > 0) { idx_base[l] = j; ++l; } } int* sel = new int[active_num_items]; while (iter < param->max_iter) { likelihood_old = likelihood; likelihood = 0.0; for (i = 0; i < m_num_users; ++i) { item_ids = users->m_vec_data[i]; n = users->m_vec_len[i]; if (n > 0) { double lambda_u = param->lambda_u / (2*n); gsl_vector_view u = gsl_matrix_row(m_U, i); // this user has rated some articles // Randomly choose 2*n negative examples sample_k_from_n(n, active_num_items, sel, idx_base); qsort(sel, n, sizeof(int), compare); l = 0; ll = 0; while (true) { if (l < n) { j = item_ids[l]; // positive } else { j = -1; } if (ll < n) { jj = sel[ll]; //negative while (ll < n-1 && jj == sel[ll+1]) ++ll; // skip same values } else { jj = -1; } if (j == -1) { if (jj == -1) break; else { positive = false; // jj is a negative example ++ll; } } else { if (j < jj) { positive = true; // j is a positive example ++l; } else if (j == jj) { positive = true; // j is a positive example ++l; ++ll; } else { // j > jj if (jj == -1) { positive = true; // j is a positive example ++l; } else { positive = false; ++ll; // jj is a negative example } } } gsl_vector_view v; gsl_vector_view theta_v; double lambda_v = 0.0; if (positive) { // j is a positive example lambda_v = param->lambda_v / (2 * items->m_vec_len[j]); v = gsl_matrix_row(m_V, j); theta_v = gsl_matrix_row(m_theta, j); // second-order // u gsl_vector_scale(&u.vector, 1 - learning_rate); gsl_blas_ddot(&v.vector, &v.vector, &inner); gsl_blas_daxpy(learning_rate / (lambda_u + inner), &v.vector, &u.vector); // v if (!param->lda_regression) { gsl_vector_scale(&v.vector, 1 - learning_rate); gsl_blas_daxpy(learning_rate, &theta_v.vector, &v.vector); gsl_blas_ddot(&u.vector, &u.vector, &inner); gsl_blas_ddot(&u.vector, &theta_v.vector, &result); gsl_blas_daxpy(learning_rate * (1.0 - result) / (lambda_v + inner), &u.vector, &v.vector); } gsl_blas_ddot(&u.vector, &v.vector, &result); likelihood += -0.5 * (1 - result) * (1 - result); // gsl_blas_ddot(&u.vector, &v.vector, &result); // result -= 1.0; } else { // jj is a negative example lambda_v = param->lambda_v / (2 * items->m_vec_len[jj]); v = gsl_matrix_row(m_V, jj); theta_v = gsl_matrix_row(m_theta, jj); // second order // u gsl_vector_scale(&u.vector, 1 - learning_rate); // v if (!param->lda_regression) { gsl_vector_scale(&v.vector, 1 - learning_rate); gsl_blas_daxpy(learning_rate, &theta_v.vector, &v.vector); gsl_blas_ddot(&u.vector, &u.vector, &inner); gsl_blas_ddot(&u.vector, &theta_v.vector, &result); gsl_blas_daxpy(-learning_rate * result / (lambda_v + inner), &u.vector, &v.vector); } gsl_blas_ddot(&u.vector, &v.vector, &result); likelihood += -0.5 * result * result; // gsl_blas_ddot(&u.vector, &v.vector, &result); } // update u // first-order // gsl_vector_scale(&u.vector, 1 - param->learning_rate * lambda_u); // gsl_blas_daxpy(-result * param->learning_rate, &v.vector, &u.vector); // second order // update v // gsl_vector_scale(&v.vector, 1 - param->learning_rate * lambda_v); // gsl_blas_daxpy(-result * param->learning_rate, &u.vector, &v.vector); // gsl_blas_daxpy(param->learning_rate * lambda_v, &theta_v.vector, &v.vector); } assert(n == l && n == l); //printf("n=%d, l=%d, ll=%d, j=%d, jj=%d\n", n, l, ll, j, jj); // update the likelihood gsl_blas_ddot(&u.vector, &u.vector, &result); likelihood += -0.5 * param->lambda_u * result; } } for (j = 0; j < m_num_items; ++j) { gsl_vector_view v = gsl_matrix_row(m_V, j); gsl_vector_view theta_v = gsl_matrix_row(m_theta, j); gsl_vector_memcpy(x, &v.vector); gsl_vector_sub(x, &theta_v.vector); gsl_blas_ddot(x, x, &result); likelihood += -0.5 * param->lambda_v * result; } // update theta if (param->ctr_run && param->theta_opt) { gsl_matrix_set_zero(word_ss); for (j = 0; j < m_num_items; j ++) { gsl_vector_view v = gsl_matrix_row(m_V, j); gsl_vector_view theta_v = gsl_matrix_row(m_theta, j); m = items->m_vec_len[j]; if (m>0) { // m > 0, some users have rated this article const c_document* doc = c->m_docs[j]; likelihood += doc_inference(doc, &theta_v.vector, log_beta, phi, gamma, word_ss, true); optimize_simplex(gamma, &v.vector, param->lambda_v, &theta_v.vector); } else { // m=0, this article has never been rated const c_document* doc = c->m_docs[j]; doc_inference(doc, &theta_v.vector, log_beta, phi, gamma, word_ss, false); vnormalize(gamma); gsl_vector_memcpy(&theta_v.vector, gamma); } } gsl_matrix_memcpy(m_beta, word_ss); for (k = 0; k < m_num_factors; k ++) { gsl_vector_view row = gsl_matrix_row(m_beta, k); vnormalize(&row.vector); } gsl_matrix_memcpy(log_beta, m_beta); mtx_log(log_beta); } time(¤t); elapsed = (int)difftime(current, start); iter++; if (iter > 50 && learning_rate > 0.001) learning_rate /= 2.0; converge = fabs((likelihood-likelihood_old)/likelihood_old); fprintf(file, "%04d %06d %10.5f %.10f\n", iter, elapsed, likelihood, converge); fflush(file); printf("iter=%04d, time=%06d, likelihood=%.5f, converge=%.10f\n", iter, elapsed, likelihood, converge); // save intermediate results if (iter % param->save_lag == 0) { sprintf(name, "%s/%04d-U.dat", directory, iter); FILE * file_U = fopen(name, "w"); gsl_matrix_fwrite(file_U, m_U); fclose(file_U); sprintf(name, "%s/%04d-V.dat", directory, iter); FILE * file_V = fopen(name, "w"); gsl_matrix_fwrite(file_V, m_V); fclose(file_V); if (param->ctr_run && param->theta_opt) { sprintf(name, "%s/%04d-theta.dat", directory, iter); FILE * file_theta = fopen(name, "w"); gsl_matrix_fwrite(file_theta, m_theta); fclose(file_theta); sprintf(name, "%s/%04d-beta.dat", directory, iter); FILE * file_beta = fopen(name, "w"); gsl_matrix_fwrite(file_beta, m_beta); fclose(file_beta); } } } // save final results sprintf(name, "%s/final-U.dat", directory); FILE * file_U = fopen(name, "w"); gsl_matrix_fwrite(file_U, m_U); fclose(file_U); sprintf(name, "%s/final-V.dat", directory); FILE * file_V = fopen(name, "w"); gsl_matrix_fwrite(file_V, m_V); fclose(file_V); if (param->ctr_run && param->theta_opt) { sprintf(name, "%s/final-theta.dat", directory); FILE * file_theta = fopen(name, "w"); gsl_matrix_fwrite(file_theta, m_theta); fclose(file_theta); sprintf(name, "%s/final-beta.dat", directory); FILE * file_beta = fopen(name, "w"); gsl_matrix_fwrite(file_beta, m_beta); fclose(file_beta); } // free memory gsl_vector_free(x); delete [] idx_base; delete [] sel; if (param->ctr_run && param->theta_opt) { gsl_matrix_free(phi); gsl_matrix_free(log_beta); gsl_matrix_free(word_ss); gsl_vector_free(gamma); } }
// Process command line specified options to generate: // 1) Boundary curves -- steady_boundary_curves.dat // 2) Steady turning quantities within feasible region -- steady_feasible.dat // 3) Specified velocity level curves -- steady_velocity.dat // 4) Specified steer torque level curves -- steady_torque.dat // 5) Specified friction coefficient curves -- steady_mew.dat // // Item 1 is done always, because these boundaries are used in the remaining // calculations. Items 2-5 are only done if whipplesteady is invoked with the // correct command line options (see whipplesteady --help). void Whipple::steadyCalcs(steadyOpts_t * opt) { double delta = M_PI / double (opt->N - 1); int ig_index; std::string filename; gsl_matrix * M = gsl_matrix_alloc(opt->N, 9); gsl_vector * steer = &(gsl_matrix_column(M, 0).vector); for (int i = 0; i < opt->N; ++i) gsl_vector_set(steer, i, delta * i); gsl_vector * lean_zero = &(gsl_matrix_column(M, 1).vector); gsl_vector * pitch_zero = &(gsl_matrix_column(M, 2).vector); gsl_vector * lean_inf = &(gsl_matrix_column(M, 3).vector); gsl_vector * pitch_inf = &(gsl_matrix_column(M, 4).vector); gsl_vector * lean_min = &(gsl_matrix_column(M, 5).vector); gsl_vector * pitch_min = &(gsl_matrix_column(M, 6).vector); gsl_vector * lean_max = &(gsl_matrix_column(M, 7).vector); gsl_vector * pitch_max = &(gsl_matrix_column(M, 8).vector); // Find static equilibrium values of lean and pitch ig_index = staticEq(lean_zero, pitch_zero, steer, this); // Find infinite speed equilibrium values of lean and pitch infspeed(lean_inf, pitch_inf, gsl_vector_get(lean_zero, ig_index), gsl_vector_get(pitch_zero, ig_index), ig_index, steer, this); // Find configurational limits cfglim(lean_max, pitch_max, lean_min, pitch_min, steer, this); // Write boundary data to file filename = opt->outfolder; filename += "boundary.dat"; FILE * fp = fopen(filename.c_str(), "wb"); gsl_matrix_fwrite(fp, M); // writes to file in row-major format fclose(fp); // Write Numpy data type information to file filename = opt->outfolder; filename += "boundary_record.py"; writeBndryRecord_dt(filename.c_str()); if (opt->iso_v) { // generate iso velocity curves // Allocate a matrix with N rows, and 1 + 2 x number of iso velocity curves // First column stores steer, subsequent columns store lean and pitch in // alternating columns. gsl_vector * lean_vi, * pitch_vi, * steer_vi; gsl_matrix * Mv = gsl_matrix_alloc(opt->N, 1 + 2*opt->iso_v->size); for (int i = 0; i < opt->N; ++i) gsl_matrix_set(Mv, i, 0, delta * i); steer_vi = &(gsl_matrix_column(Mv, 0).vector); for (unsigned int i = 0; i < opt->iso_v->size; ++i) { lean_vi = &(gsl_matrix_column(Mv, 2*i + 1).vector); pitch_vi = &(gsl_matrix_column(Mv, 2*i + 2).vector); q1 = q3 = 0; q2 = gsl_vector_get(pitch_zero, 0); u5 = -gsl_vector_get(opt->iso_v, i) / (rf + rft); cv(lean_vi, pitch_vi, steer_vi, this); } // for i filename = opt->outfolder; filename += "iso_velocity.dat"; fp = fopen(filename.c_str(), "wb"); gsl_matrix_fwrite(fp, Mv); // writes to file in row-major format fclose(fp); gsl_matrix_free(Mv); // Write Numpy data type information to file, depends upon number of iso // curves specified filename = opt->outfolder; filename += "iso_velocity_record.py"; writeiso_velRecord_dt(filename.c_str(), opt->iso_v->size); } //if (opt->all) // generate all quantities within feasible region // steadyMesh(lean_zero, pitch_zero, lean_inf, pitch_inf, // used for bounds // steer, ig_index, opt); //if (opt->iso_t) // generate iso torque curves // bb->steadyTorque(opt); //if (opt->iso_mew) // generate iso mew curves // bb->steadyMew(opt); gsl_matrix_free(M); } // steadyCalcs()