Search is not available for this dataset
text
string
meta
dict
/* * * Copyright (c) Kresimir Fresl 2002 * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) * * Author acknowledges the support of the Faculty of Civil Engineering, * University of Zagreb, Croatia. * */ #ifndef BOOST_NUMERIC_BINDINGS_BLAS_DETAIL_CBLAS_H #define BOOST_NUMERIC_BINDINGS_BLAS_DETAIL_CBLAS_H // // MKL-specific CBLAS include // #if defined BOOST_NUMERIC_BINDINGS_BLAS_MKL extern "C" { #include <mkl_cblas.h> //#include <mkl_service.h> // // mkl_types.h defines P4 macro which breaks MPL, undefine it here. // #undef P4 } // // Default CBLAS include // #else extern "C" { #include <cblas.h> } #endif #endif
{ "alphanum_fraction": 0.7284946237, "avg_line_length": 17.7142857143, "ext": "h", "hexsha": "d0df1fe638efeca8b422f5ca387a0518c970c25f", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "2739a23f23d797dbfecec79d409e914e13c45c67", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "siconos/siconos-deb", "max_forks_repo_path": "externals/numeric_bindings/boost/numeric/bindings/blas/detail/cblas.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "2739a23f23d797dbfecec79d409e914e13c45c67", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "siconos/siconos-deb", "max_issues_repo_path": "externals/numeric_bindings/boost/numeric/bindings/blas/detail/cblas.h", "max_line_length": 72, "max_stars_count": null, "max_stars_repo_head_hexsha": "2739a23f23d797dbfecec79d409e914e13c45c67", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "siconos/siconos-deb", "max_stars_repo_path": "externals/numeric_bindings/boost/numeric/bindings/blas/detail/cblas.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 205, "size": 744 }
#include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> int normalizeVector( gsl_vector *vector ) { double min = gsl_vector_min( vector ); double norm = gsl_vector_max( vector ) - min; gsl_vector_add_constant( vector, -min ); gsl_vector_scale( vector, 1/norm ); return 0; }
{ "alphanum_fraction": 0.7305389222, "avg_line_length": 23.8571428571, "ext": "c", "hexsha": "ced9c1f15df5ffe835db94a6d9d963d9625aae7c", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "825dbd5c5495b0ce0a0d14a5bed865b9bfdda98d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jakeinater/spectralILU", "max_forks_repo_path": "src/norm.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "825dbd5c5495b0ce0a0d14a5bed865b9bfdda98d", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "jakeinater/spectralILU", "max_issues_repo_path": "src/norm.c", "max_line_length": 46, "max_stars_count": null, "max_stars_repo_head_hexsha": "825dbd5c5495b0ce0a0d14a5bed865b9bfdda98d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jakeinater/spectralILU", "max_stars_repo_path": "src/norm.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 97, "size": 334 }
#include <math.h> #include <stdlib.h> #if !defined(__APPLE__) #include <malloc.h> #endif #include <stdio.h> #include <assert.h> #include <time.h> #include <string.h> #include <fftw3.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_sf_erf.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_sf_gamma.h> #include <gsl/gsl_sf_legendre.h> #include <gsl/gsl_sf_bessel.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_eigen.h> #include <gsl/gsl_sf_expint.h> #include <gsl/gsl_deriv.h> #include <gsl/gsl_interp2d.h> #include <gsl/gsl_spline2d.h> #include "../cosmolike_core/theory/basics.c" #include "../cosmolike_core/theory/structs.c" #include "../cosmolike_core/theory/parameters.c" #include "../cosmolike_core/emu17/P_cb/emu.c" #include "../cosmolike_core/theory/recompute.c" #include "../cosmolike_core/theory/cosmo3D.c" #include "../cosmolike_core/theory/redshift_spline.c" #include "../cosmolike_core/theory/halo.c" #include "../cosmolike_core/theory/HOD.c" #include "../cosmolike_core/theory/pt.c" #include "../cosmolike_core/theory/cosmo2D_fourier.c" #include "../cosmolike_core/theory/IA.c" #include "../cosmolike_core/theory/cluster.c" #include "../cosmolike_core/theory/BAO.c" #include "../cosmolike_core/theory/external_prior.c" #include "../cosmolike_core/theory/init_baryon.c" #include "init_emu.c" double C_shear_tomo_sys(double ell,int z1,int z2); double C_cgl_tomo_sys(double ell_Cluster,int zl,int nN, int zs); double C_gl_tomo_sys(double ell,int zl,int zs); void set_data_shear(int Ncl, double *ell, double *data, int start); void set_data_ggl(int Ncl, double *ell, double *data, int start); void set_data_clustering(int Ncl, double *ell, double *data, int start); void set_data_cluster_N(double *data, int start); void set_data_cgl(double *ell_Cluster, double *data, int start); void compute_data_vector(char *details, double OMM, double S8, double NS, double W0,double WA, double OMB, double H0, double MGSigma, double MGmu, double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8, double B9, double B10, double SP1, double SP2, double SP3, double SP4, double SP5, double SP6, double SP7, double SP8, double SP9, double SP10, double SPS1, double CP1, double CP2, double CP3, double CP4, double CP5, double CP6, double CP7, double CP8, double CP9, double CP10, double CPS1, double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10, double A_ia, double beta_ia, double eta_ia, double eta_ia_highz, double LF_alpha, double LF_P, double LF_Q, double LF_red_alpha, double LF_red_P, double LF_red_Q,double mass_obs_norm, double mass_obs_slope, double mass_z_slope, double mass_obs_scatter_norm, double mass_obs_scatter_mass_slope, double mass_obs_scatter_z_slope, double Q1, double Q2, double Q3); double log_multi_like(double OMM, double S8, double NS, double W0,double WA, double OMB, double H0, double MGSigma, double MGmu, double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8, double B9, double B10, double SP1, double SP2, double SP3, double SP4, double SP5, double SP6, double SP7, double SP8, double SP9, double SP10, double SPS1, double CP1, double CP2, double CP3, double CP4, double CP5, double CP6, double CP7, double CP8, double CP9, double CP10, double CPS1, double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10, double A_ia, double beta_ia, double eta_ia, double eta_ia_highz, double LF_alpha, double LF_P, double LF_Q, double LF_red_alpha, double LF_red_P, double LF_red_Q,double mass_obs_norm, double mass_obs_slope, double mass_z_slope, double mass_obs_scatter_norm, double mass_obs_scatter_mass_slope, double mass_obs_scatter_z_slope, double Q1, double Q2, double Q3); void write_vector_wrapper(char *details, input_cosmo_params ic, input_nuisance_params in); double log_like_wrapper(input_cosmo_params ic, input_nuisance_params in); int get_N_tomo_shear(void); int get_N_tomo_clustering(void); int get_N_ggl(void); int get_N_ell(void); int get_N_tomo_shear(void){ return tomo.shear_Nbin; } int get_N_tomo_clustering(void){ return tomo.clustering_Nbin; } int get_N_ggl(void){ return tomo.ggl_Npowerspectra; } int get_N_ell(void){ return like.Ncl; } double C_shear_tomo_sys(double ell, int z1, int z2) { double C; // C= C_shear_tomo_nointerp(ell,z1,z2); // if(like.IA==1) C+=C_II_nointerp(ell,z1,z2)+C_GI_nointerp(ell,z1,z2); if(like.IA!=1) C= C_shear_tomo_nointerp(ell,z1,z2); //if(like.IA==1) C= C_shear_shear_IA(ell,z1,z2); if(like.IA==1) C = C_shear_tomo_nointerp(ell,z1,z2)+C_II_nointerp(ell,z1,z2)+C_GI_nointerp(ell,z1,z2); if(like.IA==2) C += C_II_lin_nointerp(ell,z1,z2)+C_GI_lin_nointerp(ell,z1,z2); if(like.shearcalib==1) C *=(1.0+nuisance.shear_calibration_m[z1])*(1.0+nuisance.shear_calibration_m[z2]); //printf("%le %d %d %le\n",ell,z1,z2,C_shear_tomo_nointerp(ell,z1,z2)+C_II_JB_nointerp(ell,z1,z2)+C_GI_JB_nointerp(ell,z1,z2)); return C; } double C_gl_tomo_sys(double ell,int zl,int zs) { double C; // C=C_gl_tomo_nointerp(ell,zl,zs); // if(like.IA==1) C += C_gI_nointerp(ell,zl,zs); if(like.IA!=1) C=C_gl_tomo_nointerp(ell,zl,zs); if(like.IA==1) C = C_ggl_IA(ell,zl,zs); if(like.IA==2) C += C_gI_lin_nointerp(ell,zl,zs); if(like.shearcalib==1) C *=(1.0+nuisance.shear_calibration_m[zs]); return C; } double C_cgl_tomo_sys(double ell_Cluster, int zl,int nN, int zs) { double C; C=C_cgl_tomo_nointerp(ell_Cluster,zl,nN,zs); //if(like.IA!=0) C += if(like.shearcalib==1) C *=(1.0+nuisance.shear_calibration_m[zs]); return C; } void set_data_shear(int Ncl, double *ell, double *data, int start) { int i,z1,z2,nz; double a; for (nz = 0; nz < tomo.shear_Npowerspectra; nz++){ z1 = Z1(nz); z2 = Z2(nz); for (i = 0; i < Ncl; i++){ if (ell[i] < like.lmax_shear){ data[Ncl*nz+i] = C_shear_tomo_sys(ell[i],z1,z2);} else {data[Ncl*nz+i] = 0.;} } } } void set_data_ggl(int Ncl, double *ell, double *data, int start) { int i, zl,zs,nz; for (nz = 0; nz < tomo.ggl_Npowerspectra; nz++){ zl = ZL(nz); zs = ZS(nz); for (i = 0; i < Ncl; i++){ if (test_kmax(ell[i],zl)){ data[start+(Ncl*nz)+i] = C_gl_tomo_sys(ell[i],zl,zs); } else{ data[start+(Ncl*nz)+i] = 0.; } } } } void set_data_clustering(int Ncl, double *ell, double *data, int start){ int i, nz; for (nz = 0; nz < tomo.clustering_Npowerspectra; nz++){ //printf("%d %e %e\n",nz, gbias.b[nz][1],pf_photoz(gbias.b[nz][1],nz)); for (i = 0; i < Ncl; i++){ if (test_kmax(ell[i],nz)){data[start+(Ncl*nz)+i] = C_cl_tomo_nointerp(ell[i],nz,nz);} else{data[start+(Ncl*nz)+i] = 0.;} //printf("%d %d %le %le\n",nz,nz,ell[i],data[Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra + nz)+i]); } } } void set_data_cluster_N(double *data, int start){ int nN, nz; for (nz = 0; nz < tomo.cluster_Nbin; nz++){ for (nN = 0; nN < Cluster.N200_Nbin; nN++){ data[start+Cluster.N200_Nbin*nz+nN] = N_N200(nz, nN); } } } void set_data_cgl(double *ell_Cluster, double *data, int start) { int zl,zs,nN,nz,i,j; for(nN = 0; nN < Cluster.N200_Nbin; nN++){ for (nz = 0; nz < tomo.cgl_Npowerspectra; nz++){ zl = ZC(nz); zs = ZSC(nz); for (i = 0; i < Cluster.lbin; i++){ j = start; j += (nz*Cluster.N200_Nbin+nN)*Cluster.lbin +i; data[j] = C_cgl_tomo_sys(ell_Cluster[i],zl,nN,zs); } } } } int set_cosmology_params(double OMM, double S8, double NS, double W0,double WA, double OMB, double H0, double MGSigma, double MGmu) { cosmology.Omega_m=OMM; cosmology.Omega_v= 1.0-cosmology.Omega_m; cosmology.sigma_8=S8; cosmology.n_spec= NS; cosmology.w0=W0; cosmology.wa=WA; cosmology.omb=OMB; cosmology.h0=H0; cosmology.MGSigma=MGSigma; cosmology.MGmu=MGmu; if (cosmology.Omega_m < 0.04 || cosmology.Omega_m > 0.7) return 0; if (cosmology.omb < 0.04 || cosmology.omb > 0.055) return 0; if (cosmology.sigma_8 < 0.4 || cosmology.sigma_8 > 1.2) return 0; if (cosmology.n_spec < 0.84 || cosmology.n_spec > 1.06) return 0; if (cosmology.w0 < -2.1 || cosmology.w0 > -0.0) return 0; if (cosmology.wa < -2.6 || cosmology.wa > 2.6) return 0; if (cosmology.h0 < 0.4 || cosmology.h0 > 0.9) return 0; return 1; } void set_nuisance_shear_calib(double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10) { nuisance.shear_calibration_m[0] = M1; nuisance.shear_calibration_m[1] = M2; nuisance.shear_calibration_m[2] = M3; nuisance.shear_calibration_m[3] = M4; nuisance.shear_calibration_m[4] = M5; nuisance.shear_calibration_m[5] = M6; nuisance.shear_calibration_m[6] = M7; nuisance.shear_calibration_m[7] = M8; nuisance.shear_calibration_m[8] = M9; nuisance.shear_calibration_m[9] = M10; } int set_nuisance_shear_photoz(double SP1,double SP2,double SP3,double SP4,double SP5,double SP6,double SP7,double SP8,double SP9,double SP10,double SPS1) { int i; nuisance.bias_zphot_shear[0]=SP1; nuisance.bias_zphot_shear[1]=SP2; nuisance.bias_zphot_shear[2]=SP3; nuisance.bias_zphot_shear[3]=SP4; nuisance.bias_zphot_shear[4]=SP5; nuisance.bias_zphot_shear[5]=SP6; nuisance.bias_zphot_shear[6]=SP7; nuisance.bias_zphot_shear[7]=SP8; nuisance.bias_zphot_shear[8]=SP9; nuisance.bias_zphot_shear[9]=SP10; for (i=0;i<tomo.shear_Nbin; i++){ nuisance.sigma_zphot_shear[i]=SPS1; if (nuisance.sigma_zphot_shear[i]<0.000001) return 0; } return 1; } int set_nuisance_clustering_photoz(double CP1,double CP2,double CP3,double CP4,double CP5,double CP6,double CP7,double CP8,double CP9,double CP10,double CPS1) { int i; nuisance.bias_zphot_clustering[0]=CP1; nuisance.bias_zphot_clustering[1]=CP2; nuisance.bias_zphot_clustering[2]=CP3; nuisance.bias_zphot_clustering[3]=CP4; nuisance.bias_zphot_clustering[4]=CP5; nuisance.bias_zphot_clustering[5]=CP6; nuisance.bias_zphot_clustering[6]=CP7; nuisance.bias_zphot_clustering[7]=CP8; nuisance.bias_zphot_clustering[8]=CP9; nuisance.bias_zphot_clustering[9]=CP10; for (i=0;i<tomo.clustering_Nbin; i++){ nuisance.sigma_zphot_clustering[i]=CPS1; if (nuisance.sigma_zphot_clustering[i]<0.0001) return 0; } return 1; } int set_nuisance_ia(double A_ia, double beta_ia, double eta_ia, double eta_ia_highz, double LF_alpha, double LF_P, double LF_Q, double LF_red_alpha, double LF_red_P, double LF_red_Q) { nuisance.A_ia=A_ia; nuisance.beta_ia=beta_ia; nuisance.eta_ia=eta_ia; nuisance.eta_ia_highz=eta_ia_highz; nuisance.LF_alpha=LF_alpha; nuisance.LF_P=LF_P; nuisance.LF_Q=LF_Q; nuisance.LF_red_alpha=LF_red_alpha; nuisance.LF_red_P=LF_red_P; nuisance.LF_red_Q=LF_red_Q; if (nuisance.A_ia < 0.0 || nuisance.A_ia > 10.0) return 0; if (nuisance.beta_ia < -1.0 || nuisance.beta_ia > 3.0) return 0; if (nuisance.eta_ia < -3.0 || nuisance.eta_ia> 3.0) return 0; if (nuisance.eta_ia_highz < -1.0 || nuisance.eta_ia_highz> 1.0) return 0; // if(like.IA!=0){ // if (check_LF()) return 0; // } return 1; } int set_nuisance_cluster_Mobs(double cluster_Mobs_lgN0, double cluster_Mobs_alpha, double cluster_Mobs_beta, double cluster_Mobs_sigma0, double cluster_Mobs_sigma_qm, double cluster_Mobs_sigma_qz) { // nuisance.cluster_Mobs_lgM0 = mass_obs_norm; //fiducial : 1.72+log(1.e+14*0.7); could use e.g. sigma = 0.2 Gaussian prior // nuisance.cluster_Mobs_alpha = mass_obs_slope; //fiducial: 1.08; e.g. sigma = 0.1 Gaussian prior // nuisance.cluster_Mobs_beta = mass_z_slope; //fiducial: 0.0; e.g. sigma = 0.1 Gaussian prior // nuisance.cluster_Mobs_sigma = mass_obs_scatter; //fiducial 0.25; e.g. sigma = 0.05 Gaussian prior // fiducial values and priors from Murata et al. (2018) except for redshift-related parameters nuisance.cluster_Mobs_lgN0 = cluster_Mobs_lgN0; //fiducial: 3.207, flat prior [0.5, 5.0] nuisance.cluster_Mobs_alpha = cluster_Mobs_alpha; //fiducial: 0.993, flat prior [0.0, 2.0] nuisance.cluster_Mobs_beta = cluster_Mobs_beta; //fiducial: 0.0, flat prior [-1.5, 1.5] nuisance.cluster_Mobs_sigma0 = cluster_Mobs_sigma0; //fiducial: 0.456, flat prior [0.0, 1.5] nuisance.cluster_Mobs_sigma_qm = cluster_Mobs_sigma_qm; //fiducial: -0.169, flat prior [-1.5, 1.5] nuisance.cluster_Mobs_sigma_qz = cluster_Mobs_sigma_qz; //fiducial: 0.0, flat prior [-1.5, 1.5] if (nuisance.cluster_Mobs_lgN0 < 0.5 || nuisance.cluster_Mobs_lgN0 > 5.0) return 0; if (nuisance.cluster_Mobs_alpha < 0.0 || nuisance.cluster_Mobs_alpha > 2.0) return 0; if (nuisance.cluster_Mobs_beta < -1.5 || nuisance.cluster_Mobs_beta > 1.5) return 0; if (nuisance.cluster_Mobs_sigma0 < 0.0|| nuisance.cluster_Mobs_sigma0 > 1.5) return 0; if (nuisance.cluster_Mobs_sigma_qm < -1.5 && nuisance.cluster_Mobs_sigma_qm > 1.5) return 0; if (nuisance.cluster_Mobs_sigma_qz < -1.5 && nuisance.cluster_Mobs_sigma_qz > 1.5)return 0; return 1; } int set_nuisance_gbias(double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8,double B9, double B10) { int i; gbias.b[0] = B1; gbias.b[1] = B2; gbias.b[2] = B3; gbias.b[3] = B4; gbias.b[4] = B5; gbias.b[5] = B6; gbias.b[6] = B7; gbias.b[7] = B8; gbias.b[8] = B9; gbias.b[9] = B10; if(like.bias==1){ for (i = 0; i < 10; i++){ if (gbias.b[i] < 0.8 || gbias.b[i] > 3.0) return 0; } } return 1; } double log_multi_like(double OMM, double S8, double NS, double W0,double WA, double OMB, double H0, double MGSigma, double MGmu, double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8, double B9, double B10, double SP1, double SP2, double SP3, double SP4, double SP5, double SP6, double SP7, double SP8, double SP9, double SP10, double SPS1, double CP1, double CP2, double CP3, double CP4, double CP5, double CP6, double CP7, double CP8, double CP9, double CP10, double CPS1, double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10, double A_ia, double beta_ia, double eta_ia, double eta_ia_highz, double LF_alpha, double LF_P, double LF_Q, double LF_red_alpha, double LF_red_P, double LF_red_Q,double mass_obs_norm, double mass_obs_slope, double mass_z_slope, double mass_obs_scatter_norm, double mass_obs_scatter_mass_slope, double mass_obs_scatter_z_slope, double Q1, double Q2, double Q3) { int i,j,k,m=0,l; static double *pred; static double *ell; static double *ell_Cluster; static double darg; double chisqr,a,log_L_prior=0.0, log_L=0.0; if(ell==0){ pred= create_double_vector(0, like.Ndata-1); ell= create_double_vector(0, like.Ncl-1); darg=(log(like.lmax)-log(like.lmin))/like.Ncl; for (l=0;l<like.Ncl;l++){ ell[l]=exp(log(like.lmin)+(l+0.5)*darg); } ell_Cluster= create_double_vector(0, Cluster.lbin-1); darg=(log(Cluster.l_max)-log(Cluster.l_min))/Cluster.lbin; for (l=0;l<Cluster.lbin;l++){ ell_Cluster[l]=exp(log(Cluster.l_min)+(l+0.5)*darg); } } if (set_cosmology_params(OMM,S8,NS,W0,WA,OMB,H0,MGSigma,MGmu)==0){ printf("Cosmology out of bounds\n"); return -1.0e15; } set_nuisance_shear_calib(M1,M2,M3,M4,M5,M6,M7,M8,M9,M10); if (set_nuisance_shear_photoz(SP1,SP2,SP3,SP4,SP5,SP6,SP7,SP8,SP9,SP10,SPS1)==0){ printf("Shear photo-z sigma too small\n"); return -1.0e15; } if (set_nuisance_clustering_photoz(CP1,CP2,CP3,CP4,CP5,CP6,CP7,CP8,CP9,CP10,CPS1)==0){ printf("Clustering photo-z sigma too small\n"); return -1.0e15; } if (set_nuisance_ia(A_ia,beta_ia,eta_ia,eta_ia_highz,LF_alpha,LF_P,LF_Q,LF_red_alpha,LF_red_P,LF_red_Q)==0){ printf("IA parameters out of bounds\n"); return -1.0e15; } if (set_nuisance_gbias(B1,B2,B3,B4,B5,B6,B7,B8,B9,B10)==0){ printf("Bias out of bounds\n"); return -1.0e15; } //printf("like %le %le %le %le %le %le %le %le\n",cosmology.Omega_m, cosmology.Omega_v,cosmology.sigma_8,cosmology.n_spec,cosmology.w0,cosmology.wa,cosmology.omb,cosmology.h0); // printf("like %le %le %le %le\n",gbias.b[0][0], gbias.b[1][0], gbias.b[2][0], gbias.b[3][0]); // for (i=0; i<10; i++){ // printf("nuisance %le %le %le\n",nuisance.shear_calibration_m[i],nuisance.bias_zphot_shear[i],nuisance.sigma_zphot_shear[i]); // } log_L_prior=0.0; // if(like.Aubourg_Planck_BAO_SN==1) log_L_prior+=log_L_Planck_BAO_SN(); // if(like.SN==1) log_L_prior+=log_L_SN(); //if(like.BAO==1) log_L_prior+=log_L_BAO(); // if(like.Planck==1) log_L_prior+=log_L_Planck(); // if(like.Planck15_BAO_w0wa==1) log_L_prior+=log_L_Planck15_BAO_w0wa();//CH //if(like.Planck15_BAO_H070p6_JLA_w0wa==1) log_L_prior+=log_L_Planck15_BAO_H070p6_JLA_w0wa();//CH // if(like.IA!=0) log_L_prior+=log_L_ia(); // if(like.IA!=0) log_L_prior+=log_like_f_red(); if(like.wlphotoz!=0) log_L_prior+=log_L_wlphotoz(); if(like.clphotoz!=0) log_L_prior+=log_L_clphotoz(); if(like.shearcalib==1) log_L_prior+=log_L_shear_calib(); if(like.IA!=0) { log_L = 0.0; log_L -= pow((nuisance.A_ia - prior.A_ia[0])/prior.A_ia[1],2.0); log_L -= pow((nuisance.beta_ia - prior.beta_ia[0])/prior.beta_ia[1],2.0); log_L -= pow((nuisance.eta_ia - prior.eta_ia[0])/prior.eta_ia[1],2.0); log_L -= pow((nuisance.eta_ia_highz - prior.eta_ia_highz[0])/prior.eta_ia_highz[1],2.0); log_L_prior+=0.5*log_L; } if(like.baryons==1){ log_L = 0.0; log_L -= pow((Q1 - prior.bary_Q1[0])/prior.bary_Q1[1],2.0); log_L -= pow((Q2 - prior.bary_Q2[0])/prior.bary_Q2[1],2.0); log_L -= pow((Q3 - prior.bary_Q3[0])/prior.bary_Q3[1],2.0); log_L_prior+=0.5*log_L; } // if(like.clusterMobs==1) log_L_prior+=log_L_clusterMobs(); // printf("%d %d %d %d\n",like.BAO,like.wlphotoz,like.clphotoz,like.shearcalib); // printf("logl %le %le %le %le\n",log_L_shear_calib(),log_L_wlphotoz(),log_L_clphotoz(),log_L_clusterMobs()); int start=0; if(like.shear_shear==1) { set_data_shear(like.Ncl, ell, pred, start); start=start+like.Ncl*tomo.shear_Npowerspectra; } if(like.shear_pos==1){ set_data_ggl(like.Ncl, ell, pred, start); start=start+like.Ncl*tomo.ggl_Npowerspectra; } if(like.pos_pos==1){ set_data_clustering(like.Ncl,ell,pred, start); start=start+like.Ncl*tomo.clustering_Npowerspectra; } chisqr=0.0; for (i=0; i<like.Ndata; i++){ for (j=0; j<like.Ndata; j++){ a=(pred[i]-data_read(1,i)+Q1*bary_read(1,0,i)+Q2*bary_read(1,1,i)+Q3*bary_read(1,2,i))*invcov_read(1,i,j)*(pred[j]-data_read(1,j)+Q1*bary_read(1,0,j)+Q2*bary_read(1,1,j)+Q3*bary_read(1,2,j)); //a=(pred[i]-data_read(1,i))*invcov_read(1,i,j)*(pred[j]-data_read(1,j)); chisqr=chisqr+a; } // if (fabs(data_read(1,i)) < 1.e-25){ // printf("%d %le %le %le\n",i,data_read(1,i),pred[i],invcov_read(1,i,i)); // } } if (chisqr<0.0){ printf("error: chisqr = %le\n",chisqr); //exit(EXIT_FAILURE); } // printf("%le\n",chisqr); return -0.5*chisqr+log_L_prior; } void compute_data_vector(char *details, double OMM, double S8, double NS, double W0,double WA, double OMB, double H0, double MGSigma, double MGmu, double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8, double B9, double B10, double SP1, double SP2, double SP3, double SP4, double SP5,double SP6, double SP7, double SP8, double SP9, double SP10, double SPS1, double CP1, double CP2, double CP3, double CP4, double CP5, double CP6, double CP7, double CP8, double CP9, double CP10, double CPS1, double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10, double A_ia, double beta_ia, double eta_ia, double eta_ia_highz, double LF_alpha, double LF_P, double LF_Q, double LF_red_alpha, double LF_red_P, double LF_red_Q, double mass_obs_norm, double mass_obs_slope, double mass_z_slope, double mass_obs_scatter_norm, double mass_obs_scatter_mass_slope, double mass_obs_scatter_z_slope, double Q1, double Q2, double Q3) { int i,j,k,m=0,l; static double *pred; static double *ell; static double *ell_Cluster; static double darg; double chisqr,a,log_L_prior=0.0; if(ell==0){ pred= create_double_vector(0, like.Ndata-1); ell= create_double_vector(0, like.Ncl-1); darg=(log(like.lmax)-log(like.lmin))/like.Ncl; for (l=0;l<like.Ncl;l++){ ell[l]=exp(log(like.lmin)+(l+0.5)*darg); } ell_Cluster= create_double_vector(0, Cluster.lbin-1); darg=(log(Cluster.l_max)-log(Cluster.l_min))/Cluster.lbin; for (l=0;l<Cluster.lbin;l++){ ell_Cluster[l]=exp(log(Cluster.l_min)+(l+0.5)*darg); } } // for (l=0;l<like.Ncl;l++){ // printf("%d %le\n",i,ell[l]); // } set_cosmology_params(OMM,S8,NS,W0,WA,OMB,H0,MGSigma,MGmu); set_nuisance_shear_calib(M1,M2,M3,M4,M5,M6,M7,M8,M9,M10); set_nuisance_shear_photoz(SP1,SP2,SP3,SP4,SP5,SP6,SP7,SP8,SP9,SP10,SPS1); set_nuisance_clustering_photoz(CP1,CP2,CP3,CP4,CP5,CP6,CP7,CP8,CP9,CP10,CPS1); set_nuisance_ia(A_ia,beta_ia,eta_ia,eta_ia_highz,LF_alpha,LF_P,LF_Q,LF_red_alpha,LF_red_P,LF_red_Q); set_nuisance_gbias(B1,B2,B3,B4,B5,B6,B7,B8,B9,B10); int start=0; if(like.shear_shear==1) { set_data_shear(like.Ncl, ell, pred, start); start=start+like.Ncl*tomo.shear_Npowerspectra; } if(like.shear_pos==1){ //printf("ggl\n"); set_data_ggl(like.Ncl, ell, pred, start); start=start+like.Ncl*tomo.ggl_Npowerspectra; } if(like.pos_pos==1){ //printf("clustering\n"); set_data_clustering(like.Ncl,ell,pred, start); start=start+like.Ncl*tomo.clustering_Npowerspectra; } FILE *F; char filename[300]; if (strstr(details,"FM") != NULL){ sprintf(filename,"%s",details); } else {sprintf(filename,"datav/%s_%s",like.probes,details);} F=fopen(filename,"w"); for (i=0;i<like.Ndata; i++){ fprintf(F,"%d %le\n",i,pred[i]); //printf("%d %le\n",i,pred[i]); } fclose(F); // printf("&gbias.b1_function %p\n",&gbias.b1_function); // printf("gbias.b1_function %p\n",gbias.b1_function); // printf("bgal_z %p\n",bgal_z); // printf("&bgal_z %p\n",&bgal_z); // printf("b1_per_bin %p\n",b1_per_bin); // printf("&b1_per_bin %p\n",&b1_per_bin); } void write_datavector_wrapper(char *details, input_cosmo_params ic, input_nuisance_params in) { compute_data_vector(details, ic.omega_m, ic.sigma_8, ic.n_s, ic.w0, ic.wa, ic.omega_b, ic.h0, ic.MGSigma, ic.MGmu, in.bias[0], in.bias[1], in.bias[2], in.bias[3],in.bias[4], in.bias[5], in.bias[6], in.bias[7],in.bias[8], in.bias[9], in.source_z_bias[0], in.source_z_bias[1], in.source_z_bias[2], in.source_z_bias[3], in.source_z_bias[4], in.source_z_bias[5], in.source_z_bias[6], in.source_z_bias[7], in.source_z_bias[8], in.source_z_bias[9], in.source_z_s, in.lens_z_bias[0], in.lens_z_bias[1], in.lens_z_bias[2], in.lens_z_bias[3], in.lens_z_bias[4], in.lens_z_bias[5], in.lens_z_bias[6], in.lens_z_bias[7], in.lens_z_bias[8], in.lens_z_bias[9], in.lens_z_s, in.shear_m[0], in.shear_m[1], in.shear_m[2], in.shear_m[3], in.shear_m[4], in.shear_m[5], in.shear_m[6], in.shear_m[7], in.shear_m[8], in.shear_m[9], in.A_ia, in.beta_ia, in.eta_ia, in.eta_ia_highz, in.lf[0], in.lf[1], in.lf[2], in.lf[3], in.lf[4], in.lf[5], in.m_lambda[0], in.m_lambda[1], in.m_lambda[2], in.m_lambda[3], in.m_lambda[4], in.m_lambda[5],in.bary[0], in.bary[1], in.bary[2]); } double log_like_wrapper(input_cosmo_params ic, input_nuisance_params in) { double like = log_multi_like(ic.omega_m, ic.sigma_8, ic.n_s, ic.w0, ic.wa, ic.omega_b, ic.h0, ic.MGSigma, ic.MGmu, in.bias[0], in.bias[1], in.bias[2], in.bias[3],in.bias[4], in.bias[5], in.bias[6], in.bias[7],in.bias[8], in.bias[9], in.source_z_bias[0], in.source_z_bias[1], in.source_z_bias[2], in.source_z_bias[3], in.source_z_bias[4], in.source_z_bias[5], in.source_z_bias[6], in.source_z_bias[7], in.source_z_bias[8], in.source_z_bias[9], in.source_z_s, in.lens_z_bias[0], in.lens_z_bias[1], in.lens_z_bias[2], in.lens_z_bias[3], in.lens_z_bias[4], in.lens_z_bias[5], in.lens_z_bias[6], in.lens_z_bias[7], in.lens_z_bias[8], in.lens_z_bias[9], in.lens_z_s, in.shear_m[0], in.shear_m[1], in.shear_m[2], in.shear_m[3], in.shear_m[4], in.shear_m[5], in.shear_m[6], in.shear_m[7], in.shear_m[8], in.shear_m[9], in.A_ia, in.beta_ia, in.eta_ia, in.eta_ia_highz, in.lf[0], in.lf[1], in.lf[2], in.lf[3], in.lf[4], in.lf[5], in.m_lambda[0], in.m_lambda[1], in.m_lambda[2], in.m_lambda[3], in.m_lambda[4], in.m_lambda[5],in.bary[0], in.bary[1], in.bary[2]); return like; } void save_zdistr_sources(int zs){ double z,dz =(redshift.shear_zdistrpar_zmax-redshift.shear_zdistrpar_zmin)/300.0; printf("Printing redshift distribution n(z) for source redshift bin %d\n",zs); FILE *F1; char filename[300]; sprintf(filename,"zdistris/zdist_sources_bin%d.txt",zs); F1 = fopen(filename,"w"); for (z =redshift.shear_zdistrpar_zmin; z< redshift.shear_zdistrpar_zmax; z+= dz){ fprintf(F1,"%e %e\n", z, zdistr_photoz(z,zs)); } } void save_zdistr_lenses(int zl){ double z,dz =(redshift.clustering_zdistrpar_zmax-redshift.clustering_zdistrpar_zmin)/300.0; printf("Printing redshift distribution n(z) and bias b(z) for lens redshift bin %d\n",zl); FILE *F1; char filename[300]; sprintf(filename,"zdistris/zdist_lenses_bin%d.txt", zl); F1 = fopen(filename,"w"); for (z =redshift.clustering_zdistrpar_zmin; z< redshift.clustering_zdistrpar_zmax; z+= dz){ fprintf(F1,"%e %e\n", z, pf_photoz(z,zl)); } } int main(int argc, char** argv) { clock_t begin, end; double time_spent; int i; char arg1[400],arg2[400],arg3[400]; /* here, do your time-consuming job */ int sce=atoi(argv[1]); int N_scenarios=36; double area_table[36]={7623.22,14786.3,9931.47,8585.43,17681.8,15126.9,9747.99,8335.08,9533.42,18331.3,12867.8,17418.9,19783.1,12538.8,15260.0,16540.7,19636.8,11112.7,10385.5,16140.2,18920.1,17976.2,11352.0,9214.77,16910.7,11995.6,16199.8,14395.1,8133.86,13510.5,19122.3,15684.5,12014.8,14059.7,10919.3,13212.7}; double nsource_table[36]={13.991,33.3975,17.069,28.4875,35.3643,10.3802,11.1105,29.5904,31.4608,15.7463,13.3066,9.07218,9.58719,16.3234,25.8327,10.7415,38.0412,32.8821,19.8893,27.0369,15.1711,14.2418,19.1851,26.926,22.0012,12.6553,18.6304,11.9787,36.8728,22.5265,17.4381,12.3424,10.0095,23.5979,20.8771,24.8956}; double nlens_table[36]={22.9726 ,61.5948 ,28.7809 ,51.4354 ,65.7226 ,16.3777 ,17.6899 ,53.6984 ,57.562 ,26.266 ,21.703 ,14.0587 ,14.9667 ,27.36 ,46.0364 ,17.0253 ,71.39 ,60.5184 ,34.2283 ,48.4767 ,25.1812 ,23.44 ,32.8578 ,48.2513 ,38.3766 ,20.5029 ,31.783 ,19.2647 ,68.9094 ,39.4168 ,29.4874 ,19.9292 ,15.7162 ,41.5487 ,36.1616 ,44.148}; char survey_designation[1][200]={"LSST"}; char tomo_binning_source[1][200]={"source_std"}; char tomo_binning_lens[1][200]={"LSST_gold"}; char source_zfile[36][400]={"wl_redshift_model0_WLz01.880307e-01_WLalpha8.485694e-01.txt", "wl_redshift_model1_WLz01.731166e-01_WLalpha7.662434e-01.txt", "wl_redshift_model2_WLz01.846221e-01_WLalpha8.297540e-01.txt", "wl_redshift_model3_WLz01.758423e-01_WLalpha7.812893e-01.txt", "wl_redshift_model4_WLz01.721357e-01_WLalpha7.608290e-01.txt", "wl_redshift_model5_WLz01.931476e-01_WLalpha8.768147e-01.txt", "wl_redshift_model6_WLz01.919821e-01_WLalpha8.703814e-01.txt", "wl_redshift_model7_WLz01.751912e-01_WLalpha7.776952e-01.txt", "wl_redshift_model8_WLz01.741405e-01_WLalpha7.718958e-01.txt", "wl_redshift_model9_WLz01.860048e-01_WLalpha8.373865e-01.txt", "wl_redshift_model10_WLz01.888904e-01_WLalpha8.533151e-01.txt", "wl_redshift_model11_WLz01.954564e-01_WLalpha8.895592e-01.txt", "wl_redshift_model12_WLz01.945099e-01_WLalpha8.843347e-01.txt", "wl_redshift_model13_WLz01.853877e-01_WLalpha8.339802e-01.txt", "wl_redshift_model14_WLz01.775192e-01_WLalpha7.905458e-01.txt", "wl_redshift_model15_WLz01.925611e-01_WLalpha8.735775e-01.txt", "wl_redshift_model16_WLz01.708849e-01_WLalpha7.539247e-01.txt", "wl_redshift_model17_WLz01.733832e-01_WLalpha7.677150e-01.txt", "wl_redshift_model18_WLz01.820009e-01_WLalpha8.152851e-01.txt", "wl_redshift_model19_WLz01.767381e-01_WLalpha7.862345e-01.txt", "wl_redshift_model20_WLz01.866426e-01_WLalpha8.409073e-01.txt", "wl_redshift_model21_WLz01.877261e-01_WLalpha8.468882e-01.txt", "wl_redshift_model22_WLz01.826188e-01_WLalpha8.186960e-01.txt", "wl_redshift_model23_WLz01.768086e-01_WLalpha7.866234e-01.txt", "wl_redshift_model24_WLz01.802711e-01_WLalpha8.057362e-01.txt", "wl_redshift_model25_WLz01.897506e-01_WLalpha8.580632e-01.txt", "wl_redshift_model26_WLz01.831217e-01_WLalpha8.214720e-01.txt", "wl_redshift_model27_WLz01.906926e-01_WLalpha8.632630e-01.txt", "wl_redshift_model28_WLz01.714197e-01_WLalpha7.568766e-01.txt", "wl_redshift_model29_WLz01.798667e-01_WLalpha8.035040e-01.txt", "wl_redshift_model30_WLz01.842554e-01_WLalpha8.277299e-01.txt", "wl_redshift_model31_WLz01.901797e-01_WLalpha8.604322e-01.txt", "wl_redshift_model32_WLz01.937710e-01_WLalpha8.802561e-01.txt", "wl_redshift_model33_WLz01.790701e-01_WLalpha7.991072e-01.txt", "wl_redshift_model34_WLz01.811701e-01_WLalpha8.106987e-01.txt", "wl_redshift_model35_WLz01.781525e-01_WLalpha7.940419e-01.txt"}; char lens_zfile[36][400]={"LSS_redshift_model0_LSSz02.629496e-01_LSSalpha9.285983e-01.txt","LSS_redshift_model1_LSSz02.852923e-01_LSSalpha8.985943e-01.txt","LSS_redshift_model2_LSSz02.664822e-01_LSSalpha9.186036e-01.txt","LSS_redshift_model3_LSSz02.798758e-01_LSSalpha9.014201e-01.txt","LSS_redshift_model4_LSSz02.873873e-01_LSSalpha8.978683e-01.txt","LSS_redshift_model5_LSSz02.593970e-01_LSSalpha9.470921e-01.txt","LSS_redshift_model6_LSSz02.600213e-01_LSSalpha9.425114e-01.txt","LSS_redshift_model7_LSSz02.811155e-01_LSSalpha9.006370e-01.txt","LSS_redshift_model8_LSSz02.831875e-01_LSSalpha8.995165e-01.txt","LSS_redshift_model9_LSSz02.649368e-01_LSSalpha9.224338e-01.txt","LSS_redshift_model10_LSSz02.622058e-01_LSSalpha9.314128e-01.txt","LSS_redshift_model11_LSSz02.584820e-01_LSSalpha9.568082e-01.txt","LSS_redshift_model12_LSSz02.588053e-01_LSSalpha9.527220e-01.txt","LSS_redshift_model13_LSSz02.656075e-01_LSSalpha9.206866e-01.txt","LSS_redshift_model14_LSSz02.768397e-01_LSSalpha9.037492e-01.txt","LSS_redshift_model15_LSSz02.596975e-01_LSSalpha9.447600e-01.txt","LSS_redshift_model16_LSSz02.901709e-01_LSSalpha8.971658e-01.txt","LSS_redshift_model17_LSSz02.847362e-01_LSSalpha8.988183e-01.txt","LSS_redshift_model18_LSSz02.698330e-01_LSSalpha9.121821e-01.txt","LSS_redshift_model19_LSSz02.782257e-01_LSSalpha9.026084e-01.txt","LSS_redshift_model20_LSSz02.642756e-01_LSSalpha9.243038e-01.txt","LSS_redshift_model21_LSSz02.632273e-01_LSSalpha9.276296e-01.txt","LSS_redshift_model22_LSSz02.689934e-01_LSSalpha9.135968e-01.txt","LSS_redshift_model23_LSSz02.780987e-01_LSSalpha9.027073e-01.txt","LSS_redshift_model24_LSSz02.723464e-01_LSSalpha9.085463e-01.txt","LSS_redshift_model25_LSSz02.615210e-01_LSSalpha9.343470e-01.txt","LSS_redshift_model26_LSSz02.683327e-01_LSSalpha9.147934e-01.txt","LSS_redshift_model27_LSSz02.608392e-01_LSSalpha9.376962e-01.txt","LSS_redshift_model28_LSSz02.889655e-01_LSSalpha8.974355e-01.txt","LSS_redshift_model29_LSSz02.729686e-01_LSSalpha9.077654e-01.txt","LSS_redshift_model30_LSSz02.669178e-01_LSSalpha9.176391e-01.txt","LSS_redshift_model31_LSSz02.612016e-01_LSSalpha9.358553e-01.txt","LSS_redshift_model32_LSSz02.591077e-01_LSSalpha9.496317e-01.txt","LSS_redshift_model33_LSSz02.742326e-01_LSSalpha9.063038e-01.txt","LSS_redshift_model34_LSSz02.710103e-01_LSSalpha9.103760e-01.txt","LSS_redshift_model35_LSSz02.757517e-01_LSSalpha9.047459e-01.txt"}; double shear_prior[36]={0.00891915,0.0104498 ,0.0145972 ,0.0191916 ,0.00450246 ,0.00567828 ,0.00294841 ,0.00530922 ,0.0118632 ,0.0151849 ,0.00410151 ,0.0170622 ,0.0197331 ,0.0106615 ,0.0124445 ,0.00994507 ,0.0136251 ,0.0143491 ,0.0164314 ,0.016962 ,0.0186608 ,0.00945903 ,0.0113246 ,0.0155225 ,0.00800846 ,0.00732104 ,0.00649453 ,0.00243976 ,0.0125932 ,0.0182587 ,0.00335859 ,0.00682287 ,0.0177269 ,0.0035219 ,0.00773304 ,0.0134886}; double delta_z_prior[36]={0.0032537,0.00135316,0.00168787,0.00215043,0.00406031,0.00222358,0.00334993,0.00255186,0.00266499,0.00159226,0.00183664,0.00384965,0.00427765,0.00314377,0.00456113,0.00347868,0.00487938,0.00418152,0.00469911,0.00367598,0.0028009,0.00234161,0.00194964,0.00200982,0.00122739,0.00310886,0.00275168,0.00492736,0.00437241,0.00113931,0.00104864,0.00292328,0.00452082,0.00394114,0.00150756,0.003613}; double sigma_z[36]={0.0849973 ,0.0986032 ,0.0875521 ,0.0968222 ,0.0225239 ,0.0718278 ,0.0733675 ,0.0385274 ,0.0425549 ,0.0605867 ,0.0178555 ,0.0853407 ,0.0124119 ,0.0531027 ,0.0304032 ,0.0503145 ,0.0132213 ,0.0941765 ,0.0416444 ,0.0668198 ,0.063227 ,0.0291332 ,0.0481633 ,0.0595606 ,0.0818742 ,0.0472518 ,0.0270185 ,0.0767401 ,0.0219945 ,0.0902663 ,0.0779705 ,0.0337666 ,0.0362358 ,0.0692429 ,0.0558841 ,0.0150457}; double sigma_z_prior[36]={0.00331909,0.00529541,0.00478151,0.00437497,0.00443062,0.00486333,0.00467423,0.0036723,0.00426963,0.00515357,0.0054553,0.00310132,0.00305971,0.00406327,0.00594293,0.00348709,0.00562526,0.00396025,0.00540537,0.00500447,0.00318595,0.00460592,0.00412137,0.00336418,0.00524988,0.00390092,0.00498349,0.0056667,0.0036384,0.00455861,0.00554822,0.00381061,0.0057615,0.00357705,0.00590572,0.00422393}; init_cosmo_runmode("halofit"); init_bary("dmo"); init_binning_fourier(15,20.0,3000.0,3000.0,21.0,10,10); init_priors(shear_prior[sce],sigma_z[sce],delta_z_prior[sce],sigma_z_prior[sce],sigma_z[sce]*0.6,delta_z_prior[sce],sigma_z_prior[sce],3.0,1.2,3.8,2.0,16.0,5.0,0.8); init_survey(survey_designation[0],nsource_table[sce],nlens_table[sce],area_table[sce]); sprintf(arg1,"zdistris/%s",source_zfile[sce]); sprintf(arg2,"zdistris/%s",lens_zfile[sce]); init_galaxies(arg1,arg2,"gaussian","gaussian",tomo_binning_source[0],tomo_binning_lens[0]); init_IA("NLA_HF","GAMA"); init_probes("3x2pt"); //init_Pdelta("emu",0.8,0.35); // init_Pdelta("linear",0.8,0.35); // for (i =0; i< 10; i++){ // save_zdistr_sources(i); // } // for (i =0; i< 10; i++){ // save_zdistr_lenses(i); // } // double Omega; // char filename[300]; // for (i=0;i<200; i++){ // Omega=0.05+i*0.002; // sprintf(filename,"test_fid_%d", i); //compute_data_vector(filename,Omega,0.831,0.9645,-1.,0.,0.0491685,0.6727,0.,0.,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0,2.1,2.2,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.05,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.05,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,5.92,1.1,-0.47,0.0,0.0,0.0,0.0,0.0,0.0,0.0,3.207,0.993,0.0,0.456,0.0,0.0); // } sprintf(arg3,"Y10_area%le",area_table[sce]); compute_data_vector(arg3,0.3156,0.831,0.9645,-1.,0.,0.0491685,0.6727,0.,0.,gbias.b[0],gbias.b[1],gbias.b[2],gbias.b[3],gbias.b[4],gbias.b[5],gbias.b[6],gbias.b[7],gbias.b[8],gbias.b[9],0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,sigma_z[sce],0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,sigma_z[sce]*0.6,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,5.92,1.1,-0.47,0.0,0.0,0.0,0.0,0.0,0.0,0.0,3.207,0.993,0.0,0.456,0.0,0.0,0.0,0.0,0.0); // compute_data_vector("mu1_Sigma0",0.3156,0.831,0.9645,-1.,0.,0.0491685,0.6727,0.,1.,1.35,1.5,1.65,1.8,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.05,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.01,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,5.92,1.1,-0.47,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.72+log(1.e+14*0.7),1.08,0.0,0.25,0.9,0.9,0.9,0.9); // compute_data_vector("mu1_Sigma1",0.3156,0.831,0.9645,-1.,0.,0.0491685,0.6727,1.,1.,1.35,1.5,1.65,1.8,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.05,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.01,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,5.92,1.1,-0.47,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.72+log(1.e+14*0.7),1.08,0.0,0.25,0.9,0.9,0.9,0.9); // init_data_inv("cov/WFIRST_3x2pt_clusterN_clusterWL_inv","datav/WFIRST_all_2pt_clusterN_clusterWL_fid"); // begin = clock(); // log_multi_like(0.3156,0.831,0.9645,-1.,0.,0.0491685,0.6727,0.,0.,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0,2.1,2.2,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.05,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.05,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,5.92,1.1,-0.47,0.0,0.0,0.0,0.0,0.0,0.0,0.0,3.207,0.993,0.0,0.456,0.0,0.0); // // printf("knonlin %le\n",nonlinear_scale_computation(1.0)); // // printf("knonlin %le\n",nonlinear_scale_computation(0.5)); // end = clock(); // time_spent = (double)(end - begin) / CLOCKS_PER_SEC; // printf("timespent %le\n",time_spent); return 0; }
{ "alphanum_fraction": 0.7147230042, "avg_line_length": 54.2863501484, "ext": "c", "hexsha": "81da2cc12a65409f8c7f6d64676c639599d158f7", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "ed4d26b52ed26172eb35b3a030403c123e29eb2c", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "CosmoLike/LSST_emu", "max_forks_repo_path": "like_fourier.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "ed4d26b52ed26172eb35b3a030403c123e29eb2c", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "CosmoLike/LSST_emu", "max_issues_repo_path": "like_fourier.c", "max_line_length": 2395, "max_stars_count": null, "max_stars_repo_head_hexsha": "ed4d26b52ed26172eb35b3a030403c123e29eb2c", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "CosmoLike/LSST_emu", "max_stars_repo_path": "like_fourier.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 14989, "size": 36589 }
/** \ * External definitions to parametrize spectrum traces * in aXe grism exposures */ #ifndef _SPC_TRACE_FUNCTIONS_H #define _SPC_TRACE_FUNCTIONS_H #include <stdlib.h> #include <math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_integration.h> #include "aXe_errors.h" /* public */ /** A function for parametrizing spectrum traces; deriv and/or path_len (i.e. its derivative or the path length from parameter 0) may be NULL if they are not known analytically. func should return the the y offset for a given pixel column x of the spectrum trace */ typedef struct { int type; /* A unique type ID for the trace function */ double (*func) (const double, const void *const pars); double (*deriv) (const double, const void *const pars); double (*path_len) (const double, const void *const pars); void *data; /* private data for trace function, should be passed as a second parameter */ } trace_func; /* The create_xxx functions return a pointer to an allocated trace_func or NULL if the allocation failed. */ extern trace_func * create_poly2 (const double a0, const double a1, const double a2); extern trace_func * create_polyN (gsl_vector *v); extern trace_func * vector_to_trace_poly2 (gsl_vector *v); extern trace_func * vector_to_trace_polyN(gsl_vector *v); extern double polyN_ds(double x, void *pars); extern void free_poly2(trace_func * func); extern void free_polyN(trace_func * func); #endif /* ! _SPC_TRACE_FUNCTIONS_H */
{ "alphanum_fraction": 0.7371967655, "avg_line_length": 23.935483871, "ext": "h", "hexsha": "707d346c0f9d4f9a9068f51c19f89fdfa628842e", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "sosey/pyaxe", "max_forks_repo_path": "cextern/src/spc_trace_functions.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "sosey/pyaxe", "max_issues_repo_path": "cextern/src/spc_trace_functions.h", "max_line_length": 71, "max_stars_count": null, "max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "sosey/pyaxe", "max_stars_repo_path": "cextern/src/spc_trace_functions.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 376, "size": 1484 }
/**************************************************************************** * * * Author : lukasz.iwaszkiewicz@gmail.com * * ~~~~~~~~ * * License : see COPYING file for details. * * ~~~~~~~~~ * ****************************************************************************/ #pragma once #include <etl/cstring.h> // #include <fmt/core.h> // #include <fmt/format.h> #include <gsl/gsl> namespace logging { /// Line size including tick number and task name. static constexpr size_t MAX_LINE_SIZE = 256; /// Have to be initialized. void init (); /** * Add a log. Do not call from an ISR. */ bool log (gsl::czstring<> str); // template <typename Format, typename... Args> bool log2 (Format &&format, Args &&... args) // { // etl::string<MAX_LINE_SIZE> buf; // fmt::format_to (std::back_inserter (buf), std::forward<Format> (format), std::forward<Args> (args)...); // log (buf.c_str ()); // return true; // } } // namespace logging
{ "alphanum_fraction": 0.3998384491, "avg_line_length": 34.3888888889, "ext": "h", "hexsha": "37cf819a860c068b2bf071dfc23e8fb08e86ca9c", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-02-25T11:16:21.000Z", "max_forks_repo_forks_event_min_datetime": "2020-02-25T11:16:21.000Z", "max_forks_repo_head_hexsha": "e57f2d119668b588059a8c89f796340dfa06baf6", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "iwasz/freertos-test", "max_forks_repo_path": "src/logging.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "e57f2d119668b588059a8c89f796340dfa06baf6", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "iwasz/freertos-test", "max_issues_repo_path": "src/logging.h", "max_line_length": 114, "max_stars_count": null, "max_stars_repo_head_hexsha": "e57f2d119668b588059a8c89f796340dfa06baf6", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "iwasz/freertos-test", "max_stars_repo_path": "src/logging.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 230, "size": 1238 }
#pragma once #include "shapes3D.h" #include <gsl/gsl> namespace ad { template <int N_baseEdges> std::vector<vertex3D::Data> make_pyramid(float aBaseRadius, float aHeight) { std::vector<vertex3D::Data> result; // There are twice the number of edges in the pyramid, each edge being two vertices constexpr std::size_t ElementsCount{N_baseEdges*2*2}; result.reserve(ElementsCount); Vec<3> topPosition = {0.0f, 0.0f, aHeight}; auto getBasePosition = [](int aId, float aRadius) -> Vec<3> { return { std::cos(2*pi<>*aId/N_baseEdges) * aRadius, std::sin(2*pi<>*aId/N_baseEdges) * aRadius, 0.0f, }; }; Vec<3> position_prev = getBasePosition(-1, aBaseRadius); for(int i=0; i<N_baseEdges; ++i) { Vec<3> position_a = getBasePosition(i, aBaseRadius); Vec<3> position_b = getBasePosition(i+1, aBaseRadius); // The base segment { // The normal of BA vector (not AB) Vec<3> ba = (position_a - position_b).normalize(); Vec<3> base_normal = {-ba.y(), ba.x(), 0.0f}; result.emplace_back(vertex3D::Data{{position_a}, {base_normal}}); result.emplace_back(vertex3D::Data{{position_b}, {base_normal}}); } // The segment connecting base vertex "i" to the top { float teta = std::atan(aBaseRadius/aHeight); // angle between Z and a side edge Vec<3> b_prev = (position_prev - position_b).normalize(); Vec<3> side_normal = { -b_prev.y() * std::cos(teta), b_prev.x() * std::cos(teta), std::sin(teta), }; result.emplace_back(vertex3D::Data{{position_a}, {side_normal}}); result.emplace_back(vertex3D::Data{{topPosition}, {side_normal}}); } position_prev = position_a; } Expects(result.size() == ElementsCount); return result; } } // namespace ad
{ "alphanum_fraction": 0.5813253012, "avg_line_length": 29.7313432836, "ext": "h", "hexsha": "e0360f39230f262503d8906709f275c4baeeb447", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-03-31T13:17:54.000Z", "max_forks_repo_forks_event_min_datetime": "2021-03-31T13:17:54.000Z", "max_forks_repo_head_hexsha": "354a70fd89d0cdd9b4336961ad01d1567ac22474", "max_forks_repo_licenses": [ "Unlicense" ], "max_forks_repo_name": "FranzPoize/shmurp", "max_forks_repo_path": "src/app/shmurp/Shaper.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "354a70fd89d0cdd9b4336961ad01d1567ac22474", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Unlicense" ], "max_issues_repo_name": "FranzPoize/shmurp", "max_issues_repo_path": "src/app/shmurp/Shaper.h", "max_line_length": 91, "max_stars_count": 1, "max_stars_repo_head_hexsha": "354a70fd89d0cdd9b4336961ad01d1567ac22474", "max_stars_repo_licenses": [ "Unlicense" ], "max_stars_repo_name": "FranzPoize/shmurp", "max_stars_repo_path": "src/app/shmurp/Shaper.h", "max_stars_repo_stars_event_max_datetime": "2021-04-06T08:48:31.000Z", "max_stars_repo_stars_event_min_datetime": "2021-04-06T08:48:31.000Z", "num_tokens": 530, "size": 1992 }
#pragma once #ifndef _NOGSL #include <gsl/gsl_vector.h> #include <gsl/gsl_multimin.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_blas.h> #include <vector> using namespace std; typedef double (* GD_F_TYPE)(const gsl_vector*, void*); typedef void (* GD_DF_TYPE)(const gsl_vector*, void*, gsl_vector*); typedef void (* GD_FDF_TYPE)(const gsl_vector*, void*, double*, gsl_vector*); class GradientDescent { int N; // Total number of components gsl_vector *x; // The current state gsl_vector *ds; // The step size gsl_multimin_fdfminimizer* minidf; // The GSL minimizer for when derivatives needed const gsl_multimin_fdfminimizer_type *Tdf ; gsl_multimin_function_fdf myfundf; public: double INIT_STEP_SIZE = 2.0; double TOLERANCE = 0.1; double PRECISION = 1e-3; double GRAD_PRECISION = 1e-3; double ITERATIONS = 4000; GradientDescent(int N_p): N(N_p) { Tdf = gsl_multimin_fdfminimizer_vector_bfgs2; minidf = gsl_multimin_fdfminimizer_alloc(Tdf, N); myfundf.n = N; x = gsl_vector_alloc(N); } ~GradientDescent() { gsl_multimin_fdfminimizer_free(minidf); gsl_vector_free(x); } gsl_vector* getResults() { return minidf->x; } void init(GD_F_TYPE f, GD_DF_TYPE df, GD_FDF_TYPE fdf, void* p); double optimize(gsl_vector* initX, bool stopAtZero = true); // optimizes until value is 0 }; #endif
{ "alphanum_fraction": 0.736684171, "avg_line_length": 25.1509433962, "ext": "h", "hexsha": "b61600fb890b5fb1ec822c2d65b56e1064c69509", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-12-06T01:45:04.000Z", "max_forks_repo_forks_event_min_datetime": "2020-12-04T20:47:51.000Z", "max_forks_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_forks_repo_licenses": [ "X11" ], "max_forks_repo_name": "natebragg/sketch-backend", "max_forks_repo_path": "src/SketchSolver/NumericalSynthesis/Optimizers/GradientDescent.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_issues_repo_issues_event_max_datetime": "2022-03-04T04:02:09.000Z", "max_issues_repo_issues_event_min_datetime": "2022-03-01T16:53:05.000Z", "max_issues_repo_licenses": [ "X11" ], "max_issues_repo_name": "natebragg/sketch-backend", "max_issues_repo_path": "src/SketchSolver/NumericalSynthesis/Optimizers/GradientDescent.h", "max_line_length": 90, "max_stars_count": 17, "max_stars_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_stars_repo_licenses": [ "X11" ], "max_stars_repo_name": "natebragg/sketch-backend", "max_stars_repo_path": "src/SketchSolver/NumericalSynthesis/Optimizers/GradientDescent.h", "max_stars_repo_stars_event_max_datetime": "2022-03-31T00:28:40.000Z", "max_stars_repo_stars_event_min_datetime": "2020-08-20T14:54:11.000Z", "num_tokens": 405, "size": 1333 }
/** * * @file example_zpotrf.c * * PLASMA testing routines * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @brief Example of Cholesky factorization * * @version 2.6.0 * @author Bilel Hadri * @date 2010-11-15 * @precisions normal z -> c d s * **/ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <plasma.h> #include <cblas.h> #include <lapacke.h> #include <core_blas.h> int check_factorization(int, PLASMA_Complex64_t*, PLASMA_Complex64_t*, int, int); int IONE=1; int ISEED[4] = {0,0,0,1}; /* initial seed for zlarnv() */ int main () { int cores = 2; int N = 10 ; int LDA = 10 ; int info_factorization; PLASMA_Complex64_t *A1 = (PLASMA_Complex64_t *)malloc(LDA*N*sizeof(PLASMA_Complex64_t)); PLASMA_Complex64_t *A2 = (PLASMA_Complex64_t *)malloc(LDA*N*sizeof(PLASMA_Complex64_t)); /* Check if unable to allocate memory */ if ((!A1)||(!A2)){ printf("Out of Memory \n "); return EXIT_SUCCESS; } /* Plasma Initialize */ PLASMA_Init(cores); printf("-- PLASMA is initialized to run on %d cores. \n",cores); /* Initialize A1 and A2 for Symmetric Positive Matrix */ PLASMA_zplghe( (double)N, N, A1, LDA, 51 ); PLASMA_zlacpy( PlasmaUpperLower, N, N, A1, LDA, A2, LDA ); /* Plasma routines */ PLASMA_zpotrf(PlasmaUpper, N, A2, LDA); /* Check the factorization */ info_factorization = check_factorization( N, A1, A2, LDA, PlasmaUpper); if ( info_factorization != 0 ) printf("-- Error in ZPOTRF example ! \n"); else printf("-- Run of ZPOTRF example successful ! \n"); free(A1); free(A2); PLASMA_Finalize(); return EXIT_SUCCESS; } /*------------------------------------------------------------------------ * Check the factorization of the matrix A2 */ int check_factorization(int N, PLASMA_Complex64_t *A1, PLASMA_Complex64_t *A2, int LDA, int uplo) { double Anorm, Rnorm; PLASMA_Complex64_t alpha; int info_factorization; int i,j; double eps; eps = LAPACKE_dlamch_work('e'); PLASMA_Complex64_t *Residual = (PLASMA_Complex64_t *)malloc(N*N*sizeof(PLASMA_Complex64_t)); PLASMA_Complex64_t *L1 = (PLASMA_Complex64_t *)malloc(N*N*sizeof(PLASMA_Complex64_t)); PLASMA_Complex64_t *L2 = (PLASMA_Complex64_t *)malloc(N*N*sizeof(PLASMA_Complex64_t)); double *work = (double *)malloc(N*sizeof(double)); memset((void*)L1, 0, N*N*sizeof(PLASMA_Complex64_t)); memset((void*)L2, 0, N*N*sizeof(PLASMA_Complex64_t)); alpha= 1.0; LAPACKE_zlacpy_work(LAPACK_COL_MAJOR,' ', N, N, A1, LDA, Residual, N); /* Dealing with L'L or U'U */ if (uplo == PlasmaUpper){ LAPACKE_zlacpy_work(LAPACK_COL_MAJOR,'u', N, N, A2, LDA, L1, N); LAPACKE_zlacpy_work(LAPACK_COL_MAJOR,'u', N, N, A2, LDA, L2, N); cblas_ztrmm(CblasColMajor, CblasLeft, CblasUpper, CblasConjTrans, CblasNonUnit, N, N, CBLAS_SADDR(alpha), L1, N, L2, N); } else{ LAPACKE_zlacpy_work(LAPACK_COL_MAJOR,'l', N, N, A2, LDA, L1, N); LAPACKE_zlacpy_work(LAPACK_COL_MAJOR,'l', N, N, A2, LDA, L2, N); cblas_ztrmm(CblasColMajor, CblasRight, CblasLower, CblasConjTrans, CblasNonUnit, N, N, CBLAS_SADDR(alpha), L1, N, L2, N); } /* Compute the Residual || A -L'L|| */ for (i = 0; i < N; i++) for (j = 0; j < N; j++) Residual[j*N+i] = L2[j*N+i] - Residual[j*N+i]; Rnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), N, N, Residual, N, work); Anorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), N, N, A1, LDA, work); printf("============\n"); printf("Checking the Cholesky Factorization \n"); printf("-- ||L'L-A||_oo/(||A||_oo.N.eps) = %e \n",Rnorm/(Anorm*N*eps)); if ( isnan(Rnorm/(Anorm*N*eps)) || (Rnorm/(Anorm*N*eps) > 10.0) ){ printf("-- Factorization is suspicious ! \n"); info_factorization = 1; } else{ printf("-- Factorization is CORRECT ! \n"); info_factorization = 0; } free(Residual); free(L1); free(L2); free(work); return info_factorization; }
{ "alphanum_fraction": 0.6228932584, "avg_line_length": 30.7338129496, "ext": "c", "hexsha": "cf1e3045ddeed1b708cbe78b828058195bb5bd14", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_path": "examples/example_zpotrf.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_path": "examples/example_zpotrf.c", "max_line_length": 129, "max_stars_count": null, "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_path": "examples/example_zpotrf.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1421, "size": 4272 }
/** * * Copyright 2018, Planet Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdio.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_multifit.h> #include <math.h> /* A wrapper around the GSL multi-variate robust regression routine. This routine should only ever be called from the Python wrapper function, so if the parameters need to be changed, only these two files have to be changed. The array variables are given as pointers to doubles, and are referenced as 1-d arrays. However, the indexes are calculated as though they were multi-dimensional arrays, and the dimensions are described below. Input Variables *************** numParams is the number of parameters to be fitted, also equal to the number of independent variables numImages is the number of images in the stack, and corresponds to the number of points in each fit (before removing nulls) numRows is the number of rows in the image numCols is the number of columns in the image The x parameter contains the values of all the independent variables. It comes in one of two flavours, depending on the value of the perPixelX parameter. If perPixelX is 1, then the x parameter is a 4-dimensional array of doubles, with shape (numParams, numImages, numRows, numCols) otherwise it is a 2-dimensional array with shape (numParams, numImages) and it is assumed that the independent variables are constant over all pixels. This latter is the most likely case. The Y variable is notionally a 3-dimensional array of doubles. The shape should be (numImages, numRows, numCols) It contains the values of the dependent variable. The nullVal parameter is a scalar double value. Any occurrence of this value in the y array will exclude that point from the fit. Output Variables **************** The following variables are calculated within this routine, and passed back via the pointers in the parameter list. The c array is a 3-dimensional array of doubles. It corresponds to an image stack of the fitted coefficients, and its shape is (numParams, numRows, numCols) The adj_Rsqrd array stores the adjusted R^2 coefficient of determination statistic. */ void wrap_gsl_multifit_robust(double *x, double *y, double *c, double *adj_Rsqrd, int *numIter, double *rmse, int method, int perPixelX, int numRows, int numCols, int numImages, int numParams, int numRowsX, int numColsX, double nullVal) { int row, col, img, param, n, xNdx, yNdx, pixNdx; gsl_matrix *gslX, *gslCov; gsl_vector *gslY, *gslC; gsl_multifit_robust_workspace *workspace; gsl_multifit_robust_type *regressionType; gsl_multifit_robust_stats stats; int gslErrorCode; /* Turn off the default error handler, which aborts at the first error. */ gsl_set_error_handler_off(); /* Translate the integer type given into the corresponding GSL pointer */ switch (method) { case 1: regressionType = gsl_multifit_robust_bisquare; break; case 2: regressionType = gsl_multifit_robust_cauchy; break; case 3: regressionType = gsl_multifit_robust_fair; break; case 4: regressionType = gsl_multifit_robust_huber; break; case 5: regressionType = gsl_multifit_robust_ols; break; case 6: regressionType = gsl_multifit_robust_welsch; break; } /* These structures can be allocated outside the pixel loop */ gslCov = gsl_matrix_calloc(numParams, numParams); gslC = gsl_vector_calloc(numParams); /* Loop over all pixels */ for (row=0; row<numRows; row++) { for (col=0; col<numCols; col++) { /* Count how many non-null y values we have. */ n = 0; for (img=0; img<numImages; img++) { if (y[img*numRows*numCols+row*numCols+col] != nullVal) n++; } /* Allocate various structures, now we know how many non-nulls */ if (n >= numParams) { workspace = gsl_multifit_robust_alloc(regressionType, n, numParams); gslX = gsl_matrix_calloc(n, numParams); gslY = gsl_vector_calloc(n); /* Copy the data from this pixel into the relevant GSL structures. Note that we skip over null values, based on nulls in the y variable. */ n = 0; for (img=0; img<numImages; img++) { yNdx = img*numRows*numCols+row*numCols+col; if (y[yNdx] != nullVal) { gslY->data[n*gslY->stride] = y[yNdx]; for (param=0; param<numParams; param++) { if (perPixelX == 0) { xNdx = param * numImages + img; } else { xNdx = param * numRowsX * numColsX * numImages + img * numRowsX * numColsX + row * numColsX + col; } gslX->data[n*gslX->tda + param] = x[xNdx]; } n++; } } /* Do the regression fit */ gslErrorCode = gsl_multifit_robust(gslX, gslY, gslC, gslCov, workspace); if (gslErrorCode == 0) { /* Copy the coefficients back into the image stack of coefficients */ for (param=0; param<numParams; param++) { c[param*numRows*numCols + row*numCols + col] = gslC->data[param*gslC->stride]; } /* Copy some useful statistics into their arrays */ stats = gsl_multifit_robust_statistics(workspace); pixNdx = row*numCols + col; adj_Rsqrd[pixNdx] = stats.adj_Rsq; numIter[pixNdx] = stats.numit; rmse[pixNdx] = stats.rmse; } /* Free per-pixel structures */ gsl_matrix_free(gslX); gsl_vector_free(gslY); gsl_multifit_robust_free(workspace); } } } /* Free the other structures */ gsl_vector_free(gslC); gsl_matrix_free(gslCov); }
{ "alphanum_fraction": 0.6116813648, "avg_line_length": 40.4502923977, "ext": "c", "hexsha": "c1e0359178c8c66691978a3c2fa718202f2c3e09", "lang": "C", "max_forks_count": 5, "max_forks_repo_forks_event_max_datetime": "2021-09-28T02:08:24.000Z", "max_forks_repo_forks_event_min_datetime": "2019-03-20T10:39:55.000Z", "max_forks_repo_head_hexsha": "f1f46e07c7ee45c3d11e066795e110a0019518e5", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "planetlabs/planet-tmask", "max_forks_repo_path": "tmask/robreg.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "f1f46e07c7ee45c3d11e066795e110a0019518e5", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "planetlabs/planet-tmask", "max_issues_repo_path": "tmask/robreg.c", "max_line_length": 102, "max_stars_count": 8, "max_stars_repo_head_hexsha": "f1f46e07c7ee45c3d11e066795e110a0019518e5", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "planetlabs/planet-tmask", "max_stars_repo_path": "tmask/robreg.c", "max_stars_repo_stars_event_max_datetime": "2021-12-09T08:49:02.000Z", "max_stars_repo_stars_event_min_datetime": "2018-08-14T04:53:26.000Z", "num_tokens": 1616, "size": 6917 }
/* * optimize_tnc.h * * Created on: Feb 9, 2010 * Author: smitty */ #ifndef _OPTIMIZE_STATE_RECONSTRUCTOR_NLOPT_H_ #define _OPTIMIZE_STATE_RECONSTRUCTOR_NLOPT_H_ #include <nlopt.h> #include "state_reconstructor.h" #include "rate_model.h" #include <armadillo> using namespace arma; void optimize_sr_nlopt(RateModel * _rm,StateReconstructor * _sr, mat * _free_mask, int _nfree); #endif /* _OPTIMIZE_STATE_RECONSTRUCTOR_NLOPT_H_ */
{ "alphanum_fraction": 0.764573991, "avg_line_length": 20.2727272727, "ext": "h", "hexsha": "b84de327334f48c99a7363d1b286b27a28dd3a3d", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:23:31.000Z", "max_forks_repo_forks_event_min_datetime": "2021-07-18T05:20:26.000Z", "max_forks_repo_head_hexsha": "08070c6d4a6fbd9320265e1e698c95ba80f81123", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jlanga/smsk_orthofinder", "max_forks_repo_path": "src/phyx-1.01/src/optimize_state_reconstructor_nlopt.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "08070c6d4a6fbd9320265e1e698c95ba80f81123", "max_issues_repo_issues_event_max_datetime": "2018-11-08T13:59:48.000Z", "max_issues_repo_issues_event_min_datetime": "2017-08-21T07:26:13.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "jlanga/smsk_selection", "max_issues_repo_path": "src/phyx-1.01/src/optimize_state_reconstructor_nlopt.h", "max_line_length": 95, "max_stars_count": 4, "max_stars_repo_head_hexsha": "08070c6d4a6fbd9320265e1e698c95ba80f81123", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jlanga/smsk_selection", "max_stars_repo_path": "src/phyx-1.01/src/optimize_state_reconstructor_nlopt.h", "max_stars_repo_stars_event_max_datetime": "2022-01-03T10:22:33.000Z", "max_stars_repo_stars_event_min_datetime": "2021-07-18T05:20:20.000Z", "num_tokens": 128, "size": 446 }
#include <gsl/gsl_roots.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_errno.h> #include "eos_rho.h" #include "root_func.h" #include "global.h" // "reverse" EOS. input: P, T. output: rho double eos_rho (double pres, void *params) { struct param *eos_rho_params = (struct param *) params; int status; double rho_low, rho_hi, root; // root-finding stuff for inverting EOS const gsl_root_fsolver_type *T; gsl_root_fsolver *s = NULL; gsl_function F; // set up root-finding machinery for inverting EOS F.function = &root_func; F.params = params; T = gsl_root_fsolver_brent; s = gsl_root_fsolver_alloc (T); status = gsl_root_fsolver_set (s, &F, rho_root_min, rho_root_max); tmp_pres = pres; do { status = gsl_root_fsolver_iterate (s); root = gsl_root_fsolver_root (s); rho_low = gsl_root_fsolver_x_lower (s); rho_hi = gsl_root_fsolver_x_upper (s); status = gsl_root_test_interval (rho_low, rho_hi, 0, 0.001); } while (status == GSL_CONTINUE); gsl_root_fsolver_free (s); return (root); }
{ "alphanum_fraction": 0.6952830189, "avg_line_length": 26.5, "ext": "c", "hexsha": "5093b8812779e71136f99fe3cc713750b35c71f6", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "5288ad6972b47143e1ce57e282f516143f07b158", "max_forks_repo_licenses": [ "BSD-2-Clause-FreeBSD" ], "max_forks_repo_name": "bcfriesen/TOV_solver", "max_forks_repo_path": "src/eos_rho.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "5288ad6972b47143e1ce57e282f516143f07b158", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause-FreeBSD" ], "max_issues_repo_name": "bcfriesen/TOV_solver", "max_issues_repo_path": "src/eos_rho.c", "max_line_length": 68, "max_stars_count": 1, "max_stars_repo_head_hexsha": "5288ad6972b47143e1ce57e282f516143f07b158", "max_stars_repo_licenses": [ "BSD-2-Clause-FreeBSD" ], "max_stars_repo_name": "bcfriesen/TOV_solver", "max_stars_repo_path": "src/eos_rho.c", "max_stars_repo_stars_event_max_datetime": "2015-11-14T02:27:58.000Z", "max_stars_repo_stars_event_min_datetime": "2015-11-14T02:27:58.000Z", "num_tokens": 316, "size": 1060 }
/* * File: Random.h * Author: nguyentran * * Created on May 27, 2013, 10:46 AM */ #ifndef RANDOM_H #define RANDOM_H #include <gsl/gsl_rng.h> #include "PropertyMacro.h" #include "Strategies/AdaptiveCyclingStrategy.h" class Model; class Random { DISALLOW_COPY_AND_ASSIGN(Random) DISALLOW_MOVE(Random) VIRTUAL_PROPERTY(unsigned long, seed) public: gsl_rng *G_RNG; explicit Random(gsl_rng *g_rng = nullptr); virtual ~Random(); void initialize(const unsigned long &seed = 0); void release() const; virtual int random_poisson(const double &poisson_mean); virtual unsigned long random_uniform(unsigned long range); virtual unsigned long random_uniform_int(const unsigned long &from, const unsigned long &to); virtual double random_uniform_double(const double &from, const double &to); /* * This function will return a random number in [0,1) */ virtual double random_uniform(); virtual double random_normal(const double &mean, const double &sd); virtual double random_normal_truncated(const double &mean, const double &sd); virtual int random_normal(const int &mean, const int &sd); virtual int random_normal_truncated(const int &mean, const int &sd); virtual double random_beta(const double &alpha, const double &beta); virtual double random_gamma(const double &shape, const double &scale); virtual double cdf_gamma_distribution(const double &x, const double &alpha, const double &beta); virtual double cdf_gamma_distribution_inverse(const double &p, const double &alpha, const double &beta); virtual double random_flat(const double &from, const double &to); virtual void random_multinomial(const size_t &K, const unsigned &N, double p[], unsigned n[]); virtual void random_shuffle(void *base, size_t base_length, size_t size_of_type); virtual double cdf_standard_normal_distribution(const double &p); virtual int random_binomial(const double &p, const unsigned int &n); void shuffle(void *base, const size_t &n, const size_t &size); }; #endif /* RANDOM_H */
{ "alphanum_fraction": 0.7457462324, "avg_line_length": 26.3717948718, "ext": "h", "hexsha": "cab8d190199105b113a5219ee666478a523821ab", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "41086cf621274dcdf8b445435cb1825424a2e722", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "bonilab/malariaibm-generation-of-MDR-mutants", "max_forks_repo_path": "src/Core/Random.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "41086cf621274dcdf8b445435cb1825424a2e722", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "bonilab/malariaibm-generation-of-MDR-mutants", "max_issues_repo_path": "src/Core/Random.h", "max_line_length": 106, "max_stars_count": null, "max_stars_repo_head_hexsha": "41086cf621274dcdf8b445435cb1825424a2e722", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "bonilab/malariaibm-generation-of-MDR-mutants", "max_stars_repo_path": "src/Core/Random.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 482, "size": 2057 }
/* vector/gsl_vector_complex_float.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSL_VECTOR_COMPLEX_FLOAT_H__ #define __GSL_VECTOR_COMPLEX_FLOAT_H__ #if !defined( GSL_FUN ) # if !defined( GSL_DLL ) # define GSL_FUN extern # elif defined( BUILD_GSL_DLL ) # define GSL_FUN extern __declspec(dllexport) # else # define GSL_FUN extern __declspec(dllimport) # endif #endif #include <stdlib.h> #include <gsl/gsl_types.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_check_range.h> #include <gsl/gsl_vector_float.h> #include <gsl/gsl_vector_complex.h> #include <gsl/gsl_block_complex_float.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS typedef struct { size_t size; size_t stride; float *data; gsl_block_complex_float *block; int owner; } gsl_vector_complex_float; typedef struct { gsl_vector_complex_float vector; } _gsl_vector_complex_float_view; typedef _gsl_vector_complex_float_view gsl_vector_complex_float_view; typedef struct { gsl_vector_complex_float vector; } _gsl_vector_complex_float_const_view; typedef const _gsl_vector_complex_float_const_view gsl_vector_complex_float_const_view; /* Allocation */ GSL_FUN gsl_vector_complex_float *gsl_vector_complex_float_alloc (const size_t n); GSL_FUN gsl_vector_complex_float *gsl_vector_complex_float_calloc (const size_t n); GSL_FUN gsl_vector_complex_float * gsl_vector_complex_float_alloc_from_block (gsl_block_complex_float * b, const size_t offset, const size_t n, const size_t stride); GSL_FUN gsl_vector_complex_float * gsl_vector_complex_float_alloc_from_vector (gsl_vector_complex_float * v, const size_t offset, const size_t n, const size_t stride); GSL_FUN void gsl_vector_complex_float_free (gsl_vector_complex_float * v); /* Views */ GSL_FUN _gsl_vector_complex_float_view gsl_vector_complex_float_view_array (float *base, size_t n); GSL_FUN _gsl_vector_complex_float_view gsl_vector_complex_float_view_array_with_stride (float *base, size_t stride, size_t n); GSL_FUN _gsl_vector_complex_float_const_view gsl_vector_complex_float_const_view_array (const float *base, size_t n); GSL_FUN _gsl_vector_complex_float_const_view gsl_vector_complex_float_const_view_array_with_stride (const float *base, size_t stride, size_t n); GSL_FUN _gsl_vector_complex_float_view gsl_vector_complex_float_subvector (gsl_vector_complex_float *base, size_t i, size_t n); GSL_FUN _gsl_vector_complex_float_view gsl_vector_complex_float_subvector_with_stride (gsl_vector_complex_float *v, size_t i, size_t stride, size_t n); GSL_FUN _gsl_vector_complex_float_const_view gsl_vector_complex_float_const_subvector (const gsl_vector_complex_float *base, size_t i, size_t n); GSL_FUN _gsl_vector_complex_float_const_view gsl_vector_complex_float_const_subvector_with_stride (const gsl_vector_complex_float *v, size_t i, size_t stride, size_t n); GSL_FUN _gsl_vector_float_view gsl_vector_complex_float_real (gsl_vector_complex_float *v); GSL_FUN _gsl_vector_float_view gsl_vector_complex_float_imag (gsl_vector_complex_float *v); GSL_FUN _gsl_vector_float_const_view gsl_vector_complex_float_const_real (const gsl_vector_complex_float *v); GSL_FUN _gsl_vector_float_const_view gsl_vector_complex_float_const_imag (const gsl_vector_complex_float *v); /* Operations */ GSL_FUN void gsl_vector_complex_float_set_zero (gsl_vector_complex_float * v); GSL_FUN void gsl_vector_complex_float_set_all (gsl_vector_complex_float * v, gsl_complex_float z); GSL_FUN int gsl_vector_complex_float_set_basis (gsl_vector_complex_float * v, size_t i); GSL_FUN int gsl_vector_complex_float_fread (FILE * stream, gsl_vector_complex_float * v); GSL_FUN int gsl_vector_complex_float_fwrite (FILE * stream, const gsl_vector_complex_float * v); GSL_FUN int gsl_vector_complex_float_fscanf (FILE * stream, gsl_vector_complex_float * v); GSL_FUN int gsl_vector_complex_float_fprintf (FILE * stream, const gsl_vector_complex_float * v, const char *format); GSL_FUN int gsl_vector_complex_float_memcpy (gsl_vector_complex_float * dest, const gsl_vector_complex_float * src); GSL_FUN int gsl_vector_complex_float_reverse (gsl_vector_complex_float * v); GSL_FUN int gsl_vector_complex_float_swap (gsl_vector_complex_float * v, gsl_vector_complex_float * w); GSL_FUN int gsl_vector_complex_float_swap_elements (gsl_vector_complex_float * v, const size_t i, const size_t j); GSL_FUN int gsl_vector_complex_float_equal (const gsl_vector_complex_float * u, const gsl_vector_complex_float * v); GSL_FUN int gsl_vector_complex_float_isnull (const gsl_vector_complex_float * v); GSL_FUN int gsl_vector_complex_float_ispos (const gsl_vector_complex_float * v); GSL_FUN int gsl_vector_complex_float_isneg (const gsl_vector_complex_float * v); GSL_FUN int gsl_vector_complex_float_isnonneg (const gsl_vector_complex_float * v); GSL_FUN int gsl_vector_complex_float_add (gsl_vector_complex_float * a, const gsl_vector_complex_float * b); GSL_FUN int gsl_vector_complex_float_sub (gsl_vector_complex_float * a, const gsl_vector_complex_float * b); GSL_FUN int gsl_vector_complex_float_mul (gsl_vector_complex_float * a, const gsl_vector_complex_float * b); GSL_FUN int gsl_vector_complex_float_div (gsl_vector_complex_float * a, const gsl_vector_complex_float * b); GSL_FUN int gsl_vector_complex_float_scale (gsl_vector_complex_float * a, const gsl_complex_float x); GSL_FUN int gsl_vector_complex_float_add_constant (gsl_vector_complex_float * a, const gsl_complex_float x); GSL_FUN int gsl_vector_complex_float_axpby (const gsl_complex_float alpha, const gsl_vector_complex_float * x, const gsl_complex_float beta, gsl_vector_complex_float * y); GSL_FUN INLINE_DECL gsl_complex_float gsl_vector_complex_float_get (const gsl_vector_complex_float * v, const size_t i); GSL_FUN INLINE_DECL void gsl_vector_complex_float_set (gsl_vector_complex_float * v, const size_t i, gsl_complex_float z); GSL_FUN INLINE_DECL gsl_complex_float *gsl_vector_complex_float_ptr (gsl_vector_complex_float * v, const size_t i); GSL_FUN INLINE_DECL const gsl_complex_float *gsl_vector_complex_float_const_ptr (const gsl_vector_complex_float * v, const size_t i); #ifdef HAVE_INLINE INLINE_FUN gsl_complex_float gsl_vector_complex_float_get (const gsl_vector_complex_float * v, const size_t i) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(i >= v->size)) { gsl_complex_float zero = {{0, 0}}; GSL_ERROR_VAL ("index out of range", GSL_EINVAL, zero); } #endif return *GSL_COMPLEX_FLOAT_AT (v, i); } INLINE_FUN void gsl_vector_complex_float_set (gsl_vector_complex_float * v, const size_t i, gsl_complex_float z) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(i >= v->size)) { GSL_ERROR_VOID ("index out of range", GSL_EINVAL); } #endif *GSL_COMPLEX_FLOAT_AT (v, i) = z; } INLINE_FUN gsl_complex_float * gsl_vector_complex_float_ptr (gsl_vector_complex_float * v, const size_t i) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(i >= v->size)) { GSL_ERROR_NULL ("index out of range", GSL_EINVAL); } #endif return GSL_COMPLEX_FLOAT_AT (v, i); } INLINE_FUN const gsl_complex_float * gsl_vector_complex_float_const_ptr (const gsl_vector_complex_float * v, const size_t i) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(i >= v->size)) { GSL_ERROR_NULL ("index out of range", GSL_EINVAL); } #endif return GSL_COMPLEX_FLOAT_AT (v, i); } #endif /* HAVE_INLINE */ __END_DECLS #endif /* __GSL_VECTOR_COMPLEX_FLOAT_H__ */
{ "alphanum_fraction": 0.6960724461, "avg_line_length": 37.3688212928, "ext": "h", "hexsha": "c48a48c8e52241b27d2f4e61164c1783fda58a72", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-10-14T12:45:35.000Z", "max_forks_repo_forks_event_min_datetime": "2020-10-14T12:45:35.000Z", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_vector_complex_float.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_vector_complex_float.h", "max_line_length": 171, "max_stars_count": 1, "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_vector_complex_float.h", "max_stars_repo_stars_event_max_datetime": "2020-09-28T08:20:20.000Z", "max_stars_repo_stars_event_min_datetime": "2020-09-28T08:20:20.000Z", "num_tokens": 2149, "size": 9828 }
#include <stdio.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #define NRAND 1000000 #define HIST_SIZE 25 #define HIST_MIN 0 #define HIST_MAX (HIST_SIZE - 1) int hist[HIST_SIZE]; int main (void) { const gsl_rng_type * T; gsl_rng * r; double mu = 2.0; /* create a generator chosen by the environment variable GSL_RNG_TYPE */ gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc (T); printf("Distribution with mean of %f\n", mu); /* print N random variates chosen from the poisson distribution with mean parameter mu */ for (int i = 0; i < NRAND; i++) { /* unsigned int k = gsl_ran_poisson(r, mu) + 10; */ unsigned int k = gsl_ran_gaussian(r, mu) + 10; if (HIST_MIN <= k && k <= HIST_MAX) { hist[k]++; } else { printf ("outside history range: %u\n", k); } } for (int i = 0; i < HIST_SIZE; i++) { printf("[%d] ", i); for (int j = 0; j < hist[i] / (NRAND / 100); j++) { putchar('*'); } printf("\n"); } gsl_rng_free (r); return 0; }
{ "alphanum_fraction": 0.6126482213, "avg_line_length": 19.4615384615, "ext": "c", "hexsha": "41675ef51e82f39ff8c000c7e6e90db2c7370315", "lang": "C", "max_forks_count": 22, "max_forks_repo_forks_event_max_datetime": "2022-03-14T18:31:08.000Z", "max_forks_repo_forks_event_min_datetime": "2015-04-07T07:28:35.000Z", "max_forks_repo_head_hexsha": "5c93bc84de32a7b8011258c0371f2a132ace3f5f", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "Rugang/scraps", "max_forks_repo_path": "cpp/rand-distributions/gsl.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "5c93bc84de32a7b8011258c0371f2a132ace3f5f", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "Rugang/scraps", "max_issues_repo_path": "cpp/rand-distributions/gsl.c", "max_line_length": 53, "max_stars_count": 35, "max_stars_repo_head_hexsha": "5c93bc84de32a7b8011258c0371f2a132ace3f5f", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "Rugang/scraps", "max_stars_repo_path": "cpp/rand-distributions/gsl.c", "max_stars_repo_stars_event_max_datetime": "2022-03-14T18:16:06.000Z", "max_stars_repo_stars_event_min_datetime": "2015-04-19T16:18:11.000Z", "num_tokens": 339, "size": 1012 }
/* linalg/condest.c * * Copyright (C) 2016 Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <string.h> #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> /* * This module contains routines for estimating the condition number * of matrices in the 1-norm. The algorithm is based on the paper, * * [1] N. J. Higham, "FORTRAN codes for estimating the one-norm of * a real or complex matrix, with applications to condition estimation", * ACM Trans. Math. Soft., vol. 14, no. 4, pp. 381-396, December 1988. */ static double condest_tri_norm1(CBLAS_UPLO_t Uplo, const gsl_matrix * A); static int condest_tri_rcond(CBLAS_UPLO_t Uplo, const gsl_matrix * A, double * rcond, gsl_vector * work); static int condest_same_sign(const gsl_vector * x, const gsl_vector * y); static int condest_invtriu(CBLAS_TRANSPOSE_t TransA, gsl_vector * x, void * params); static int condest_invtril(CBLAS_TRANSPOSE_t TransA, gsl_vector * x, void * params); /* gsl_linalg_tri_upper_rcond() Estimate reciprocal condition number of upper triangular matrix Inputs: A - upper triangular matrix, N-by-N rcond - (output) reciprocal condition number estimate work - workspace, length 3*N Return: success/error */ int gsl_linalg_tri_upper_rcond(const gsl_matrix * A, double * rcond, gsl_vector * work) { int status = condest_tri_rcond(CblasUpper, A, rcond, work); return status; } /* gsl_linalg_tri_lower_rcond() Estimate reciprocal condition number of lower triangular matrix Inputs: A - lower triangular matrix, N-by-N rcond - (output) reciprocal condition number estimate work - workspace, length 3*N Return: success/error */ int gsl_linalg_tri_lower_rcond(const gsl_matrix * A, double * rcond, gsl_vector * work) { int status = condest_tri_rcond(CblasLower, A, rcond, work); return status; } /* gsl_linalg_invnorm1() Estimate the 1-norm of ||A^{-1}||, where A is a square N-by-N matrix Inputs: N - size of matrix Ainvx - pointer to function which calculates: x := A^{-1} x or x := A^{-t} x params - parameters to pass to Ainvx Ainvnorm - (output) estimate of ||A^{-1}||_1 work - workspace, length 3*N */ int gsl_linalg_invnorm1(const size_t N, int (* Ainvx)(CBLAS_TRANSPOSE_t TransA, gsl_vector * x, void * params), void * params, double * Ainvnorm, gsl_vector * work) { if (work->size != 3 * N) { GSL_ERROR ("work vector must have length 3*N", GSL_EBADLEN); } else { const size_t maxit = 5; gsl_vector_view x = gsl_vector_subvector(work, 0, N); gsl_vector_view v = gsl_vector_subvector(work, N, N); gsl_vector_view xi = gsl_vector_subvector(work, 2*N, N); double gamma, gamma_old, temp; size_t i, k; for (i = 0; i < N; ++i) gsl_vector_set(&x.vector, i, 1.0 / (double) N); /* compute v = A^{-1} x */ gsl_vector_memcpy(&v.vector, &x.vector); (*Ainvx)(CblasNoTrans, &v.vector, params); /* gamma = ||v||_1 */ gamma = gsl_blas_dasum(&v.vector); /* xi = sign(v) */ for (i = 0; i < N; ++i) { double vi = gsl_vector_get(&v.vector, i); gsl_vector_set(&xi.vector, i, GSL_SIGN(vi)); } /* x = A^{-t} xi */ gsl_vector_memcpy(&x.vector, &xi.vector); (*Ainvx)(CblasTrans, &x.vector, params); for (k = 0; k < maxit; ++k) { size_t j = (size_t) gsl_blas_idamax(&x.vector); /* v := A^{-1} e_j */ gsl_vector_set_zero(&v.vector); gsl_vector_set(&v.vector, j, 1.0); (*Ainvx)(CblasNoTrans, &v.vector, params); gamma_old = gamma; gamma = gsl_blas_dasum(&v.vector); /* check for repeated sign vector (algorithm has converged) */ if (condest_same_sign(&v.vector, &xi.vector) || (gamma < gamma_old)) break; /* xi = sign(v) */ for (i = 0; i < N; ++i) { double vi = gsl_vector_get(&v.vector, i); gsl_vector_set(&xi.vector, i, GSL_SIGN(vi)); } /* x = A^{-t} sign(v) */ gsl_vector_memcpy(&x.vector, &xi.vector); (*Ainvx)(CblasTrans, &x.vector, params); } temp = 1.0; /* (-1)^i */ for (i = 0; i < N; ++i) { double term = 1.0 + (double) i / (N - 1.0); gsl_vector_set(&x.vector, i, temp * term); temp = -temp; } /* x := A^{-1} x */ (*Ainvx)(CblasNoTrans, &x.vector, params); temp = 2.0 * gsl_blas_dasum(&x.vector) / (3.0 * N); if (temp > gamma) { gsl_vector_memcpy(&v.vector, &x.vector); gamma = temp; } *Ainvnorm = gamma; return GSL_SUCCESS; } } static int condest_tri_rcond(CBLAS_UPLO_t Uplo, const gsl_matrix * A, double * rcond, gsl_vector * work) { const size_t M = A->size1; const size_t N = A->size2; if (M != N) { GSL_ERROR ("matrix must be square", GSL_ENOTSQR); } else if (work->size != 3 * N) { GSL_ERROR ("work vector must have length 3*N", GSL_EBADLEN); } else { int status; double Anorm = condest_tri_norm1(Uplo, A); /* ||A||_1 */ double Ainvnorm; /* ||A^{-1}||_1 */ *rcond = 0.0; /* don't continue if matrix is singular */ if (Anorm == 0.0) return GSL_SUCCESS; /* estimate ||A^{-1}||_1 */ if (Uplo == CblasUpper) status = gsl_linalg_invnorm1(N, condest_invtriu, (void *) A, &Ainvnorm, work); else status = gsl_linalg_invnorm1(N, condest_invtril, (void *) A, &Ainvnorm, work); if (status) return status; if (Ainvnorm != 0.0) *rcond = (1.0 / Anorm) / Ainvnorm; return GSL_SUCCESS; } } /* calculate 1 norm of triangular matrix */ static double condest_tri_norm1(CBLAS_UPLO_t Uplo, const gsl_matrix * A) { const size_t N = A->size2; double max = 0.0; size_t i, j; if (Uplo == CblasUpper) { for (j = 0; j < N; ++j) { double sum = 0.0; for (i = 0; i <= j; ++i) { double Aij = gsl_matrix_get(A, i, j); sum += fabs(Aij); } max = GSL_MAX(max, sum); } } else { for (j = 0; j < N; ++j) { double sum = 0.0; for (i = j; i < N; ++i) { double Aij = gsl_matrix_get(A, i, j); sum += fabs(Aij); } max = GSL_MAX(max, sum); } } return max; } /* return 1 if sign(x) = sign(y), 0 otherwise */ static int condest_same_sign(const gsl_vector * x, const gsl_vector * y) { const size_t n = x->size; size_t i; for (i = 0; i < n; ++i) { double xi = gsl_vector_get(x, i); double yi = gsl_vector_get(y, i); if (GSL_SIGN(xi) != GSL_SIGN(yi)) return 0; } return 1; } /* x := A^{-1} x, A upper triangular */ static int condest_invtriu(CBLAS_TRANSPOSE_t TransA, gsl_vector * x, void * params) { gsl_matrix * A = (gsl_matrix *) params; return gsl_blas_dtrsv(CblasUpper, TransA, CblasNonUnit, A, x); } /* x := A^{-1} x, A lower triangular */ static int condest_invtril(CBLAS_TRANSPOSE_t TransA, gsl_vector * x, void * params) { gsl_matrix * A = (gsl_matrix *) params; return gsl_blas_dtrsv(CblasLower, TransA, CblasNonUnit, A, x); }
{ "alphanum_fraction": 0.587330208, "avg_line_length": 27.73, "ext": "c", "hexsha": "eb50a30f4ede148da8d382a70d5165167c32a904", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/linalg/condest.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/linalg/condest.c", "max_line_length": 93, "max_stars_count": 1, "max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_stars_repo_path": "gsl-2.4/linalg/condest.c", "max_stars_repo_stars_event_max_datetime": "2021-01-13T05:01:59.000Z", "max_stars_repo_stars_event_min_datetime": "2021-01-13T05:01:59.000Z", "num_tokens": 2435, "size": 8319 }
#define MAXLOCI 1000000 #include <gsl/gsl_linalg.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> /* data definition- holds sample size of each species, segsites in each species, D, length of locus */ struct hkaData{ int na, nb, length, lArray[30], sArray[30]; double d, sa, sb; char name[81]; }; struct hkaParams{ int *lengths; }; double harmSum(int n); double harmSumSquare(int n); void getData(int argc, char *argv[]); void usage(); double calculateHKA(gsl_vector *params,gsl_vector *chiSquares, gsl_vector *expSA, gsl_vector *expD); int chopByWhite(char *in, char *outArray[], int outSize); int setHKAFunction(const gsl_vector *x, void *p, gsl_vector *f); int solveSystem(gsl_vector *params);
{ "alphanum_fraction": 0.7339832869, "avg_line_length": 28.72, "ext": "h", "hexsha": "c6d6a41b29d63b0538deeecd00fbca9c81d9b55e", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "a5aab11242ceffcc84a1701a3a397b1e57634f89", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "kern-lab/hka", "max_forks_repo_path": "hka.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "a5aab11242ceffcc84a1701a3a397b1e57634f89", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "kern-lab/hka", "max_issues_repo_path": "hka.h", "max_line_length": 102, "max_stars_count": 1, "max_stars_repo_head_hexsha": "a5aab11242ceffcc84a1701a3a397b1e57634f89", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "kern-lab/hka", "max_stars_repo_path": "hka.h", "max_stars_repo_stars_event_max_datetime": "2018-10-06T02:12:05.000Z", "max_stars_repo_stars_event_min_datetime": "2018-10-06T02:12:05.000Z", "num_tokens": 210, "size": 718 }
/* ieee-utils/print.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdio.h> #include <math.h> #include <gsl/gsl_ieee_utils.h> /* A table of sign characters, 0=positive, 1=negative. We print a space instead of a unary + sign for compatibility with bc */ static char signs[2]={' ','-'} ; void gsl_ieee_fprintf_float (FILE * stream, const float * x) { gsl_ieee_float_rep r ; gsl_ieee_float_to_rep(x, &r) ; switch (r.type) { case GSL_IEEE_TYPE_NAN: fprintf(stream, "NaN") ; break ; case GSL_IEEE_TYPE_INF: fprintf(stream, "%cInf", signs[r.sign]) ; break ; case GSL_IEEE_TYPE_NORMAL: fprintf(stream, "%c1.%s*2^%d", signs[r.sign], r.mantissa, r.exponent) ; break ; case GSL_IEEE_TYPE_DENORMAL: fprintf(stream, "%c0.%s*2^%d", signs[r.sign], r.mantissa, r.exponent + 1) ; break ; case GSL_IEEE_TYPE_ZERO: fprintf(stream, "%c0", signs[r.sign]) ; break ; default: fprintf(stream, "[non-standard IEEE float]") ; } } void gsl_ieee_printf_float (const float * x) { gsl_ieee_fprintf_float (stdout,x); } void gsl_ieee_fprintf_double (FILE * stream, const double * x) { gsl_ieee_double_rep r ; gsl_ieee_double_to_rep (x, &r) ; switch (r.type) { case GSL_IEEE_TYPE_NAN: fprintf(stream, "NaN") ; break ; case GSL_IEEE_TYPE_INF: fprintf(stream, "%cInf", signs[r.sign]) ; break ; case GSL_IEEE_TYPE_NORMAL: fprintf(stream, "%c1.%s*2^%d", signs[r.sign], r.mantissa, r.exponent) ; break ; case GSL_IEEE_TYPE_DENORMAL: fprintf(stream, "%c0.%s*2^%d", signs[r.sign], r.mantissa, r.exponent + 1) ; break ; case GSL_IEEE_TYPE_ZERO: fprintf(stream, "%c0", signs[r.sign]) ; break ; default: fprintf(stream, "[non-standard IEEE double]") ; } } void gsl_ieee_printf_double (const double * x) { gsl_ieee_fprintf_double (stdout,x); }
{ "alphanum_fraction": 0.6605301915, "avg_line_length": 27.16, "ext": "c", "hexsha": "eb788dddb05e2cd322d31fd86db063057b30703c", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/ieee-utils/print.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/ieee-utils/print.c", "max_line_length": 81, "max_stars_count": 14, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/ieee-utils/print.c", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "num_tokens": 770, "size": 2716 }
#include <stdio.h> #include <stdlib.h> #include <gsl/gsl_math.h> #include <gsl/gsl_movstat.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_vector.h> int main(void) { const size_t N = 1000; /* length of time series */ const double sigma[] = { 1.0, 5.0, 1.0, 3.0, 5.0 }; /* variances */ const size_t N_sigma[] = { 200, 450, 600, 850, 1000 }; /* samples where variance changes */ const size_t K = 41; /* window size */ gsl_vector *x = gsl_vector_alloc(N); gsl_vector *xmedian = gsl_vector_alloc(N); gsl_vector *xmad = gsl_vector_alloc(N); gsl_vector *xiqr = gsl_vector_alloc(N); gsl_vector *xSn = gsl_vector_alloc(N); gsl_vector *xQn = gsl_vector_alloc(N); gsl_vector *xsd = gsl_vector_alloc(N); gsl_rng *r = gsl_rng_alloc(gsl_rng_default); gsl_movstat_workspace * w = gsl_movstat_alloc(K); size_t idx = 0; size_t i; for (i = 0; i < N; ++i) { double gi = gsl_ran_gaussian(r, sigma[idx]); double u = gsl_rng_uniform(r); double outlier = (u < 0.01) ? 15.0*GSL_SIGN(gi) : 0.0; double xi = gi + outlier; gsl_vector_set(x, i, xi); if (i == N_sigma[idx] - 1) ++idx; } /* compute moving statistics */ gsl_movstat_mad(GSL_MOVSTAT_END_TRUNCATE, x, xmedian, xmad, w); gsl_movstat_qqr(GSL_MOVSTAT_END_TRUNCATE, x, 0.25, xiqr, w); gsl_movstat_Sn(GSL_MOVSTAT_END_TRUNCATE, x, xSn, w); gsl_movstat_Qn(GSL_MOVSTAT_END_TRUNCATE, x, xQn, w); gsl_movstat_sd(GSL_MOVSTAT_END_TRUNCATE, x, xsd, w); /* scale IQR by factor to approximate standard deviation */ gsl_vector_scale(xiqr, 0.7413); /* print results */ idx = 0; for (i = 0; i < N; ++i) { printf("%zu %f %f %f %f %f %f %f\n", i, gsl_vector_get(x, i), sigma[idx], gsl_vector_get(xmad, i), gsl_vector_get(xiqr, i), gsl_vector_get(xSn, i), gsl_vector_get(xQn, i), gsl_vector_get(xsd, i)); if (i == N_sigma[idx] - 1) ++idx; } gsl_vector_free(x); gsl_vector_free(xmedian); gsl_vector_free(xmad); gsl_vector_free(xiqr); gsl_vector_free(xSn); gsl_vector_free(xQn); gsl_vector_free(xsd); gsl_rng_free(r); gsl_movstat_free(w); return 0; }
{ "alphanum_fraction": 0.6069587629, "avg_line_length": 28.3902439024, "ext": "c", "hexsha": "bc841b1d4ccaf82201f78090bb6cc812ee0918be", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_path": "test/lib/gsl-2.6/doc/examples/movstat2.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_path": "gsl-2.6/doc/examples/movstat2.c", "max_line_length": 93, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/doc/examples/movstat2.c", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "num_tokens": 733, "size": 2328 }
/** * copyright (C) 2004 * the icecube collaboration * $Id: I3GSLRandomService.h 161127 2018-02-20 14:27:18Z kjmeagher $ * * @brief An implementation of the I3RandomService interface. * * Uses the gsl library for the random numbers * * @version $Revision: 161127 $ * @date $Date: 2018-02-20 07:27:18 -0700 (Tue, 20 Feb 2018) $ * @author pretz */ #ifndef I3GSLRANDOMSERVICE_H #define I3GSLRANDOMSERVICE_H #include "phys-services/I3RandomService.h" #include <gsl/gsl_randist.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_test.h> /** * This is (the state for) a shim which allows us to count the calls to the * RNG, but otherwise hands all work off to the real GSL implmentations. */ typedef struct { unsigned long int seed; uint64_t icalls; uint64_t dcalls; gsl_rng* rng; } gsl_rng_wrapper_state; extern const gsl_rng_type gsl_rng_counting_wrapper; class I3GSLRandomService : public I3RandomService{ public: /** * default constructor */ I3GSLRandomService(); /** * constructor */ explicit I3GSLRandomService(unsigned long int seed, bool track_state=true); /** * destructor */ virtual ~I3GSLRandomService(); /** * a number drawn from a binomial distribution */ virtual int Binomial(int ntot, double prob); /** * A number from an Exponential distribution */ virtual double Exp(double tau); /** * An integer drawn uniformly from [0,imax) */ virtual unsigned int Integer(unsigned int imax); /** * An integer drawn from a Poisson distribution */ virtual int Poisson(double mean); /** * A number drawn from a Poisson distribution, as a double */ virtual double PoissonD(double mean); /** * a double drawn from a uniform distribution (0,x1) */ virtual double Uniform(double x1 = 1); /** * a double drawn from a uniform distribution (x1,x2) */ virtual double Uniform(double x1, double x2); /** * a double drawn from a Gaussian distribution with given * mean and standard deviation */ virtual double Gaus(double mean, double stddev); /** * get all information necessary to restore the internal * state of the generator */ virtual I3FrameObjectPtr GetState() const; /** * restore the internal state of the generator */ virtual void RestoreState(I3FrameObjectConstPtr state); private: // private copy constructors and assignment I3GSLRandomService(const I3GSLRandomService& ); I3GSLRandomService operator=(const I3GSLRandomService& ); /** * Helper function which constructs our preferred GSL RNG. */ static void construct(gsl_rng*& r); /** * Helper function which constructs a GSL RNG wrapped with the counting shim */ static void construct_counted(gsl_rng*& r); gsl_rng* r; bool track_state; SET_LOGGER("I3GSLRandomService"); //let gsl_wrapper_set use construct() friend void gsl_wrapper_set(void* vstate, unsigned long int s); }; I3_POINTER_TYPEDEFS(I3GSLRandomService); #endif //I3GSLRANDOMSERVICE_H
{ "alphanum_fraction": 0.7014233697, "avg_line_length": 22.3777777778, "ext": "h", "hexsha": "c1f244a3f2a7ee8933c9b809db33b9734e54b3c8", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-03-30T16:44:18.000Z", "max_forks_repo_forks_event_min_datetime": "2020-07-17T09:20:29.000Z", "max_forks_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "hschwane/offline_production", "max_forks_repo_path": "phys-services/public/phys-services/I3GSLRandomService.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "hschwane/offline_production", "max_issues_repo_path": "phys-services/public/phys-services/I3GSLRandomService.h", "max_line_length": 78, "max_stars_count": 1, "max_stars_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "hschwane/offline_production", "max_stars_repo_path": "phys-services/public/phys-services/I3GSLRandomService.h", "max_stars_repo_stars_event_max_datetime": "2020-12-24T22:00:01.000Z", "max_stars_repo_stars_event_min_datetime": "2020-12-24T22:00:01.000Z", "num_tokens": 798, "size": 3021 }
/* specfunc/legendre.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* Author: G. Jungman */ /* Declare private but non-local support functions * used in various Legendre function evaluations. */ #include <gsl/gsl_sf_result.h> /* Large negative mu asymptotic * P^{-mu}_{-1/2 + I tau}, mu -> Inf * |x| < 1 */ int gsl_sf_conicalP_xlt1_large_neg_mu_e(double mu, double tau, double x, gsl_sf_result * result, double * ln_multiplier); /* Large tau uniform asymptotics * P^{-mu}_{-1/2 + I tau}, tau -> Inf * 1 < x */ int gsl_sf_conicalP_xgt1_neg_mu_largetau_e(const double mu, const double tau, const double x, double acosh_x, gsl_sf_result * result, double * ln_multiplier); /* Large tau uniform asymptotics * P^{-mu}_{-1/2 + I tau}, tau -> Inf * -1 < x < 1 */ int gsl_sf_conicalP_xlt1_neg_mu_largetau_e(const double mu, const double tau, const double x, const double acos_x, gsl_sf_result * result, double * ln_multiplier); /* P^{mu}_{-1/2 + I tau} * x->Inf * * * This is effective to precision EPS for * * (mu^2 + tau^2)/((1 + tau^2)^(1/2) x^2) < EPS^{1/3} * * since it goes only to a fixed order, based on the * representation in terms of hypegeometric functions * of argument 1/x^2. * [Zhurina+Karmazina, (3.8)] */ int gsl_sf_conicalP_large_x_e(const double mu, const double tau, const double x, gsl_sf_result * result, double * ln_multiplier);
{ "alphanum_fraction": 0.6342710997, "avg_line_length": 32.1369863014, "ext": "h", "hexsha": "002591a3843f36e0315c24465a9ef9904512e7b3", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_path": "code/em/treba/gsl-1.0/specfunc/legendre.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_path": "code/em/treba/gsl-1.0/specfunc/legendre.h", "max_line_length": 90, "max_stars_count": 14, "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_path": "code/em/treba/gsl-1.0/specfunc/legendre.h", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "num_tokens": 616, "size": 2346 }
#ifndef __COMPLEARN_REALCOMPRESSOR_H #define __COMPLEARN_REALCOMPRESSOR_H #define COMPLEARN_REAL_COMPRESSOR_TYPE (real_compressor_get_type ()) #define COMPLEARN_TYPE_REAL_COMPRESSOR (real_compressor_get_type ()) #define COMPLEARN_REAL_COMPRESSOR(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), COMPLEARN_REAL_COMPRESSOR_TYPE, CompLearnRealCompressor)) #define IS_COMPLEARN_REAL_COMPRESSOR(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), COMPLEARN_REAL_COMPRESSOR_TYPE)) #define COMPLEARN_REAL_COMPRESSOR_GET_INTERFACE(inst) (G_TYPE_INSTANCE_GET_INTERFACE((inst), COMPLEARN_REAL_COMPRESSOR_TYPE, CompLearnRealCompressorIface)) #include <glib.h> #include <glib-object.h> #include <glib/garray.h> #include <gsl/gsl_matrix.h> #define COMPLEARN_ERROR 1 #define COMPLEARN_ERROR_NO_COMPRESSOR_SET 100 typedef struct _CompLearnRealCompressor CompLearnRealCompressor; typedef struct _CompLearnRealCompressorIface CompLearnRealCompressorIface; struct _CompLearnRealCompressorIface { GTypeInterface parent; GString *(*compress)(CompLearnRealCompressor *self, const GString *input); GString *(*decompress)(CompLearnRealCompressor *self, const GString *input); GString *(*blurb)(CompLearnRealCompressor *self); GString *(*canonical_extension)(CompLearnRealCompressor *self); GString *(*name)(CompLearnRealCompressor *self); GString *(*compressor_version)(CompLearnRealCompressor *self); GString *(*binding_version)(CompLearnRealCompressor *self); gboolean (*is_threadsafe)(CompLearnRealCompressor *self); gboolean (*is_compressible)(CompLearnRealCompressor *self, const GString *input); gboolean (*is_decompressible)(CompLearnRealCompressor *self, const GString *input); gboolean (*is_just_size)(CompLearnRealCompressor *self); gboolean (*is_hash_function)(CompLearnRealCompressor *self); GString *(*hash)(CompLearnRealCompressor *self, const GString *input); gboolean (*is_operational)(CompLearnRealCompressor *self); gboolean (*is_private_property)(CompLearnRealCompressor *self, const char *propname); gdouble (*compressed_size)(CompLearnRealCompressor *self, const GString *input); guint64 (*window_size)(CompLearnRealCompressor *self); CompLearnRealCompressor *(*clone)(CompLearnRealCompressor *self); }; GType real_compressor_get_type(void); GString *real_compressor_compress(CompLearnRealCompressor *self,const GString *input); GString *real_compressor_hash(CompLearnRealCompressor *self,const GString *input); GString *real_compressor_decompress(CompLearnRealCompressor *self,const GString *input); gdouble real_compressor_compressed_size(CompLearnRealCompressor *self,const GString *input); GString *real_compressor_blurb(CompLearnRealCompressor *self); GString *real_compressor_name(CompLearnRealCompressor *self); GString *real_compressor_compressor_version(CompLearnRealCompressor *self); GString *real_compressor_binding_version(CompLearnRealCompressor *self); gboolean real_compressor_is_compressible(CompLearnRealCompressor *self, const GString *input); gboolean real_compressor_is_decompressible(CompLearnRealCompressor *self, const GString *input); gboolean real_compressor_is_private_property(CompLearnRealCompressor *self, const char *input); guint64 real_compressor_window_size(CompLearnRealCompressor *self); gboolean real_compressor_is_threadsafe(CompLearnRealCompressor *self); gboolean real_compressor_is_just_size(CompLearnRealCompressor *self); gboolean real_compressor_is_hash_function(CompLearnRealCompressor *self); GString *real_compressor_canonical_extension(CompLearnRealCompressor *rc); gboolean real_compressor_is_operational(CompLearnRealCompressor *self); CompLearnRealCompressor *real_compressor_clone(CompLearnRealCompressor *self); #define SET_DEFAULT_PROPS(groupname, clt, mobj) \ do { \ GParamSpec **gps, **cur; \ g_assert(mobj != NULL); \ if (complearn_environment_get_nameable(groupname) == NULL) { \ complearn_environment_register_nameable(groupname, G_OBJECT(mobj)); \ break; \ } \ gps =g_object_class_list_properties(G_OBJECT_CLASS(clt(mobj)), NULL); \ for (cur = gps; *cur; cur += 1) { \ GValue v = {0,}; \ g_value_init(&v, (*cur)->value_type); \ g_param_value_set_default(*cur, &v); \ g_object_set_property(G_OBJECT(mobj), (*cur)->name, &v); \ complearn_environment_register_property(G_OBJECT(mobj), (*cur), &v); \ } } while(0) #define SET_DEFAULT_COMPRESSOR_PROPS(groupname, clt, mobj) \ do { \ SET_DEFAULT_PROPS(groupname, clt, mobj); \ if (complearn_environment_get_nameable(groupname) == NULL) { \ complearn_environment_register_compressor(mobj); \ } \ } while (0); #endif #define G_LOG_LEVEL_NOTICE G_LOG_LEVEL_USER_SHIFT #define g_notice(...) g_log(G_LOG_DOMAIN, G_LOG_LEVEL_NOTICE, __VA_ARGS__) void real_compressor_interface_init (gpointer g_iface, gpointer iface_data);
{ "alphanum_fraction": 0.805561277, "avg_line_length": 50.5729166667, "ext": "h", "hexsha": "9dec49365f4fe600dd497d73b38655bd7e20367e", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "c70ac5ad7bcfe3af80a2a8f087ee6f5904820a66", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "rudi-cilibrasi/classic-complearn", "max_forks_repo_path": "src/complearn/real-compressor.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "c70ac5ad7bcfe3af80a2a8f087ee6f5904820a66", "max_issues_repo_issues_event_max_datetime": "2017-03-15T18:30:04.000Z", "max_issues_repo_issues_event_min_datetime": "2016-05-10T12:56:52.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "rudi-cilibrasi/classic-complearn", "max_issues_repo_path": "src/complearn/real-compressor.h", "max_line_length": 155, "max_stars_count": 2, "max_stars_repo_head_hexsha": "c70ac5ad7bcfe3af80a2a8f087ee6f5904820a66", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "rudi-cilibrasi/classic-complearn", "max_stars_repo_path": "src/complearn/real-compressor.h", "max_stars_repo_stars_event_max_datetime": "2018-06-08T11:13:03.000Z", "max_stars_repo_stars_event_min_datetime": "2018-03-14T13:52:31.000Z", "num_tokens": 1241, "size": 4855 }
/* Excited States software: KGS Contributors: See CONTRIBUTORS.txt Contact: kgs-contact@simtk.org Copyright (C) 2009-2017 Stanford University Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: This entire text, including the above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS, CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef KGS_LSNRELATIVEDIRECTION_H #define KGS_LSNRELATIVEDIRECTION_H #include <gsl/gsl_vector.h> #include "Selection.h" #include "Direction.h" #include "core/Configuration.h" class LSNrelativeDirection: public Direction { public: LSNrelativeDirection(Selection& atomsMoving, const std::vector< std::tuple<Atom*, Atom*, double> >& goal_distances); const std::vector< std::tuple<Atom*, Atom*, double> > getGoalDistances(){return m_goalDistances;} void setGoalDistances(std::vector< std::tuple<Atom*, Atom*, double> > goal_distances){m_goalDistances=goal_distances;} protected: void computeGradient(Configuration* conf, Configuration* conf2, gsl_vector* ret) override; void computeGradientExternalN(gsl_matrix* fullN, Configuration* conf, Configuration* conf2, gsl_vector* ret); private: void fillmatrices(Configuration* current_q, gsl_matrix* targetJacobian, gsl_matrix* targetDirection); // void clashFreeGradient(gsl_vector* gradient, gsl_vector* admissible_gradient, Molecule* protein); gsl_matrix* determineBestMove(gsl_matrix* N, gsl_matrix* targetJacobian, gsl_matrix* TargetPosition); Selection& m_atomsMovingSelection; std::vector< std::tuple<Atom*, Atom*, double> > m_goalDistances; friend class LSNclashAvoidingMove; //requires the computeGradientExternalN function }; #endif //KGS_LSNRELATIVEDIRECTION_H
{ "alphanum_fraction": 0.7888030888, "avg_line_length": 39.8461538462, "ext": "h", "hexsha": "7beb049d65b5e1ab138a900d9bc67fb937d76129", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "XiyuChenFAU/kgs_vibration_entropy", "max_forks_repo_path": "src/directions/LSNrelativeDirection.h", "max_issues_count": 8, "max_issues_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9", "max_issues_repo_issues_event_max_datetime": "2021-02-06T16:06:30.000Z", "max_issues_repo_issues_event_min_datetime": "2017-01-26T19:54:38.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "XiyuChenFAU/kgs_vibration_entropy", "max_issues_repo_path": "src/directions/LSNrelativeDirection.h", "max_line_length": 120, "max_stars_count": 1, "max_stars_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "XiyuChenFAU/kgs_vibration_entropy", "max_stars_repo_path": "src/directions/LSNrelativeDirection.h", "max_stars_repo_stars_event_max_datetime": "2020-05-23T18:26:14.000Z", "max_stars_repo_stars_event_min_datetime": "2020-05-23T18:26:14.000Z", "num_tokens": 589, "size": 2590 }
#include <math.h> #include <matrix.h> #include <mex.h> #include <string.h> #include <blas.h> void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { double * A = mxGetPr(prhs[0]); double * B = mxGetPr(prhs[1]); double * rows = mxGetPr(prhs[2]); double * cols = mxGetPr(prhs[3]); mwSize n_inds = mxGetM(prhs[2]); mwSize m_len_A = mxGetM(prhs[0]); mwSize m_len_B = mxGetM(prhs[1]); plhs[0] = mxCreateDoubleMatrix(n_inds, 1, mxREAL); double *pr = mxGetPr(plhs[0]); mwSize cur_row; mwSize cur_col; mwSignedIndex one = 1; mwSignedIndex dot_length = (mwSignedIndex)m_len_B; /* For each element we wish to calculate */ for (int i = 0; i < n_inds; i++) { cur_row = rows[i]; cur_col = cols[i]; pr[i] = ddot(&dot_length, &A[m_len_A * (cur_row-1)], &one, &B[m_len_A * (cur_col-1)], &one); } }
{ "alphanum_fraction": 0.5827956989, "avg_line_length": 25.1351351351, "ext": "c", "hexsha": "344f98a9d16bd70e495d2e8b3bd7263977f2b06f", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-08-13T16:34:29.000Z", "max_forks_repo_forks_event_min_datetime": "2017-10-27T06:41:40.000Z", "max_forks_repo_head_hexsha": "9189465e4b14c344fac73756ffb6cf84fb36b68f", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "sjtrny/kssc", "max_forks_repo_path": "common/selmult_mt_m_fast.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "9189465e4b14c344fac73756ffb6cf84fb36b68f", "max_issues_repo_issues_event_max_datetime": "2019-08-19T00:40:21.000Z", "max_issues_repo_issues_event_min_datetime": "2017-04-05T12:22:26.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "sjtrny/kssc", "max_issues_repo_path": "common/selmult_mt_m_fast.c", "max_line_length": 100, "max_stars_count": 11, "max_stars_repo_head_hexsha": "9189465e4b14c344fac73756ffb6cf84fb36b68f", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "sjtrny/kssc", "max_stars_repo_path": "common/selmult_mt_m_fast.c", "max_stars_repo_stars_event_max_datetime": "2020-11-19T10:39:49.000Z", "max_stars_repo_stars_event_min_datetime": "2017-04-05T03:02:23.000Z", "num_tokens": 306, "size": 930 }
//**************************************************************************\ //* This file is property of and copyright by the ALICE Project *\ //* ALICE Experiment at CERN, All rights reserved. *\ //* *\ //* Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no> *\ //* for The ALICE HLT Project. *\ //* *\ //* Permission to use, copy, modify and distribute this software and its *\ //* documentation strictly for non-commercial purposes is hereby granted *\ //* without fee, provided that the above copyright notice appears in all *\ //* copies and that both the copyright notice and this permission notice *\ //* appear in the supporting documentation. The authors make no claims *\ //* about the suitability of this software for any purpose. It is *\ //* provided "as is" without express or implied warranty. *\ //************************************************************************** /// \file GPUO2InterfaceConfiguration.h /// \author David Rohr #ifndef GPUO2INTERFACECONFIGURATION_H #define GPUO2INTERFACECONFIGURATION_H #ifndef HAVE_O2HEADERS #define HAVE_O2HEADERS #endif #ifndef GPUCA_TPC_GEOMETRY_O2 #define GPUCA_TPC_GEOMETRY_O2 #endif #ifndef GPUCA_O2_INTERFACE #define GPUCA_O2_INTERFACE #endif #include <memory> #include <array> #include <vector> #include <functional> #include <gsl/gsl> #include "GPUSettings.h" #include "GPUDataTypes.h" #include "GPUHostDataTypes.h" #include "GPUOutputControl.h" #include "DataFormatsTPC/Constants.h" class TH1F; class TH1D; class TH2F; namespace o2 { namespace tpc { class TrackTPC; class Digit; } // namespace tpc namespace gpu { class TPCFastTransform; class GPUReconstruction; struct GPUSettingsO2; struct GPUInterfaceQAOutputs { const std::vector<TH1F>* hist1; const std::vector<TH2F>* hist2; const std::vector<TH1D>* hist3; }; struct GPUInterfaceOutputs : public GPUTrackingOutputs { GPUInterfaceQAOutputs qa; }; // Full configuration structure with all available settings of GPU... struct GPUO2InterfaceConfiguration { GPUO2InterfaceConfiguration() = default; ~GPUO2InterfaceConfiguration() = default; GPUO2InterfaceConfiguration(const GPUO2InterfaceConfiguration&) = default; // Settings for the Interface class struct GPUInterfaceSettings { int dumpEvents = 0; bool outputToExternalBuffers = false; float memoryBufferScaleFactor = 1.f; // These constants affect GPU memory allocation only and do not limit the CPU processing unsigned long maxTPCZS = 8192ul * 1024 * 1024; unsigned int maxTPCHits = 1024 * 1024 * 1024; unsigned int maxTRDTracklets = 128 * 1024; unsigned int maxITSTracks = 96 * 1024; }; GPUSettingsDeviceBackend configDeviceBackend; GPUSettingsProcessing configProcessing; GPUSettingsGRP configGRP; GPUSettingsRec configReconstruction; GPUSettingsDisplay configDisplay; GPUSettingsQA configQA; GPUInterfaceSettings configInterface; GPURecoStepConfiguration configWorkflow; GPUCalibObjects configCalib; GPUSettingsO2 ReadConfigurableParam(); private: friend class GPUReconstruction; GPUSettingsO2 ReadConfigurableParam_internal(); }; } // namespace gpu } // namespace o2 #endif
{ "alphanum_fraction": 0.6738686131, "avg_line_length": 31.1363636364, "ext": "h", "hexsha": "e5b81b0489f3bb0a3415d29dd51a7185a1ff06e4", "lang": "C", "max_forks_count": 275, "max_forks_repo_forks_event_max_datetime": "2022-03-31T13:06:19.000Z", "max_forks_repo_forks_event_min_datetime": "2016-06-21T20:24:05.000Z", "max_forks_repo_head_hexsha": "c1d89b133b433f608b2373112d3608d8cec26095", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "chengtt0406/AliRoot", "max_forks_repo_path": "GPU/GPUTracking/Interface/GPUO2InterfaceConfiguration.h", "max_issues_count": 1388, "max_issues_repo_head_hexsha": "c1d89b133b433f608b2373112d3608d8cec26095", "max_issues_repo_issues_event_max_datetime": "2022-03-30T15:26:09.000Z", "max_issues_repo_issues_event_min_datetime": "2016-11-01T10:27:36.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "chengtt0406/AliRoot", "max_issues_repo_path": "GPU/GPUTracking/Interface/GPUO2InterfaceConfiguration.h", "max_line_length": 92, "max_stars_count": 52, "max_stars_repo_head_hexsha": "c1d89b133b433f608b2373112d3608d8cec26095", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "chengtt0406/AliRoot", "max_stars_repo_path": "GPU/GPUTracking/Interface/GPUO2InterfaceConfiguration.h", "max_stars_repo_stars_event_max_datetime": "2022-03-11T11:49:35.000Z", "max_stars_repo_stars_event_min_datetime": "2016-12-11T13:04:01.000Z", "num_tokens": 766, "size": 3425 }
#include <stdio.h> #include <string.h> #include <math.h> #include "chaincolln.h" #include "cokus.h" #include "chain.h" #include "config.h" #include "parameters.h" #include "irmutils.h" #include "relation.h" #include "domain.h" #ifdef GSL #include <gsl/gsl_randist.h> #include <gsl/gsl_permutation.h> #include <gsl/gsl_rng.h> #endif /***************************************************************************** A collection of chains. We maintain several chains in case we want to run Metropolis-coupled MCMC (MC^3). We also keep one spare chain so that split-merge proposals can be tried without losing the current state. *****************************************************************************/ struct chaincolln_str { int nchains; chain *chains; chain sparechain; char prefix[MAXSTRING]; /* unused right now */ int itercount; /* iteration count */ } chaincolln_str; /* nchains already includes one extra for sparechain */ chaincolln chaincolln_create(int nchains, int ndomains, int nrelns, char *pref) { int i; chaincolln cc; double temp; cc = (chaincolln) my_malloc(sizeof(struct chaincolln_str)); cc->chains = (chain *) my_malloc(nchains*sizeof(chain )); /* include spare chain */ for (i = 0; i < nchains; i++) { temp = 1.0/(1+ps.temp*i); cc->chains[i] = chain_create(ndomains, nrelns, temp); } cc->nchains = nchains-1; cc->sparechain = cc->chains[nchains-1]; strcpy(cc->prefix, pref); cc->itercount = 0; return cc; } /* read the configuration file and the graph */ chaincolln chaincolln_readdata(void) { FILE *fileptr, *initzsfile; int i, j, k, ndom, nreln, d, r, nitem, dim, maxclass, initclass, relcl, ndim, domlabel, clusterflag, itemind, nchains, cind, zind; int *domlabels, *participants, participant; double val; double nig[DISTSIZE]; domain *doms; relation rn; int *initclasses, ***edgecounts, *relsizes; char prefix[MAXSTRING]; chaincolln cc; chain c, c0; #ifdef GSL gsl_rng *rng; const gsl_rng_type *T; gsl_permutation *perm ; size_t N; gsl_rng_env_setup(); T = gsl_rng_default; rng = gsl_rng_alloc(T); #endif fprintf(stdout,"A\n"); nchains = ps.nchains+1; nig[0] = ps.m; nig[1] = ps.v; nig[2] = ps.a; nig[3] = ps.b; fileptr = fopen(ps.configfile,"r"); if (fileptr == NULL) { fprintf(stderr, "couldn't read config file\n"); exit(1); } /* initial read of ps.configfile to get ps.maxdim, ps.maxrel, ps.maxitem, ps.maxclass */ fscanf(fileptr, "%s", prefix); fscanf(fileptr, "%d %d", &ndom, &nreln); relsizes= (int *) my_malloc(nreln*sizeof(int)); ps.maxrel = nreln; ps.maxitem = 0; ps.maxclass = 0; for (d = 0; d < ndom; d++) { fscanf(fileptr, "%d %d %d %d", &nitem, &maxclass, &initclass, &clusterflag); if (nitem > ps.maxitem) { ps.maxitem = nitem; } if (maxclass > ps.maxclass) { ps.maxclass= maxclass; } } fprintf(stdout,"B\n"); ps.maxdim = 0; for (r = 0; r < nreln; r++) { fscanf(fileptr, "%d", &ndim); relsizes[r] = ndim; if (ndim > ps.maxdim) { ps.maxdim = ndim; } for (dim=0; dim < ndim; dim++) { fscanf(fileptr, "%d", &domlabel); } } fclose(fileptr); fprintf(stdout,"C\n"); domlabels= (int *) my_malloc(ps.maxdim*sizeof(int)); participants= (int *) my_malloc(ps.maxdim*sizeof(int)); initclasses = (int *) my_malloc(ps.maxitem*sizeof(int)); fprintf(stdout,"D \n"); /* initial read of ps.graphname to get ps.maxobjtuples */ edgecounts = (int ***) my_malloc(ps.maxrel*sizeof(int **)); for (i = 0; i < ps.maxrel; i++) { edgecounts[i] = (int **) my_malloc(ps.maxdim*sizeof(int *)); for (j = 0; j < ps.maxdim; j++) { edgecounts[i][j] = (int *) my_malloc(ps.maxitem*sizeof(int)); for (k = 0; k < ps.maxitem; k++) { edgecounts[i][j][k] = 0; } } } ps.maxobjtuples = 0; fprintf(stdout,"D2 \n"); fileptr = fopen(ps.graphname,"r"); if (fileptr == NULL) { fprintf(stderr, "couldn't read graph\n"); exit(1); } while( fscanf( fileptr, " %d", &r)!=EOF ) { fprintf(stdout,"%s %d %d\n",__FILE__,__LINE__,r); ndim = relsizes[r]; fprintf(stdout,"%s %d %d\n",__FILE__,__LINE__,ndim); for (dim = 0; dim < ndim; dim++) { fscanf(fileptr, "%d", &participant); participants[dim] = participant; } fscanf(fileptr, "%lf", &val); for (dim = 0; dim < ndim; dim++) { fprintf(stdout,"D2 %d %d %d \n",r,dim,participants[dim]); edgecounts[r][dim][participants[dim]]++; fprintf(stdout,"D2 %d %d %d \n",r,dim,participants[dim]); } } fprintf(stdout,"E\n"); fclose(fileptr); for (i = 0; i < ps.maxrel; i++) { for (j = 0; j < ps.maxdim; j++) { for (k = 0; k < ps.maxitem; k++) { if (edgecounts[i][j][k] > ps.maxobjtuples) { ps.maxobjtuples = edgecounts[i][j][k]; } edgecounts[i][j][k]= 0; } } } fprintf(stdout,"F\n"); free(relsizes); for (i = 0; i < ps.maxrel; i++) { for (j = 0; j < ps.maxdim; j++) { free(edgecounts[i][j]); } free(edgecounts[i]); } free(edgecounts); fprintf(stdout,"G\n"); /* second read of ps.configfile where we set up datastructures */ fileptr = fopen(ps.configfile,"r"); if (ps.outsideinit) { initzsfile= fopen(ps.initfile,"r"); if (initzsfile == NULL) { fprintf(stderr, "couldn't read initzsfile\n"); exit(1); } } else { initzsfile = NULL; } fprintf(stdout,"H\n"); fscanf(fileptr, "%s", prefix); fscanf(fileptr, "%d %d", &ndom, &nreln); cc = chaincolln_create(nchains, ndom, nreln, prefix); c0 = chaincolln_getchain(cc, 0); fprintf(stdout,"I\n"); /* read domains */ /* input file: nitem maxclass initclass clusterflag*/ for (d = 0; d < ndom; d++) { fscanf(fileptr, "%d %d %d %d", &nitem, &maxclass, &initclass, &clusterflag); #ifdef GSL N = nitem; #endif if (ps.outsideinit) { for (zind = 0; zind < nitem; zind++) { fscanf(initzsfile, "%d", &initclasses[zind]); } } fprintf(stdout,"J\n"); /* add domains and items to chains */ for (cind = 0; cind < nchains; cind++) { c = chaincolln_getchain(cc, cind); chain_adddomain(c, d, nitem, maxclass, clusterflag, ps.alpha, ps.alphahyp, initclasses); #ifdef GSL perm = gsl_permutation_alloc(N); gsl_permutation_init(perm); gsl_ran_shuffle(rng, perm->data, N, sizeof(size_t)); #endif /* assign items to classes */ relcl = 0; for (i = 0; i < nitem; i++) { if (ps.outsideinit) { chain_additemtoclass(c, d, i, initclasses[i]); } else { if (relcl == initclass) relcl = 0; /* without the GNUSL, each chain gets initialized the same way. This * is suboptimal */ itemind = i; #ifdef GSL itemind = gsl_permutation_get(perm, i); #endif chain_additemtoclass(c, d, itemind, relcl); relcl++; } } #ifdef GSL gsl_permutation_free(perm); #endif } } #ifdef GSL gsl_rng_free(rng); #endif fprintf(stdout,"K\n"); /* read relations*/ /* input file: ndim d0 ... dn */ for (r = 0; r < nreln; r++) { fscanf(fileptr, "%d", &ndim); for (dim=0; dim < ndim; dim++) { fscanf(fileptr, "%d", &domlabel); domlabels[dim] = domlabel; } for (cind = 0; cind < nchains; cind++) { c = chaincolln_getchain(cc, cind); chain_addrelation(c, r, ndim, ps.betaprop, ps.betamag, nig, domlabels); } } if (ps.outsideinit) { fclose(initzsfile); } fprintf(stdout,"L\n"); fclose(fileptr); /* second read of ps.graphname: store edges*/ fileptr = fopen(ps.graphname,"r"); /* input file: relind p0 p1 p2 .. pn val */ while( fscanf( fileptr, " %d", &r)!= EOF ) { ndim = relation_getdim( chain_getrelation(c0, r) ); doms = relation_getdoms( chain_getrelation(c0, r) ); for (dim = 0; dim < ndim; dim++) { fscanf(fileptr, "%d", &participant); fprintf(stdout,"M %d %d\n",dim,participant); participants[dim] = participant; domlabels[dim] = domain_getlabel(doms[dim]); } for (i = 0; i < ndim; i++) { for (j = 0; j < i; j++) { if (participants[i] == participants[j] && domlabels[i] == domlabels[j]) { fprintf(stderr, "Self links not allowed.\n"); exit(1); } } } fscanf(fileptr, "%lf", &val); fprintf(stderr,"%d\n",nchains); for (cind = 0; cind < nchains; cind++) { c = chaincolln_getchain(cc, cind); chain_addedge(c, r, val, participants); rn = chain_getrelation(c, r); if (doubleeq(val, 0)) { relation_setmissing(rn, 1); } if (val > 1.5 && relation_getdtype(rn) != CONT) { relation_setdtype(rn, FREQ); } if (!doubleeq(val, (int) val)) { relation_setdtype(rn, CONT); relation_setmissing(rn, 1); /* XXX: no sparse continuous matrices */ } } } fprintf(stderr,"N\n"); fclose(fileptr); for (cind = 0; cind < nchains; cind++) { c = chaincolln_getchain(cc, cind); for (i = 0; i < chain_getndomains(c); i++) { chain_updatedomprobs(c, i); } } fprintf(stderr,"O\n"); free(domlabels); free(participants); free(initclasses); return cc; } int chaincolln_getnchain(chaincolln cc) { return cc->nchains; } chain chaincolln_getchain(chaincolln cc, int chainind) { return cc->chains[chainind]; } char *chaincolln_getprefix(chaincolln cc) { return cc->prefix; } int chaincolln_getitercount(chaincolln cc) { return cc->itercount; } void chaincolln_print(chaincolln cc) { chaincolln_printassignments(cc); chaincolln_printstatus(cc, NULL); chaincolln_printstatus(cc, stderr); } /* run hillclimbing with random restarts */ void chaincolln_climb(chaincolln cc, int maxloops) { int i, j, changeflag, nrepeats; chain chn, schn; double oldscore, newscore, currscore; chn = chaincolln_getchain(cc, 0); schn = cc->sparechain; changeflag = 1; nrepeats = 0; oldscore = -MAXDOUBLE; currscore= -MAXDOUBLE; chaincolln_print(cc); for (i = 0; i < maxloops; i++) { if (changeflag > 0) { /* maximizing scan: move each object to the best class for it */ changeflag = chain_climbscan(chn); } /*chain_print(chn); fprintf(stderr, "splitting\n");*/ changeflag = changeflag + chain_climbsplitfast(chn, schn); /*chain_print(chn); fprintf(stderr, "merging\n");*/ changeflag = changeflag + chain_climbmergefast(chn, schn); for (j = 0; j < ps.hypupdates; j++) { changeflag = changeflag + chaincolln_hypupdates(cc, &proposal_best); } cc->itercount++; newscore = chain_getprob(chn); if ( fabs(newscore - oldscore) < 0.00001 * fabs(newscore) ) { nrepeats++; if (nrepeats == 8) { chaincolln_print(cc); fprintf(stderr, "*************** randomize\n"); nrepeats = 0; chain_randomize(cc->chains[0]); currscore = chain_getprob(chn); newscore = chain_getprob(chn); } } else { nrepeats = 0; } oldscore = newscore; chaincolln_printstatus(cc, stderr); } } /* run gibbs sampler with Metropolis updates (MC^3, split-merge) */ void chaincolln_mcmc(chaincolln cc, int maxloops) { int i, j; chaincolln_print(cc); for (i = 0; i < maxloops; i++) { fprintf(stderr,"loop %d",i); /* gibbs scans and split merge updates */ chaincolln_sample(cc, 1); /* MC^3: try swaps between chains at different temperatures */ chaincolln_tryswaps(cc); /* hyperparameter updates? */ for (j = 0; j < ps.hypupdates; j++) { chaincolln_hypupdates(cc, &proposal_mcmc); } chaincolln_print(cc); } } /* update hyperparameters */ int chaincolln_hypupdates(chaincolln cc, int (*proposal_choose) (double, double, double)) { int i, changeflag; changeflag = 0; for (i = 0; i < cc->nchains; i++) { chain_hypupdate(chaincolln_getchain(cc, i), proposal_choose, &changeflag); } return changeflag; } void chaincolln_itergibbsm(chaincolln cc) { int i; if (1) { /* regular gibbs scans */ for (i = 0; i < cc->nchains; i++) { chain_itergibbs(chaincolln_getchain(cc, i)); } } if (1) { /* split-merge updates */ for (i = 0; i < cc->nchains; i++) { chain_itersm(chaincolln_getchain(cc, i), cc->sparechain); } } cc->itercount++; } void chaincolln_sample(chaincolln cc, int niter) { int i; for (i = 0; i < niter; i++) { chaincolln_itergibbsm(cc); } } /* try swapping chains at different temperatures */ void chaincolln_tryswaps(chaincolln cc) { int nchains; int sw1, sw2, swcount; chain c1, c2; double t1, t2, aswap, rn; nchains = cc->nchains; if (nchains > 1) { for (swcount = 0; swcount < 1; swcount++) { sw1 = randomitem(nchains); sw2 = sw1; while (sw2 == sw1) { sw2 = randomitem(nchains); } c1 = cc->chains[sw1]; c2 = cc->chains[sw2]; t1 = chain_gettemp(c1); t2 = chain_gettemp(c2); aswap = exp( (t1 - t2)* (chain_getprob(c2) - chain_getprob(c1)) ); if (aswap > 1) { aswap=1; } rn = myrand(); if (rn < aswap) { chaincolln_swapchains(cc, sw1, sw2); fprintf(stderr, "****CS: %f\n", aswap); } } } } /* swap chains SW1 and SW2 */ void chaincolln_swapchains(chaincolln cc, int sw1, int sw2) { chain c1, c2; double t1, t2; c1 = chaincolln_getchain(cc, sw1); c2 = chaincolln_getchain(cc, sw2); t1 = chain_gettemp(c1); t2 = chain_gettemp(c2); chain_settemp(c1, t2); chain_settemp(c2, t1); cc->chains[sw1] = c2; cc->chains[sw2] = c1; } void chaincolln_printassignments(chaincolln cc) { int i; chain chn; char filename[MAXSTRING]; FILE * domfileptr; chn = chaincolln_getchain(cc, 0); for (i = 0; i < chain_getndomains(chn); i++) { sprintf(filename, "%s_dom%d", ps.outroot, i); domfileptr = fopen(filename, "a"); if (domfileptr == NULL) { fprintf(stderr, "couldn't read domain file\n"); exit(1); } domain_printassignments(domfileptr, chain_getdomain(chn, i)); fclose(domfileptr); } } void chaincolln_printstatus(chaincolln cc, FILE *fptr) { int i, nchains; chain chn; char filename[MAXSTRING]; FILE * domfileptr; nchains = chaincolln_getnchain(cc); if (fptr == NULL) { sprintf(filename, "%s_status", ps.outroot); domfileptr = fopen(filename, "a"); if (domfileptr == NULL) { fprintf(stderr, "couldn't read statusfile\n"); exit(1); } } else { domfileptr = fptr; } fprintf(domfileptr, "%4d: ", chaincolln_getitercount(cc)); chn = chaincolln_getchain(cc, 0); chain_printdetailedstatus(chn, domfileptr); for (i = 1; i < nchains; i++) { chn = chaincolln_getchain(cc, i); chain_printbriefstatus(chn, domfileptr); } chn = chaincolln_getchain(cc,0); chain_printhyps(chn, domfileptr); fprintf(domfileptr, "\n"); if (fptr == NULL) { fclose(domfileptr); } } void chaincolln_free(chaincolln cc) { int i; /* include spare chain */ for (i = 0; i < cc->nchains+1; i++) { chain_free(cc->chains[i]); } free(cc->chains); free(cc); }
{ "alphanum_fraction": 0.6000792969, "avg_line_length": 26.6895943563, "ext": "c", "hexsha": "c9861b4c05eacd928f095e9fc6b1bb831c853278", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "93cddb9931509e90693c61a559b98c24ba8a7110", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "adamsumm/CausalMario", "max_forks_repo_path": "HiddenCauses/irm/chaincolln.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "93cddb9931509e90693c61a559b98c24ba8a7110", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "adamsumm/CausalMario", "max_issues_repo_path": "HiddenCauses/irm/chaincolln.c", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "93cddb9931509e90693c61a559b98c24ba8a7110", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "adamsumm/CausalMario", "max_stars_repo_path": "HiddenCauses/irm/chaincolln.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4829, "size": 15133 }
#ifndef _GSLRNG_H #define _GSLRNG_H #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <ctime> #include <vector> using namespace std; namespace myGSL { class Rng; class PoissonGenerator; }; typedef myGSL::Rng GSLRng; class myGSL::Rng { public: Rng(const gsl_rng_type * T = gsl_rng_taus2, unsigned long seed = time(NULL)) : rng(gsl_rng_alloc(T)), discrete_t(NULL) { gsl_rng_set(rng,seed); } Rng(const Rng& R) : rng(gsl_rng_clone(R.constptr())), discrete_t(NULL) {} ~Rng() { gsl_rng_free(rng); if (discrete_t != NULL) discrete_free(); } inline void set(unsigned long seed) { gsl_rng_set(rng,seed); } inline unsigned long min() { return gsl_rng_min(rng); } inline unsigned long max() { return gsl_rng_max(rng); } // uniform distributions inline unsigned long get() { return gsl_rng_get(rng); } inline double uniform() { return gsl_rng_uniform(rng); } inline double uniform_pos() { return gsl_rng_uniform_pos(rng); } inline double uniform(double a, double b) { return a + (b-a)*uniform(); } inline unsigned long uniform_int(unsigned long n) { return gsl_rng_uniform_int(rng,n); } // other distributions inline double gaussian(double mu, double s) { return gsl_ran_gaussian(rng,s) + mu; } inline unsigned long binomial(double r, unsigned n) { return gsl_ran_binomial(rng,r,n); } inline unsigned int poisson(double mu) { return gsl_ran_poisson(rng,mu); } inline double exponential(double mu) { return gsl_ran_exponential(rng,mu); } // discrete distributions inline void discrete_preproc(int K, const double * P) { discrete_t = gsl_ran_discrete_preproc(K,P); } inline int get_discrete() { return gsl_ran_discrete(rng,discrete_t); } inline void discrete_free() { gsl_ran_discrete_free(discrete_t); discrete_t = NULL; } template<typename T> inline void shuffle(vector<T>& src, size_t first = 0, size_t last = -1) { if (first >= src.size()) return; if (last > src.size()) last = src.size(); gsl_ran_shuffle(rng,&src[first],last-first,sizeof(T)); } template<typename T> inline void choose(vector<T>& src, vector<T>& dest) { gsl_ran_choose(rng,&dest[0],dest.size(),&src[0],src.size(),sizeof(T)); } inline gsl_rng * ptr() { return rng; } inline const gsl_rng * constptr() const { return rng; } private: gsl_rng * rng; gsl_ran_discrete_t * discrete_t; }; class myGSL::PoissonGenerator { public: double mu; Rng* rng; PoissonGenerator(double m, Rng* r) { mu = m; rng = r; } double operator()() { return rng->poisson(mu); } }; #endif
{ "alphanum_fraction": 0.6904854369, "avg_line_length": 31.4024390244, "ext": "h", "hexsha": "a35618f2c39133543d403bf41f94416bdfec72d6", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2022-03-17T09:34:55.000Z", "max_forks_repo_forks_event_min_datetime": "2017-11-11T13:00:48.000Z", "max_forks_repo_head_hexsha": "9c831df9bdcd2eb9890a4d12c47f1935e53a7062", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "marieberth/tiff_opt", "max_forks_repo_path": "GSLRng.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "9c831df9bdcd2eb9890a4d12c47f1935e53a7062", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "marieberth/tiff_opt", "max_issues_repo_path": "GSLRng.h", "max_line_length": 103, "max_stars_count": 17, "max_stars_repo_head_hexsha": "9c831df9bdcd2eb9890a4d12c47f1935e53a7062", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "marieberth/tiff_opt", "max_stars_repo_path": "GSLRng.h", "max_stars_repo_stars_event_max_datetime": "2021-03-03T11:02:58.000Z", "max_stars_repo_stars_event_min_datetime": "2016-11-28T07:13:41.000Z", "num_tokens": 717, "size": 2575 }
#include <gsl/gsl_errno.h> #include <gsl/matrix/gsl_matrix.h> #include <string.h> #define BASE_DOUBLE #include <gsl/templates_on.h> #include <gsl/matrix/copy_source.c> #include <gsl/templates_off.h> #undef BASE_DOUBLE
{ "alphanum_fraction": 0.7681818182, "avg_line_length": 20, "ext": "c", "hexsha": "df30e8aa5f74b04ad9941c395a04bed50f8f737b", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "MontyThibault/centre-of-mass-awareness", "max_forks_repo_path": "Cartwheel/cartwheel-3d/gsl/matrix/copy.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "MontyThibault/centre-of-mass-awareness", "max_issues_repo_path": "Cartwheel/cartwheel-3d/gsl/matrix/copy.c", "max_line_length": 35, "max_stars_count": null, "max_stars_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "MontyThibault/centre-of-mass-awareness", "max_stars_repo_path": "Cartwheel/cartwheel-3d/gsl/matrix/copy.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 60, "size": 220 }
#ifndef MATRIX_H #define MATRIX_H #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <stdbool.h> #include <config.h> #include "collections.h" #include "file_utils.h" #include "vector.h" #include "vector_math.h" #ifdef HAVE_CBLAS #include <cblas.h> #else #warning "No CLBAS" #endif typedef enum { MATRIX_DENSE, MATRIX_SPARSE } matrix_type_t; #define MATRIX_INIT(name, type, type_name, array_type) \ typedef struct { \ size_t m, n; \ type *values; \ } name##_t; \ \ static name##_t *name##_new(size_t m, size_t n) { \ name##_t *matrix = malloc(sizeof(name##_t)); \ \ if (matrix == NULL) { \ return NULL; \ } \ \ matrix->m = m; \ matrix->n = n; \ \ matrix->values = malloc(sizeof(type) * m * n); \ if (matrix->values == NULL) { \ free(matrix); \ return NULL; \ } \ \ return matrix; \ \ } \ \ static name##_t *name##_new_aligned(size_t m, size_t n, size_t alignment) { \ name##_t *matrix = malloc(sizeof(name##_t)); \ \ if (matrix == NULL) { \ return NULL; \ } \ \ matrix->m = m; \ matrix->n = n; \ \ matrix->values = _aligned_malloc(sizeof(type) * m * n, alignment); \ if (matrix->values == NULL) { \ free(matrix); \ return NULL; \ } \ \ return matrix; \ \ } \ \ static void name##_destroy(name##_t *self) { \ if (self == NULL) return; \ \ if (self->values != NULL) { \ free(self->values); \ } \ \ free(self); \ } \ \ static void name##_destroy_aligned(name##_t *self) { \ if (self == NULL) return; \ \ if (self->values != NULL) { \ _aligned_free(self->values); \ } \ \ free(self); \ } \ \ static inline void name##_zero(name##_t *self) { \ memset(self->values, 0, self->m * self->n * sizeof(type)); \ } \ \ \ static inline bool name##_resize(name##_t *self, size_t m, size_t n) { \ if (self == NULL) return false; \ \ if (m * n > (self->m * self->n)) { \ type *ptr = realloc(self->values, sizeof(type) * m * n); \ if (ptr == NULL) { \ return false; \ } \ self->values = ptr; \ } \ \ self->m = m; \ self->n = n; \ \ return true; \ } \ \ static inline bool name##_resize_aligned(name##_t *self, size_t m, size_t n, size_t alignment) { \ if (self == NULL) return false; \ \ if (m * n > (self->m * self->n)) { \ type *ptr = _aligned_realloc(self->values, sizeof(type) * m * n, alignment); \ if (ptr == NULL) { \ return false; \ } \ self->values = ptr; \ } \ \ self->m = m; \ self->n = n; \ \ return true; \ } \ \ static inline bool name##_resize_fill_zeros(name##_t *self, size_t m, size_t n) { \ size_t old_m = self->m; \ bool ret = name##_resize(self, m, n); \ if (ret && m > old_m) { \ memset(self->values + old_m, 0, (m - old_m) * self->n * sizeof(type)); \ } \ return ret; \ } \ \ static inline bool name##_resize_aligned_fill_zeros(name##_t *self, size_t m, size_t n, size_t alignment) { \ size_t old_m = self->m; \ bool ret = name##_resize_aligned(self, m, n, alignment); \ if (ret && m > old_m) { \ memset(self->values + old_m, 0, (m - old_m) * self->n * sizeof(type)); \ } \ return ret; \ } \ \ static inline name##_t *name##_new_copy(name##_t *self) { \ name##_t *cpy = name##_new(self->m, self->n); \ size_t num_values = self->m * self->n; \ memcpy(cpy->values, self->values, num_values * sizeof(type)); \ \ return cpy; \ } \ \ static inline bool name##_copy(name##_t *self, name##_t *other) { \ if (self->m != other->m || self->n != other->n) { \ return false; \ } \ size_t num_values = self->m * self->n; \ \ memcpy(other->values, self->values, num_values * sizeof(type)); \ return true; \ } \ \ static inline void name##_init_values(name##_t *self, type *values) { \ size_t num_values = self->m * self->n; \ memcpy(self->values, values, num_values * sizeof(type)); \ } \ \ static inline void name##_set(name##_t *self, type value) { \ array_type##_set(self->values, value, self->m * self->n); \ } \ \ static inline void name##_set_row(name##_t *self, size_t index, type *row) { \ size_t offset = index * self->n; \ type *values = self->values; \ size_t n = self->n; \ memcpy(values + offset, row, n * sizeof(type)); \ } \ \ static inline void name##_set_scalar(name##_t *self, size_t row_index, size_t col_index, type value) { \ size_t offset = row_index * self->n + col_index; \ self->values[offset] = value; \ } \ \ static inline void name##_add_scalar(name##_t *self, size_t row_index, size_t col_index, type value) { \ size_t offset = row_index * self->n + col_index; \ self->values[offset] += value; \ } \ \ static inline void name##_sub_scalar(name##_t *self, size_t row_index, size_t col_index, type value) { \ size_t offset = row_index * self->n + col_index; \ self->values[offset] -= value; \ } \ \ static inline void name##_mul_scalar(name##_t *self, size_t row_index, size_t col_index, type value) { \ size_t offset = row_index * self->n + col_index; \ self->values[offset] *= value; \ } \ \ static inline void name##_div_scalar(name##_t *self, size_t row_index, size_t col_index, type value) { \ size_t offset = row_index * self->n + col_index; \ self->values[offset] /= value; \ } \ \ static inline type name##_get(name##_t *self, size_t row_index, size_t col_index) { \ size_t index = row_index * self->n + col_index; \ return self->values[index]; \ } \ \ static inline type *name##_get_row(name##_t *self, size_t row_index) { \ size_t index = row_index * self->n; \ return self->values + index; \ } \ \ static inline name##_t *name##_new_value(size_t m, size_t n, type value) { \ name##_t *matrix = name##_new(m, n); \ name##_set(matrix, value); \ return matrix; \ } \ \ static inline name##_t *name##_new_zeros(size_t m, size_t n) { \ name##_t *matrix = name##_new(m, n); \ name##_zero(matrix); \ return matrix; \ } \ \ static inline name##_t *name##_new_ones(size_t m, size_t n) { \ return name##_new_value(m, n, (type)1); \ } \ \ static inline name##_t *name##_new_values(size_t m, size_t n, type *values) { \ name##_t *matrix = name##_new(m, n); \ memcpy(matrix->values, values, m * n * sizeof(type)); \ return matrix; \ } \ \ static inline void name##_div(name##_t *self, type value) { \ array_type##_div(self->values, value, self->m * self->n); \ } \ \ static inline bool name##_div_matrix(name##_t *self, name##_t *other) { \ if (self->m != other->m || self->n != other->n) return false; \ array_type##_div_array(self->values, other->values, self->m * self->n); \ return true; \ } \ \ static inline bool name##_div_matrix_times_scalar(name##_t *self, name##_t *other, type v) { \ if (self->m != other->m || self->n != other->n) return false; \ array_type##_div_array_times_scalar(self->values, other->values, v, self->m * self->n); \ return true; \ } \ \ static inline void name##_mul(name##_t *self, type value) { \ array_type##_mul(self->values, value, self->m * self->n); \ } \ \ static inline bool name##_mul_matrix(name##_t *self, name##_t *other) { \ if (self->m != other->m || self->n != other->n) return false; \ array_type##_mul_array(self->values, other->values, self->m * self->n); \ return true; \ } \ \ static inline bool name##_mul_matrix_times_scalar(name##_t *self, name##_t *other, type v) { \ if (self->m != other->m || self->n != other->n) return false; \ array_type##_mul_array_times_scalar(self->values, other->values, v, self->m * self->n); \ return true; \ } \ \ static inline void name##_add(name##_t *self, type value) { \ array_type##_add(self->values, self->m * self->n, value); \ } \ \ \ static inline bool name##_add_matrix(name##_t *self, name##_t *other) { \ if (self->m != other->m || self->n != other->n) return false; \ array_type##_add_array(self->values, other->values, self->m * self->n); \ return true; \ } \ \ static inline bool name##_add_matrix_times_scalar(name##_t *self, name##_t *other, type v) { \ if (self->m != other->m || self->n != other->n) return false; \ array_type##_add_array_times_scalar(self->values, other->values, v, self->m * self->n); \ return true; \ } \ \ static inline void name##_sub(name##_t *self, type value) { \ array_type##_sub(self->values, value, self->m * self->n); \ } \ \ static inline bool name##_sub_matrix(name##_t *self, name##_t *other) { \ if (self->m != other->m || self->n != other->n) return false; \ array_type##_sub_array(self->values, other->values, self->m * self->n); \ return true; \ } \ \ static inline bool name##_sub_matrix_times_scalar(name##_t *self, name##_t *other, type v) { \ if (self->m != other->m || self->n != other->n) return false; \ array_type##_sub_array_times_scalar(self->values, other->values, v, self->m * self->n); \ return true; \ } \ \ static name##_t *name##_read(FILE *f) { \ name##_t *mat = malloc(sizeof(name##_t)); \ if (mat == NULL) return NULL; \ \ mat->values = NULL; \ \ uint64_t m = 0; \ uint64_t n = 0; \ \ if (!file_read_uint64(f, &m) || \ !file_read_uint64(f, &n)) { \ goto exit_##name##_allocated; \ } \ \ mat->m = (size_t)m; \ mat->n = (size_t)n; \ \ size_t len_data = mat->m * mat->n; \ \ type *data = malloc(len_data * sizeof(type)); \ if (data == NULL) { \ log_error("error in data malloc\n"); \ goto exit_##name##_allocated; \ } \ \ if (!file_read_##array_type(f, data, len_data)) { \ free(data); \ goto exit_##name##_allocated; \ } \ \ mat->values = data; \ \ return mat; \ \ exit_##name##_allocated: \ name##_destroy(mat); \ return NULL; \ } \ \ static bool name##_write(name##_t *self, FILE *f) { \ if (self == NULL || self->values == NULL) { \ return false; \ } \ \ if (!file_write_uint64(f, (uint64_t)self->m) || \ !file_write_uint64(f, (uint64_t)self->n)) { \ return false; \ } \ \ uint64_t len_data = (uint64_t)self->m * (uint64_t)self->n; \ \ for (uint64_t i = 0; i < len_data; i++) { \ if (!file_write_##type_name(f, self->values[i])) { \ return false; \ } \ } \ \ return true; \ } #define MATRIX_INIT_FLOAT_BASE(name, type, type_name, array_type) \ MATRIX_INIT(name, type, type_name, array_type) \ \ static inline void name##_log(name##_t *self) { \ array_type##_log(self->values, self->m * self->n); \ } \ \ static inline void name##_exp(name##_t *self) { \ array_type##_exp(self->values, self->m * self->n); \ } \ \ static inline void name##_dot_vector(name##_t *self, type *vec, type *result) { \ type *values = self->values; \ size_t m = self->m; \ size_t n = self->n; \ for (size_t i = 0; i < m; i++) { \ for (size_t j = 0; j < n; j++) { \ result[i] += values[n * i + j] * vec[j]; \ } \ } \ } #ifdef HAVE_CBLAS #define MATRIX_INIT_FLOAT(name, type, type_name, array_type, blas_prefix) \ MATRIX_INIT_FLOAT_BASE(name, type, type_name, array_type) \ \ static inline bool name##_dot_matrix(name##_t *m1, name##_t *m2, name##_t *result) { \ if (m1->n != m2->m || m1->m != result->m || m2->n != result->n) { \ return false; \ } \ \ log_debug("doing CBLAS\n"); \ cblas_##blas_prefix##gemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, \ m1->m, m2->n, m1->n, 1.0, \ m1->values, m1->n, \ m2->values, m2->n, 0.0, \ result->values, result->n \ ); \ \ return true; \ } #else #define MATRIX_INIT_FLOAT(name, type, type_name, array_type, blas_prefix) \ MATRIX_INIT_FLOAT_BASE(name, type, type_name, array_type) \ \ static inline bool name##_dot_matrix(name##_t *m1, name##_t *m2, name##_t *result) { \ if (m1->n != m2->m || m1->m != result->m || m2->n != result->n) { \ return false; \ } \ \ size_t m1_rows = m1->m; \ size_t m1_cols = m1->n; \ size_t m2_rows = m2->m; \ size_t m2_cols = m2->n; \ \ type *m1_values = m1->values; \ type *m2_values = m2->values; \ type *result_values = result->values; \ \ for (size_t i = 0; i < m1_rows; i++) { \ for (size_t j = 0; j < m2_cols; j++) { \ size_t result_index = m2_cols * i + j; \ result_values[result_index] = 0.0; \ for (size_t k = 0; k < m2_rows; k++) { \ result_values[result_index] += m1_values[m1_cols * i + k] * m2_values[m2_cols * k + j]; \ } \ } \ } \ \ return true; \ } #endif MATRIX_INIT(uint32_matrix, uint32_t, uint32, uint32_array) MATRIX_INIT_FLOAT(float_matrix, float, float, float_array,s) MATRIX_INIT_FLOAT(double_matrix, double, double, double_array,d) #endif
{ "alphanum_fraction": 0.1637405245, "avg_line_length": 102.2449888641, "ext": "h", "hexsha": "d0f43a713846d325c565207a1d9fff4a9b6574d9", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "63036f35a9512d3e14f3fee43b7d0f8fe895460f", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "rinigus/deb-libpostal", "max_forks_repo_path": "src/matrix.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "63036f35a9512d3e14f3fee43b7d0f8fe895460f", "max_issues_repo_issues_event_max_datetime": "2021-12-13T20:22:28.000Z", "max_issues_repo_issues_event_min_datetime": "2021-03-25T22:59:06.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "rinigus/deb-libpostal", "max_issues_repo_path": "src/matrix.h", "max_line_length": 113, "max_stars_count": null, "max_stars_repo_head_hexsha": "63036f35a9512d3e14f3fee43b7d0f8fe895460f", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "rinigus/deb-libpostal", "max_stars_repo_path": "src/matrix.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4650, "size": 45908 }
#include <gsl/gsl_sf_bessel.h> #include <stdio.h> /** * The example program from the GSL documentation * http://www.gnu.org/software/gsl/doc/html/usage.html#an-example-program */ int main() { double x = 5.0; double y = gsl_sf_bessel_J0 (x); printf ("J0(%g) = %.18e\n", x, y); return 0; }
{ "alphanum_fraction": 0.6310679612, "avg_line_length": 20.6, "ext": "c", "hexsha": "f0b03b16cad40c9e76d921fb68abc7ef9c3a8982", "lang": "C", "max_forks_count": 1126, "max_forks_repo_forks_event_max_datetime": "2022-03-31T16:43:38.000Z", "max_forks_repo_forks_event_min_datetime": "2019-09-04T11:57:46.000Z", "max_forks_repo_head_hexsha": "d739adcec3e4dd4c250eff559ceb738e420673dd", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "rockandsalt/conan-center-index", "max_forks_repo_path": "recipes/gsl/all/test_package/test_package.c", "max_issues_count": 9799, "max_issues_repo_head_hexsha": "d739adcec3e4dd4c250eff559ceb738e420673dd", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:55:45.000Z", "max_issues_repo_issues_event_min_datetime": "2019-09-04T12:02:11.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "rockandsalt/conan-center-index", "max_issues_repo_path": "recipes/gsl/all/test_package/test_package.c", "max_line_length": 73, "max_stars_count": 562, "max_stars_repo_head_hexsha": "d739adcec3e4dd4c250eff559ceb738e420673dd", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "rockandsalt/conan-center-index", "max_stars_repo_path": "recipes/gsl/all/test_package/test_package.c", "max_stars_repo_stars_event_max_datetime": "2022-03-29T16:41:43.000Z", "max_stars_repo_stars_event_min_datetime": "2019-09-04T12:23:43.000Z", "num_tokens": 96, "size": 309 }
/* Copyright 2019, Alistair Boyle, 3-clause BSD License */ #include "config.h" #include <stdlib.h> /* malloc, free */ #include <assert.h> /* assert */ #include <stdio.h> /* printf */ #include <string.h> /* memset */ #include <float.h> /* DBL_MIN */ #include <lapacke.h> #include "matrix.h" #include "fwd.h" #include "inv.h" #ifdef UNIT_TESTING extern void * _mock_test_malloc(const size_t size, const char * file, const int line); extern void _test_free(void * const ptr, const char * file, const int line); #define malloc(size) _mock_test_malloc(size, __FILE__, __LINE__) #define free(ptr) _test_free(ptr, __FILE__, __LINE__) #endif #define SUCCESS 1 #define FAILURE 0 // #define DEBUG_SVD_MATRICES 1 #ifdef DEBUG_SVD_MATRICES static void set_matrix(matrix * X, char symbol[], char name[], char units[], int m, int n, double * x) { memset(X, 0, sizeof(matrix)); X->m = m; X->n = n; X->type = DENSE; X->symmetric = false; X->scale = 1.0; X->symbol = &(symbol[0]); X->name = &(name[0]); X->units = &(units[0]); X->x.dense = x; } #endif /* static int svd(matrix * J, matrix * U, matrix * sv, matrix * Vt) { assert(J != NULL); const int m = J->m; const int n = J->n; return m*n; } */ /* max/min: watch out for double evaluation of arguments e.g. a++ == a+=2 */ #define min(a,b) (((a) < (b)) ? (a) : (b) ) #define max(a,b) (((a) > (b)) ? (a) : (b) ) /* dense matrix indexing */ #define colmaj(i,j,ld) ((i) + (j)*(ld)) /* column major indexing */ /* solve Δx=(JᵀJ+λ²I)⁻¹Jb for b=b₂-b₁ * where J=UΣVᵀ (by the SVD) * and * Δx=VΣ⁺Uᵀb=VϕΣ⁻¹Uᵀb with Σ⁺=(Σ²+λ²I)⁻¹Σ or ϕₖ=σₖ²/(σₖ²+λ²) * for filter factor ϕ */ #define phi(s,hp) ((s*s)/((s*s)+(hp*hp))) static int inv_solve_svd(model * const mdl, double const * b, double * x) { int ret = FAILURE; assert(mdl != NULL); assert(b != NULL); assert(x != NULL); const int m = mdl->n_stimmeas; const int n = mdl->n_params[0]; /* init J */ // printf("J is %d x %d = %d --> %d B\n", m, n, m * n, m * n * (int) sizeof(double)); double * Ux = NULL, * sx = NULL, * Vtx = NULL, * superb = NULL; double * Jx = malloc(sizeof(double) * m * n); if(Jx == NULL) { printf("error: %s: out of memory\n", "jacobian"); return FAILURE; } if(!calc_jacobian(mdl, &Jx[0])) { printf("error: inv_solve/calc_jacobian failed\n"); free(Jx); return FAILURE; } #ifdef DEBUG_SVD_MATRICES matrix J; set_matrix(&J, "J", "Jacobian", "Vm/S", m, n, &Jx[0]); printf_matrix(&J); #endif /* calculate SVD of J; J is destroyed in the process */ /* SVD config */ const int layout = LAPACK_COL_MAJOR; /* A= m cols of U --> u; S= min(m,n) cols U --> u; O=min(m,n) cols U --> a (overwrite); 'N'=no U */ const char jobu = 'A'; const char jobvt = 'A'; const int ldJ = (layout == LAPACK_ROW_MAJOR) ? n : m; const int ldU = ((jobu == 'S') && (layout == LAPACK_ROW_MAJOR)) ? min(m, n) : m; const int ldVt = ((jobu == 'S') && (layout == LAPACK_COL_MAJOR)) ? min(m, n) : n; /* SVD outputs */ const int Usz = ((jobu == 'S') && (layout == LAPACK_COL_MAJOR)) ? ldU * min(m, n) : ldU * m; const int ssz = min(m, n); const int Vtsz = ((jobu == 'S') && (layout == LAPACK_COL_MAJOR)) ? ldVt * min(m, n) : ldVt * n; const int sbsz = min(m, n) - 1; Ux = malloc(sizeof(double) * Usz); sx = malloc(sizeof(double) * ssz); Vtx = malloc(sizeof(double) * Vtsz); superb = malloc(sizeof(double) * sbsz); assert(Ux != NULL); assert(sx != NULL); assert(Vtx != NULL); assert(superb != NULL); int info = LAPACKE_dgesvd(layout, jobu, jobvt, m, n, Jx, ldJ, sx, Ux, ldU, Vtx, ldVt, superb); //printf("LAPACKE_dgesvd info = %d\n", info); assert(info == 0); free(Jx); free(superb); #if DEBUG_SVD_MATRICES matrix U, s, Vt; set_matrix(&U, "U", "left singular vectors", NULL, m, Usz / ldU, &Ux[0]); set_matrix(&s, "Σ", "singular values", NULL, ssz, 1, &sx[0]); set_matrix(&Vt, "Vᵀ", "right singular vectors", NULL, n, Vtsz / ldVt, &Vtx[0]); printf_matrix(&U); printf_matrix(&s); printf_matrix(&Vt); #endif /* calculate Utb = Uᵀb */ double Utb[ssz]; memset(Utb, 0, sizeof(double)*ssz); for(int i = 0; i < m; i++) { /* i: b row = Uᵀ col = U row */ for(int j = 0; j < ssz; j++) { /* j: Uᵀb row = Uᵀ row = U col */ Utb[j] += Ux[colmaj(i, j, ldU)] * b[i]; } } #if DEBUG_SVD_MATRICES matrix Utbm; set_matrix(&Utbm, "Uᵀb", NULL, NULL, ssz, 1, &Utb[0]); printf_matrix(&Utbm); #endif /* calculate Utb = ϕΣ⁻¹(Uᵀb) */ const double hp = mdl->hp; for(int j = 0; j < ssz; j++) { Utb[j] = (phi(sx[j], hp) * Utb[j]) / (sx[j] + DBL_EPSILON); /* filtered Uᵀb */ } #ifdef DEBUG_SVD_MATRICES for(int j = 0; j < ssz; j++) { printf("ϕ[%d]=%8g Utb[%d]=%8g\n", j, phi(sx[j], hp), j, Utb[j]); } #endif /* complete the solution as Δx=V(ϕΣ⁻¹Uᵀb) */ memset(x, 0, sizeof(double) * n); for(int i = 0; i < ssz; i++) { /* i: Uᵀb row = V col = Vᵀ row */ const double Utbi = Utb[i]; for(int j = 0; j < n; j++) { /* j: x row = V row = Vᵀ col */ x[j] += Vtx[colmaj(i, j, ldVt)] * Utbi; } } #ifdef DEBUG_SVD_MATRICES matrix xm; set_matrix(&xm, "x", NULL, NULL, n, 1, &x[0]); printf_matrix(&xm); #endif free(Ux); free(sx); free(Vtx); ret = SUCCESS; return ret; } static int inv_solve_diff(model * const mdl, double const * b1, double const * b2, double * x) { assert(mdl != NULL); assert(b1 != NULL); assert(b2 != NULL); const int m = mdl->n_stimmeas; double b[m]; for(int i = 0; i < m; i++) { b[i] = b2[i] - b1[i]; } #ifdef DEBUG_SVD_MATRICES printf("b = "); for(int i = 0; i < m; i++) { printf(" %g", b[i]); } printf("\n"); #endif return inv_solve_svd(mdl, &b[0], x); } int inv_solve(model * const mdl, double * x) { assert(mdl != NULL); assert(x != NULL); const int m = mdl->n_stimmeas; const int n = mdl->n_params[0]; for(int frame_idx = 1; frame_idx < mdl->n_data[1]; frame_idx++) { int ret = inv_solve_diff(mdl, &(mdl->data[0]), &(mdl->data[frame_idx * m]), &x[(frame_idx - 1) * n]); if(!ret) { return FAILURE; } if(mdl->n_params[1] > 1) { break; } } // printf_model(mdl); return SUCCESS; }
{ "alphanum_fraction": 0.5367769219, "avg_line_length": 31.0845070423, "ext": "c", "hexsha": "3ac51f9b7f6924a9d9635cc248e4e7f9a86632ca", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "05a10333eda3b1569a9acd6e8b8fca245f9f012e", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "boyle/zedhat", "max_forks_repo_path": "src/inv.c", "max_issues_count": 2, "max_issues_repo_head_hexsha": "05a10333eda3b1569a9acd6e8b8fca245f9f012e", "max_issues_repo_issues_event_max_datetime": "2018-04-12T09:34:48.000Z", "max_issues_repo_issues_event_min_datetime": "2018-03-30T02:37:55.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "boyle/zedhat", "max_issues_repo_path": "src/inv.c", "max_line_length": 109, "max_stars_count": 2, "max_stars_repo_head_hexsha": "05a10333eda3b1569a9acd6e8b8fca245f9f012e", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "boyle/zedhat", "max_stars_repo_path": "src/inv.c", "max_stars_repo_stars_event_max_datetime": "2021-07-06T01:26:06.000Z", "max_stars_repo_stars_event_min_datetime": "2019-01-08T16:02:51.000Z", "num_tokens": 2298, "size": 6621 }
/* integration/qmomo.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007, 2009 Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_errno.h> static void initialise (double * ri, double * rj, double * rg, double * rh, double alpha, double beta); gsl_integration_qaws_table * gsl_integration_qaws_table_alloc (double alpha, double beta, int mu, int nu) { gsl_integration_qaws_table * t; if (alpha < -1.0) { GSL_ERROR_VAL ("alpha must be greater than -1.0", GSL_EINVAL, 0); } if (beta < -1.0) { GSL_ERROR_VAL ("beta must be greater than -1.0", GSL_EINVAL, 0); } if (mu != 0 && mu != 1) { GSL_ERROR_VAL ("mu must be 0 or 1", GSL_EINVAL, 0); } if (nu != 0 && nu != 1) { GSL_ERROR_VAL ("nu must be 0 or 1", GSL_EINVAL, 0); } t = (gsl_integration_qaws_table *) malloc(sizeof(gsl_integration_qaws_table)); if (t == 0) { GSL_ERROR_VAL ("failed to allocate space for qaws_table struct", GSL_ENOMEM, 0); } t->alpha = alpha; t->beta = beta; t->mu = mu; t->nu = nu; initialise (t->ri, t->rj, t->rg, t->rh, alpha, beta); return t; } int gsl_integration_qaws_table_set (gsl_integration_qaws_table * t, double alpha, double beta, int mu, int nu) { if (alpha < -1.0) { GSL_ERROR ("alpha must be greater than -1.0", GSL_EINVAL); } if (beta < -1.0) { GSL_ERROR ("beta must be greater than -1.0", GSL_EINVAL); } if (mu != 0 && mu != 1) { GSL_ERROR ("mu must be 0 or 1", GSL_EINVAL); } if (nu != 0 && nu != 1) { GSL_ERROR ("nu must be 0 or 1", GSL_EINVAL); } t->alpha = alpha; t->beta = beta; t->mu = mu; t->nu = nu; initialise (t->ri, t->rj, t->rg, t->rh, alpha, beta); return GSL_SUCCESS; } void gsl_integration_qaws_table_free (gsl_integration_qaws_table * t) { RETURN_IF_NULL (t); free (t); } static void initialise (double * ri, double * rj, double * rg, double * rh, double alpha, double beta) { const double alpha_p1 = alpha + 1.0; const double beta_p1 = beta + 1.0; const double alpha_p2 = alpha + 2.0; const double beta_p2 = beta + 2.0; const double r_alpha = pow (2.0, alpha_p1); const double r_beta = pow (2.0, beta_p1); size_t i; double an, anm1; ri[0] = r_alpha / alpha_p1; ri[1] = ri[0] * alpha / alpha_p2; an = 2.0; anm1 = 1.0; for (i = 2; i < 25; i++) { ri[i] = -(r_alpha + an * (an - alpha_p2) * ri[i - 1]) / (anm1 * (an + alpha_p1)); anm1 = an; an = an + 1.0; } rj[0] = r_beta / beta_p1; rj[1] = rj[0] * beta / beta_p2; an = 2.0; anm1 = 1.0; for (i = 2; i < 25; i++) { rj[i] = -(r_beta + an * (an - beta_p2) * rj[i - 1]) / (anm1 * (an + beta_p1)); anm1 = an; an = an + 1.0; } rg[0] = -ri[0] / alpha_p1; rg[1] = -rg[0] - 2.0 * r_alpha / (alpha_p2 * alpha_p2); an = 2.0; anm1 = 1.0; for (i = 2; i < 25; i++) { rg[i] = -(an * (an - alpha_p2) * rg[i - 1] - an * ri[i - 1] + anm1 * ri[i]) / (anm1 * (an + alpha_p1)); anm1 = an; an = an + 1.0; } rh[0] = -rj[0] / beta_p1; rh[1] = -rh[0] - 2.0 * r_beta / (beta_p2 * beta_p2); an = 2.0; anm1 = 1.0; for (i = 2; i < 25; i++) { rh[i] = -(an * (an - beta_p2) * rh[i - 1] - an * rj[i - 1] + anm1 * rj[i]) / (anm1 * (an + beta_p1)); anm1 = an; an = an + 1.0; } for (i = 1; i < 25; i += 2) { rj[i] *= -1; rh[i] *= -1; } }
{ "alphanum_fraction": 0.5526375885, "avg_line_length": 22.4564102564, "ext": "c", "hexsha": "f2573cdb1b5e016cf9519c58816a1a84126643ff", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/integration/qmomo.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/integration/qmomo.c", "max_line_length": 81, "max_stars_count": 14, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/integration/qmomo.c", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "num_tokens": 1560, "size": 4379 }
#pragma once #include <gsl.h> #include <mitkBaseData.h> namespace crimson { class QtPropertyStorage; /*! \brief A solver parameters data interface. */ class ISolverParametersData : public mitk::BaseData { public: mitkClassMacro(ISolverParametersData, BaseData); /*! * \brief Gets property storage for the SolverParametersData properties. */ virtual gsl::not_null<QtPropertyStorage*> getPropertyStorage() = 0; protected: ISolverParametersData() { mitk::BaseData::InitializeTimeGeometry(1); } virtual ~ISolverParametersData() {} ISolverParametersData(const Self&) = default; void SetRequestedRegion(const itk::DataObject*) override {} void SetRequestedRegionToLargestPossibleRegion() override {} bool RequestedRegionIsOutsideOfTheBufferedRegion() override { return true; } bool VerifyRequestedRegion() override { return true; } }; }
{ "alphanum_fraction": 0.7407407407, "avg_line_length": 26.2058823529, "ext": "h", "hexsha": "e0b6ff72e3cf5ce30aa4b90feebc123b892902f7", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-07-26T17:39:57.000Z", "max_forks_repo_forks_event_min_datetime": "2021-05-19T09:02:21.000Z", "max_forks_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "carthurs/CRIMSONGUI", "max_forks_repo_path": "Modules/SolverSetupService/include/ISolverParametersData.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "carthurs/CRIMSONGUI", "max_issues_repo_path": "Modules/SolverSetupService/include/ISolverParametersData.h", "max_line_length": 80, "max_stars_count": 10, "max_stars_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "carthurs/CRIMSONGUI", "max_stars_repo_path": "Modules/SolverSetupService/include/ISolverParametersData.h", "max_stars_repo_stars_event_max_datetime": "2022-02-23T02:52:38.000Z", "max_stars_repo_stars_event_min_datetime": "2020-09-17T18:55:31.000Z", "num_tokens": 204, "size": 891 }
/* * Copyright 2014 RWTH Aachen University. All rights reserved. * * Licensed under the RWTH LM License (the "License"); * you may not use this file except in compliance with the License. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <gsl/gsl_cblas.h> #include <cassert> #include <cstring> #include <cmath> #include <algorithm> #include <numeric> typedef double Real; inline void FastZero(const int size, float x[]) { std::fill(x, x + size, 0.0f); } inline void FastZero(const int size, double x[]) { std::fill(x, x + size, 0.0); } inline void FastCopy(const float source[], const int size, float destination[]) { memcpy(destination, source, size * sizeof(float)); } inline void FastCopy(const double source[], const int size, double destination[]) { memcpy(destination, source, size * sizeof(double)); } inline float FastMax(const float x[], const int size) { return *std::max_element(x, x + size); } inline double FastMax(const double x[], const int size) { return *std::max_element(x, x + size); } inline float FastComputeSum(const float x[], const int size) { return std::accumulate(x, x + size, 0.0f); } inline double FastComputeSum(const double x[], const int size) { return std::accumulate(x, x + size, 0.0); } inline void FastAddConstant(const float source[], const int size, const float value, float destination[]) { std::transform(source, source + size, destination, [value](const float x) { return x + value; }); } inline void FastAddConstant(const double source[], const int size, const double value, double destination[]) { std::transform(source, source + size, destination, [value](const double x) { return x + value; }); } inline void FastSubtractConstant(const float source[], const int size, const float value, float destination[]) { std::transform(source, source + size, destination, [value](const double x) { return x - value; }); } inline void FastSubtractConstant(const double source[], const int size, const double value, double destination[]) { std::transform(source, source + size, destination, [value](const double x) { return x - value; }); } inline void FastReverseSubtractConstant( const float source[], const int size, const float value, float destination[]) { std::transform(source, source + size, destination, [value](const float x) { return value - x; }); } inline void FastReverseSubtractConstant( const double source[], const int size, const double value, double destination[]) { std::transform(source, source + size, destination, [value](const double x) { return value - x; }); } inline void FastMultiplyByConstant(const float source[], const int size, const float value, float destination[]) { std::transform(source, source + size, destination, [value](const float x) { return value * x; }); } inline void FastMultiplyByConstant(const double source[], const int size, const double value, double destination[]) { std::transform(source, source + size, destination, [value](const double x) { return value * x; }); } inline void FastDivideByConstant(const float source[], const int size, const float value, float destination[]) { std::transform(source, source + size, destination, [value](const float x) { return x / value; }); } inline void FastDivideByConstant(const double source[], const int size, const double value, double destination[]) { std::transform(source, source + size, destination, [value](const double x) { return x / value; }); } inline void FastInvert(const float source[], const int size, float destination[]) { std::transform(source, source + size, destination, [](const double x) { return 1.0f / x; }); } inline void FastInvert(const double source[], const int size, double destination[]) { std::transform(source, source + size, destination, [](const double x) { return 1.0 / x; }); } inline void FastAdd(const float a[], const int size, const float b[], float c[]) { std::transform(a, a + size, b, c, [](const float x, const float y) { return x + y; }); } inline void FastAdd(const double a[], const int size, const double b[], double c[]) { std::transform(a, a + size, b, c, [](const double x, const double y) { return x + y; }); } inline void FastMultiplyByConstantAdd(const float alpha, const float a[], const int size, float b[]) { cblas_saxpy(size, alpha, a, 1, b, 1); } inline void FastMultiplyByConstantAdd(const double alpha, const double a[], const int size, double b[]) { cblas_daxpy(size, alpha, a, 1, b, 1); } inline void FastSub(const float a[], const int size, const float b[], float c[]) { std::transform(a, a + size, b, c, [](const float x, const float y) { return x - y; }); } inline void FastSub(const double a[], const int size, const double b[], double c[]) { std::transform(a, a + size, b, c, [](const double x, const double y) { return x - y; }); } inline void FastMultiply(const float a[], const int size, const float b[], float c[]) { std::transform(a, a + size, b, c, [](const float x, const float y) { return x * y; }); } inline void FastMultiply(const double a[], const int size, const double b[], double c[]) { std::transform(a, a + size, b, c, [](const double x, const double y) { return x * y; }); } inline void FastMultiplyAdd(const float a[], const int size, const float b[], float c[]) { for (int i = 0; i < size; ++i) c[i] += a[i] * b[i]; } inline void FastMultiplyAdd(const double a[], const int size, const double b[], double c[]) { for (int i = 0; i < size; ++i) c[i] += a[i] * b[i]; } inline void FastTanh(const float source[], const int size, float destination[]) { std::transform(source, source + size, destination, [](const float x) { return std::tanh(x); }); } inline void FastTanh(const double source[], const int size, double destination[]) { std::transform(source, source + size, destination, [](const double x) { return std::tanh(x); }); } inline void FastExponential(const float source[], const int size, float destination[]) { std::transform(source, source + size, destination, [](const float x) { return std::exp(x); }); } inline void FastExponential(const double source[], const int size, double destination[]) { std::transform(source, source + size, destination, [](const double x) { return std::exp(x); }); } inline void FastMatrixVectorMultiply(const float a[], const bool transpose_a, const int rows_a, const int columns_a, const float x[], float y[]) { cblas_sgemv(CblasColMajor, transpose_a ? CblasTrans : CblasNoTrans, rows_a, columns_a, 1.0f, a, rows_a, x, 1, 1.0f, y, 1); } inline void FastMatrixVectorMultiply(const double a[], const bool transpose_a, const int rows_a, const int columns_a, const double x[], double y[]) { cblas_dgemv(CblasColMajor, transpose_a ? CblasTrans : CblasNoTrans, rows_a, columns_a, 1.0, a, rows_a, x, 1, 1.0, y, 1); } inline void FastOuterProduct(const float alpha, const float x[], const int size_x, const float y[], const int size_y, float a[]) { cblas_sger(CblasColMajor, size_x, size_y, alpha, x, 1, y, 1, a, size_x); } inline void FastOuterProduct(const double alpha, const double x[], const int size_x, const double y[], const int size_y, double a[]) { cblas_dger(CblasColMajor, size_x, size_y, alpha, x, 1, y, 1, a, size_x); } inline void FastMatrixMatrixMultiply( const float alpha, const float a[], const bool transpose_a, const int rows_a, const int columns_a, const float b[], const bool transpose_b, const int columns_b, float c[]) { cblas_sgemm(CblasColMajor, transpose_a ? CblasTrans : CblasNoTrans, transpose_b ? CblasTrans : CblasNoTrans, rows_a, columns_b, columns_a, alpha, a, transpose_a ? columns_a : rows_a, b, transpose_b ? columns_b : columns_a, 1.0f, c, rows_a); } inline void FastMatrixMatrixMultiply( const double alpha, const double a[], const bool transpose_a, const int rows_a, // m const int columns_a, // k const double b[], const bool transpose_b, const int columns_b, // n double c[]) { cblas_dgemm(CblasColMajor, transpose_a ? CblasTrans : CblasNoTrans, transpose_b ? CblasTrans : CblasNoTrans, rows_a, // m columns_b, // n columns_a, // k alpha, a, transpose_a ? columns_a : rows_a, b, transpose_b ? columns_b : columns_a, 1.0, c, rows_a); } inline Real *FastMalloc(const int size) { Real *result = new Real[size]; assert(result != nullptr || size == 0); return result; } inline void FastFree(Real *x) { delete [] x; }
{ "alphanum_fraction": 0.4335554123, "avg_line_length": 31.1584821429, "ext": "h", "hexsha": "071ae714f20d6848b23998a5cceadfb2f26f5e35", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "28055937fc777cbba8cbc4c87ba5a2670da7d4e2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "darongliu/Input_Method", "max_forks_repo_path": "rwthlm/fast.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "28055937fc777cbba8cbc4c87ba5a2670da7d4e2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "darongliu/Input_Method", "max_issues_repo_path": "rwthlm/fast.h", "max_line_length": 76, "max_stars_count": 1, "max_stars_repo_head_hexsha": "28055937fc777cbba8cbc4c87ba5a2670da7d4e2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "darongliu/Input_Method", "max_stars_repo_path": "rwthlm/fast.h", "max_stars_repo_stars_event_max_datetime": "2018-07-03T07:42:42.000Z", "max_stars_repo_stars_event_min_datetime": "2018-07-03T07:42:42.000Z", "num_tokens": 2567, "size": 13959 }
#include <stdio.h> #include <math.h> #include <gsl/gsl_poly.h> #include <gsl/gsl_errno.h> #include <time.h> int main (int argc, char* argv[]) { /* Parse the command line arguments. */ const char* usage = "Usage: zeroes <xmin> <xmax> <ymin> <ymax> <xres> <coeff> ... <coeff> - <degree> ... <degree>\n"; if (argc < 8) { fprintf (stderr, "%s", usage); exit(EXIT_FAILURE); } /* The window in the plane. */ const double xmin = atof(argv[1]); const double xmax = atof(argv[2]); const double ymin = atof(argv[3]); const double ymax = atof(argv[4]); /* Image size, width is given, height is computed. */ const int xres = atoi(argv[5]); const int yres = (int)((xres * (ymax-ymin)) / (xmax-xmin)); /* The coefficients */ int ci_max = 0 ; while (6 + ci_max < argc && (argv[6+ci_max][0] != '-' || argv[6+ci_max][1] != 0)) { ci_max++; } if (ci_max == 0) { fprintf (stderr, "%s\nError: specify at least one coefficient.", usage) ; exit(EXIT_FAILURE); } double coeff[ci_max]; for (int ci = 0; ci < ci_max; ci++) { coeff[ci] = atof(argv[6+ci]); } /* The degrees */ const int di_max = argc - 7 - ci_max; if (di_max <= 0) { fprintf (stderr, "%s\nError: specify at least one degree.", usage) ; exit(EXIT_FAILURE); } int degree[di_max]; for (int di = 0; di < di_max; di++) { degree[di] = atoi(argv[7+ci_max+di]); } /* Allocate the image and initialize it */ unsigned int *image = (unsigned int *)calloc(sizeof(unsigned int), yres * xres) ; const unsigned int count_bound = 0xffffffff; unsigned int max_count = 0 ; /* Turn off the GSL error handler that aborts on error (some polynomials have tricky zeroes) */ gsl_set_error_handler_off (); /* We're going to skip zeroes whose imaginary part is almost zero. */ const double epsilon = 1.0e-20 ; time_t start = time(NULL); /* Run through degrees and compute the zeroes for each one. */ for (int di = 0; di < di_max; di++) { const int d = degree[di]; /* The degree we're working on. */ time_t now = time(NULL); fprintf (stderr, "Degree %d (%.2lf seconds)\n", d, difftime(now, start)); /* Initialize the polynomial. */ double poly[d+1]; for (int j = 0; j <= d; j++) { poly[j] = coeff[0]; } /* Initialize the counters. */ int counter[d+1]; for (int j = 0; j <= d; j++) { counter[j] = 0; } int j = 0; /* Allocate the workspace. */ gsl_poly_complex_workspace *w = gsl_poly_complex_workspace_alloc(d+1); do { /* Compute the zeroes if head coefficient is non-zero. */ if (poly[d] > epsilon || poly[d] < -epsilon) { double z[2*d]; /* the zeroes are stored here */ int status = gsl_poly_complex_solve (poly, d+1, w, z); /* Only use zeroes if GSL reported success */ if (status == 0) { /* Draw zeroes, skipping the real ones that are away from the origin */ for (int i=0; i < d; i++) { if (-epsilon < z[2*i+1] && z[2*i+1] < epsilon && (z[2*i] < -0.5 || z[2*i] > 0.5)) { continue; } int x = (int)((xres * (z[2*i] - xmin)) / (xmax - xmin)); int y = yres - (int)((yres * (z[2*i+1] - ymin)) / (ymax - ymin)); if (0 <= x && x < xres && 0 <= y && y < yres && image[xres * y + x] < count_bound) { int c = ++image[xres * y + x]; if (max_count < c) { max_count = c; } } } } } /* calculate the next polynomial */ for (j = 0; j <= d && counter[j] == ci_max-1; j++) { counter[j] = 0; poly[j] = coeff[0]; } if (j <= d) { counter[j]++; poly[j] = coeff[counter[j]]; } } while (j <= d); /* Deallocate workspace. */ gsl_poly_complex_workspace_free (w); } /* Output the computed result. */ /* ASCII header to the file*/ printf("P6\n# Zeroes, xmin=%lf, xmax=%lf, ymin=%lf, ymax=%lf, max_count=%d, coeffs=[", xmin, xmax, ymin, ymax, max_count); for (int ci=0; ci < ci_max; ci++) { printf("%lf%s", coeff[ci], (ci < ci_max-1 ? ", " : "],")); } printf("degrees = ["); for (int di=0; di < di_max; di++) { printf("%d%s", degree[di], (di < di_max-1 ? ", " : "],")); } printf("\n"); printf("%d\n%d\n%d\n", xres, yres, 0xffff); /* Image */ double r = 65535.0 / log((double)max_count) ; for (int y = 0; y < yres; y++) { for (int x = 0; x < xres; x++) { unsigned char color[6]; unsigned int k = (unsigned int)(r * log((float)image[xres * y + x])) ; color[0] = k >> 8; color[1] = k & 255; color[2] = k >> 8; color[3] = k & 255; color[4] = k >> 8; color[5] = k & 255; fwrite(color, 6, 1, stdout); } } free(image); return(0); }
{ "alphanum_fraction": 0.543989824, "avg_line_length": 36.8515625, "ext": "c", "hexsha": "042840bcad3dd105a8ea105d6b5ff035ec975370", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-04-28T03:30:42.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-25T19:33:40.000Z", "max_forks_repo_head_hexsha": "948f10bedcf38ac3aa63cdd1d629163f67c59d55", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "andrejbauer/zeroes", "max_forks_repo_path": "zeroes.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "948f10bedcf38ac3aa63cdd1d629163f67c59d55", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "andrejbauer/zeroes", "max_issues_repo_path": "zeroes.c", "max_line_length": 124, "max_stars_count": 7, "max_stars_repo_head_hexsha": "948f10bedcf38ac3aa63cdd1d629163f67c59d55", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "andrejbauer/zeroes", "max_stars_repo_path": "zeroes.c", "max_stars_repo_stars_event_max_datetime": "2021-12-24T09:13:58.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-01T18:23:04.000Z", "num_tokens": 1491, "size": 4717 }
#include <math.h> #include <gsl/gsl_sf_gamma.h> #include <galpy_potentials.h> #ifndef M_PI #define M_PI 3.14159265358979323846 #endif //PowerSphericalPotentialwCutoff //3 arguments: amp, alpha, rc double mass(double r2,double alpha, double rc){ return 2. * M_PI * pow ( rc , 3. - alpha ) * ( gsl_sf_gamma ( 1.5 - 0.5 * alpha ) - gsl_sf_gamma_inc ( 1.5 - 0.5 * alpha , r2 / rc / rc ) ); } double PowerSphericalPotentialwCutoffEval(double R,double Z, double phi, double t, struct potentialArg * potentialArgs){ double * args= potentialArgs->args; //Get args double amp= *args++; double alpha= *args++; double rc= *args; //Radius double r2= R*R+Z*Z; double r= sqrt(r2); return amp * 2. * M_PI * pow(rc,3.-alpha) / r * ( r / rc * ( gsl_sf_gamma ( 1. - 0.5 * alpha ) - gsl_sf_gamma_inc ( 1. - 0.5 * alpha , r2 / rc / rc ) ) - ( gsl_sf_gamma ( 1.5 - 0.5 * alpha ) - gsl_sf_gamma_inc ( 1.5 - 0.5 * alpha , r2 / rc / rc) ) ); } double PowerSphericalPotentialwCutoffRforce(double R,double Z, double phi, double t, struct potentialArg * potentialArgs){ double * args= potentialArgs->args; //Get args double amp= *args++; double alpha= *args++; double rc= *args; //Radius double r2= R*R+Z*Z; //Calculate Rforce return - amp * mass (r2,alpha,rc) * R / pow(r2,1.5); } double PowerSphericalPotentialwCutoffPlanarRforce(double R,double phi, double t, struct potentialArg * potentialArgs){ double * args= potentialArgs->args; //Get args double amp= *args++; double alpha= *args++; double rc= *args; //Radius double r2= R*R; //Calculate Rforce return - amp * mass (r2,alpha,rc) / r2; } double PowerSphericalPotentialwCutoffzforce(double R,double Z,double phi, double t, struct potentialArg * potentialArgs){ double * args= potentialArgs->args; //Get args double amp= *args++; double alpha= *args++; double rc= *args; //Radius double r2= R*R+Z*Z; //Calculate Rforce return - amp * mass (r2,alpha,rc) * Z / pow(r2,1.5); } double PowerSphericalPotentialwCutoffPlanarR2deriv(double R,double phi, double t, struct potentialArg * potentialArgs){ double * args= potentialArgs->args; //Get args double amp= *args++; double alpha= *args++; double rc= *args; //Radius double r2= R*R; //Calculate R2deriv return amp * ( 4. * M_PI * pow(r2,- 0.5 * alpha) * exp(-r2/rc/rc) - 2. * mass(r2,alpha,rc)/pow(r2,1.5) ); }
{ "alphanum_fraction": 0.6413484972, "avg_line_length": 31.974025974, "ext": "c", "hexsha": "bde397ba7c46536f49201f62750d49f9567aefe6", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-07-30T06:14:31.000Z", "max_forks_repo_forks_event_min_datetime": "2020-07-30T06:14:31.000Z", "max_forks_repo_head_hexsha": "cabb42bef3b4f88a2f593cdb123452cd41451db3", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "BurcuAkbulut/galpy", "max_forks_repo_path": "galpy/potential/potential_c_ext/PowerSphericalPotentialwCutoff.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "cabb42bef3b4f88a2f593cdb123452cd41451db3", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "BurcuAkbulut/galpy", "max_issues_repo_path": "galpy/potential/potential_c_ext/PowerSphericalPotentialwCutoff.c", "max_line_length": 252, "max_stars_count": 1, "max_stars_repo_head_hexsha": "7132eddbf2dab491fe137790e31eacdc604b0534", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "turnergarrow/galpy", "max_stars_repo_path": "galpy/potential/potential_c_ext/PowerSphericalPotentialwCutoff.c", "max_stars_repo_stars_event_max_datetime": "2019-02-28T08:54:38.000Z", "max_stars_repo_stars_event_min_datetime": "2019-02-28T08:54:38.000Z", "num_tokens": 804, "size": 2462 }
/*****************************************************************\ __ / / / / __ __ / /______ _______ / / / / ________ __ __ / ______ \ /_____ \ / / / / / _____ | / / / / / / | / _______| / / / / / / /____/ / / / / / / / / / / _____ / / / / / / _______/ / / / / / / / / / /____/ / / / / / / |______ / |______/ / /_/ /_/ |________/ / / / / \_______/ \_______ / /_/ /_/ / / / / High Level Game Framework /_/ --------------------------------------------------------------- Copyright (c) 2007-2011 - Rodrigo Braz Monteiro. This file is subject to the terms of halley_license.txt. \*****************************************************************/ #pragma once #include <algorithm> #include <limits> #include <list> #include <cmath> #include <memory> #include <array> #include <functional> #include <halley/data_structures/vector.h> #include <gsl/gsl_assert> #ifdef _MSC_VER #include <xmmintrin.h> #endif namespace Halley { // General aliases using Byte = unsigned char; using Bytes = Vector<Byte>; template <typename T> constexpr inline T clamp(T value, T minValue, T maxValue) { return std::min(std::max(minValue, value), maxValue); } template <typename T> constexpr inline T clamp2(T value, T minValue, T maxValue) { return std::max(minValue, std::min(value, maxValue)); } template <typename T> constexpr inline T maxAbs(T a, T b) { return abs(a) > abs(b) ? a : b; } template <typename T> constexpr inline T minAbs(T a, T b) { return abs(a) < abs(b) ? a : b; } template <typename T> constexpr inline bool rangeIntersection(T s1, T e1, T s2, T e2) { return (s1 < e2) && (s2 < e1); } constexpr double pi() { return 3.1415926535897932384626433832795; } // Endianness conversion //const bool IS_BIG_ENDIAN = *((short*)"AB") == 0x4243; constexpr bool IS_BIG_ENDIAN = false; template <typename T> constexpr inline T FixEndian(T t) { if (IS_BIG_ENDIAN) { T temp = t; unsigned char *v = reinterpret_cast<unsigned char*>(&temp); for (size_t i=0; i<sizeof(T)/2; i++) { std::swap(v[i], v[sizeof(T)-1-i]); } return temp; } else { return t; } } template<> constexpr inline char FixEndian<char>(char t) { return t; } template<> constexpr inline unsigned char FixEndian<unsigned char>(unsigned char t) { return t; } // True modulo definition template <typename T> constexpr inline T modulo (T a, T b) { static_assert(std::is_signed<T>::value, "Must be signed to use modulo operation"); T res = a % b; if (res < 0) res = b+res; return res; } template <typename T> constexpr inline T floatModulo (T a, T b) { if (b == 0) return a; return a - b * std::floor(a/b); } template <> constexpr inline float modulo (float a, float b) { return floatModulo(a, b); } template <> constexpr inline double modulo (double a, double b) { return floatModulo(a, b); } // Float floor division (e.g. -0.5 / 2 = -1.0) template <typename T> constexpr inline T floorDivFloat (T a, T b) { return floor(a / b); } // Int floor division (e.g. -2 / 3 = -1) template <typename T> constexpr inline T floorDivInt (T a, T b) { T result = a / b; if (a % b < 0) { --result; } return result; } // Generic floor divs constexpr inline float floorDiv (float a, float b) { return floorDivFloat(a, b); } constexpr inline double floorDiv (double a, double b) { return floorDivFloat(a, b); } constexpr inline long floorDiv (long a, long b) { return floorDivInt(a, b); } constexpr inline int floorDiv (int a, int b) { return floorDivInt(a, b); } constexpr inline short floorDiv (short a, short b) { return floorDivInt(a, b); } constexpr inline char floorDiv (char a, char b) { return floorDivInt(a, b); } // Interpolation template <typename T> constexpr inline T interpolate(T a, T b, float factor) { return static_cast<T>(a * (1 - factor) + b * factor); } template <typename T> constexpr inline T lerp(T a, T b, float factor) { return static_cast<T>(a * (1 - factor) + b * factor); } // Smoothing template <typename T> constexpr inline T smoothCos(T a) { return T((1-cos(a * 3.1415926535897932384626433832795))*0.5); } // ASR (attack-sustain-release) envelope // Returns 0 at start of attack and end of release, 1 during sustain // Attack and release are linear interpolations template <typename T> constexpr inline T asr(T x, T a, T s, T r) { if (x < a) return x/a; T as = a+s; if (x < as) return 1; return 1 - ((x-as)/r); } // Next power of 2 template<typename T> constexpr static T nextPowerOf2(T val) { --val; val = (val >> 1) | val; val = (val >> 2) | val; val = (val >> 4) | val; val = (val >> 8) | val; val = (val >> 16) | val; return val+1; } constexpr inline int fastLog2Floor (uint32_t value) { // From https://stackoverflow.com/questions/11376288/fast-computing-of-log2-for-64-bit-integers constexpr int tab32[32] = { 0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30, 8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31 }; Expects(value > 0); value |= value >> 1; value |= value >> 2; value |= value >> 4; value |= value >> 8; value |= value >> 16; return tab32[uint32_t(value * 0x07C4ACDD) >> 27]; } constexpr inline int fastLog2Floor (uint64_t value) { // From https://stackoverflow.com/questions/11376288/fast-computing-of-log2-for-64-bit-integers constexpr int tab64[64] = { 63, 0, 58, 1, 59, 47, 53, 2, 60, 39, 48, 27, 54, 33, 42, 3, 61, 51, 37, 40, 49, 18, 28, 20, 55, 30, 34, 11, 43, 14, 22, 4, 62, 57, 46, 52, 38, 26, 32, 41, 50, 36, 17, 19, 29, 10, 13, 21, 56, 45, 25, 31, 35, 16, 9, 12, 44, 24, 15, 8, 23, 7, 6, 5}; Expects(value > 0); value |= value >> 1; value |= value >> 2; value |= value >> 4; value |= value >> 8; value |= value >> 16; value |= value >> 32; return tab64[uint64_t((value - (value >> 1)) * 0x07EDD5E59A4E28C2) >> 58]; } constexpr inline int fastLog2Ceil (uint32_t value) { return fastLog2Floor(value - 1) + 1; } constexpr inline int fastLog2Ceil (uint64_t value) { return fastLog2Floor(value - 1) + 1; } // Advance a to b by up to inc template<typename T> constexpr static T advance(T a, T b, T inc) { if (a < b) return std::min(a+inc, b); else return std::max(a-inc, b); } // Align address template <typename T> constexpr T alignUp(T val, T align) { return val + (align - (val % align)) % align; } template <typename T> constexpr T alignDown(T val, T align) { return (val / align) * align; } // Prefetch data from memory static inline void prefetchL1(void* p) { #ifdef _MSC_VER _mm_prefetch(static_cast<const char*>(p), _MM_HINT_T0); #else __builtin_prefetch(p); #endif } static inline void prefetchL2(void* p) { #ifdef _MSC_VER _mm_prefetch(static_cast<const char*>(p), _MM_HINT_T1); #else __builtin_prefetch(p); #endif } }
{ "alphanum_fraction": 0.5926867147, "avg_line_length": 26.3308550186, "ext": "h", "hexsha": "bbc7727e05b02b031d640bfb8a7925ec67e1a655", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "aa58e1abe22cda9e80637922721c03574779cd81", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Healthire/halley", "max_forks_repo_path": "src/engine/utils/include/halley/utils/utils.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "aa58e1abe22cda9e80637922721c03574779cd81", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Healthire/halley", "max_issues_repo_path": "src/engine/utils/include/halley/utils/utils.h", "max_line_length": 287, "max_stars_count": null, "max_stars_repo_head_hexsha": "aa58e1abe22cda9e80637922721c03574779cd81", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "Healthire/halley", "max_stars_repo_path": "src/engine/utils/include/halley/utils/utils.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2321, "size": 7083 }
/* vector/gsl_vector_complex_double.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSL_VECTOR_COMPLEX_DOUBLE_H__ #define __GSL_VECTOR_COMPLEX_DOUBLE_H__ #if !defined( GSL_FUN ) # if !defined( GSL_DLL ) # define GSL_FUN extern # elif defined( BUILD_GSL_DLL ) # define GSL_FUN extern __declspec(dllexport) # else # define GSL_FUN extern __declspec(dllimport) # endif #endif #include <stdlib.h> #include <gsl/gsl_types.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_check_range.h> #include <gsl/gsl_vector_double.h> #include <gsl/gsl_vector_complex.h> #include <gsl/gsl_block_complex_double.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS typedef struct { size_t size; size_t stride; double *data; gsl_block_complex *block; int owner; } gsl_vector_complex; typedef struct { gsl_vector_complex vector; } _gsl_vector_complex_view; typedef _gsl_vector_complex_view gsl_vector_complex_view; typedef struct { gsl_vector_complex vector; } _gsl_vector_complex_const_view; typedef const _gsl_vector_complex_const_view gsl_vector_complex_const_view; /* Allocation */ GSL_FUN gsl_vector_complex *gsl_vector_complex_alloc (const size_t n); GSL_FUN gsl_vector_complex *gsl_vector_complex_calloc (const size_t n); GSL_FUN gsl_vector_complex * gsl_vector_complex_alloc_from_block (gsl_block_complex * b, const size_t offset, const size_t n, const size_t stride); GSL_FUN gsl_vector_complex * gsl_vector_complex_alloc_from_vector (gsl_vector_complex * v, const size_t offset, const size_t n, const size_t stride); GSL_FUN void gsl_vector_complex_free (gsl_vector_complex * v); /* Views */ GSL_FUN _gsl_vector_complex_view gsl_vector_complex_view_array (double *base, size_t n); GSL_FUN _gsl_vector_complex_view gsl_vector_complex_view_array_with_stride (double *base, size_t stride, size_t n); GSL_FUN _gsl_vector_complex_const_view gsl_vector_complex_const_view_array (const double *base, size_t n); GSL_FUN _gsl_vector_complex_const_view gsl_vector_complex_const_view_array_with_stride (const double *base, size_t stride, size_t n); GSL_FUN _gsl_vector_complex_view gsl_vector_complex_subvector (gsl_vector_complex *base, size_t i, size_t n); GSL_FUN _gsl_vector_complex_view gsl_vector_complex_subvector_with_stride (gsl_vector_complex *v, size_t i, size_t stride, size_t n); GSL_FUN _gsl_vector_complex_const_view gsl_vector_complex_const_subvector (const gsl_vector_complex *base, size_t i, size_t n); GSL_FUN _gsl_vector_complex_const_view gsl_vector_complex_const_subvector_with_stride (const gsl_vector_complex *v, size_t i, size_t stride, size_t n); GSL_FUN _gsl_vector_view gsl_vector_complex_real (gsl_vector_complex *v); GSL_FUN _gsl_vector_view gsl_vector_complex_imag (gsl_vector_complex *v); GSL_FUN _gsl_vector_const_view gsl_vector_complex_const_real (const gsl_vector_complex *v); GSL_FUN _gsl_vector_const_view gsl_vector_complex_const_imag (const gsl_vector_complex *v); /* Operations */ GSL_FUN void gsl_vector_complex_set_zero (gsl_vector_complex * v); GSL_FUN void gsl_vector_complex_set_all (gsl_vector_complex * v, gsl_complex z); GSL_FUN int gsl_vector_complex_set_basis (gsl_vector_complex * v, size_t i); GSL_FUN int gsl_vector_complex_fread (FILE * stream, gsl_vector_complex * v); GSL_FUN int gsl_vector_complex_fwrite (FILE * stream, const gsl_vector_complex * v); GSL_FUN int gsl_vector_complex_fscanf (FILE * stream, gsl_vector_complex * v); GSL_FUN int gsl_vector_complex_fprintf (FILE * stream, const gsl_vector_complex * v, const char *format); GSL_FUN int gsl_vector_complex_memcpy (gsl_vector_complex * dest, const gsl_vector_complex * src); GSL_FUN int gsl_vector_complex_reverse (gsl_vector_complex * v); GSL_FUN int gsl_vector_complex_swap (gsl_vector_complex * v, gsl_vector_complex * w); GSL_FUN int gsl_vector_complex_swap_elements (gsl_vector_complex * v, const size_t i, const size_t j); GSL_FUN int gsl_vector_complex_isnull (const gsl_vector_complex * v); GSL_FUN int gsl_vector_complex_ispos (const gsl_vector_complex * v); GSL_FUN int gsl_vector_complex_isneg (const gsl_vector_complex * v); GSL_FUN int gsl_vector_complex_isnonneg (const gsl_vector_complex * v); GSL_FUN int gsl_vector_complex_add (gsl_vector_complex * a, const gsl_vector_complex * b); GSL_FUN int gsl_vector_complex_sub (gsl_vector_complex * a, const gsl_vector_complex * b); GSL_FUN int gsl_vector_complex_mul (gsl_vector_complex * a, const gsl_vector_complex * b); GSL_FUN int gsl_vector_complex_div (gsl_vector_complex * a, const gsl_vector_complex * b); GSL_FUN int gsl_vector_complex_scale (gsl_vector_complex * a, const gsl_complex x); GSL_FUN int gsl_vector_complex_add_constant (gsl_vector_complex * a, const gsl_complex x); GSL_FUN INLINE_DECL gsl_complex gsl_vector_complex_get (const gsl_vector_complex * v, const size_t i); GSL_FUN INLINE_DECL void gsl_vector_complex_set (gsl_vector_complex * v, const size_t i, gsl_complex z); GSL_FUN INLINE_DECL gsl_complex *gsl_vector_complex_ptr (gsl_vector_complex * v, const size_t i); GSL_FUN INLINE_DECL const gsl_complex *gsl_vector_complex_const_ptr (const gsl_vector_complex * v, const size_t i); #ifdef HAVE_INLINE INLINE_FUN gsl_complex gsl_vector_complex_get (const gsl_vector_complex * v, const size_t i) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(i >= v->size)) { gsl_complex zero = {{0, 0}}; GSL_ERROR_VAL ("index out of range", GSL_EINVAL, zero); } #endif return *GSL_COMPLEX_AT (v, i); } INLINE_FUN void gsl_vector_complex_set (gsl_vector_complex * v, const size_t i, gsl_complex z) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(i >= v->size)) { GSL_ERROR_VOID ("index out of range", GSL_EINVAL); } #endif *GSL_COMPLEX_AT (v, i) = z; } INLINE_FUN gsl_complex * gsl_vector_complex_ptr (gsl_vector_complex * v, const size_t i) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(i >= v->size)) { GSL_ERROR_NULL ("index out of range", GSL_EINVAL); } #endif return GSL_COMPLEX_AT (v, i); } INLINE_FUN const gsl_complex * gsl_vector_complex_const_ptr (const gsl_vector_complex * v, const size_t i) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(i >= v->size)) { GSL_ERROR_NULL ("index out of range", GSL_EINVAL); } #endif return GSL_COMPLEX_AT (v, i); } #endif /* HAVE_INLINE */ __END_DECLS #endif /* __GSL_VECTOR_COMPLEX_DOUBLE_H__ */
{ "alphanum_fraction": 0.6468882445, "avg_line_length": 34.6177606178, "ext": "h", "hexsha": "8d9274b9ae11fa22794849accec0ea1a6b180ac3", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "berkus/music-cs", "max_forks_repo_path": "deps/include/gsl/gsl_vector_complex_double.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "berkus/music-cs", "max_issues_repo_path": "deps/include/gsl/gsl_vector_complex_double.h", "max_line_length": 116, "max_stars_count": null, "max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "berkus/music-cs", "max_stars_repo_path": "deps/include/gsl/gsl_vector_complex_double.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1950, "size": 8966 }
#pragma once #define VULKAN_H_ 1 #include <vulkan/vk_platform.h> #include <vulkan/vulkan_core.h> #if defined(VK_USE_PLATFORM_WIN32_KHR) // This is to avoid including Windows.h #ifndef DECLARE_HANDLE using HANDLE = void*; #define DECLARE_HANDLE(name) struct name##__; typedef struct name##__ *name DECLARE_HANDLE(HINSTANCE); DECLARE_HANDLE(HMONITOR); DECLARE_HANDLE(HWND); #undef DECLARE_HANDLE struct _SECURITY_ATTRIBUTES; using SECURITY_ATTRIBUTES = _SECURITY_ATTRIBUTES; using LPCWSTR = const wchar_t*; using PCWSTR = const wchar_t*; using DWORD = unsigned long; // NOLINT(google-runtime-int) #endif // ReSharper disable once CppUnusedIncludeDirective #include <vulkan/vulkan_win32.h> #endif #if defined(VK_USE_PLATFORM_XCB_KHR) typedef struct xcb_connection_t xcb_connection_t; typedef uint32_t xcb_window_t; typedef uint32_t xcb_visualid_t; // ReSharper disable once CppUnusedIncludeDirective #include <vulkan/vulkan_xcb.h> #endif #if defined(VK_USE_PLATFORM_XLIB_KHR) typedef struct _XDisplay Display; typedef unsigned long XID; typedef XID Window; typedef unsigned long VisualID; // ReSharper disable once CppUnusedIncludeDirective #include <vulkan/vulkan_xlib.h> #endif #if defined(VK_USE_PLATFORM_XLIB_XRANDR_EXT) typedef struct _XDisplay Display; typedef unsigned long XID; typedef XID Window; typedef unsigned long VisualID; typedef XID RROutput; // ReSharper disable once CppUnusedIncludeDirective #include <vulkan/vulkan_xlib_xrandr.h> #endif #include "Config.h" #include <vulkan/vk_icd.h> #include <gsl/gsl> #if !defined(_MSC_VER) #define __debugbreak() __asm__("int3") inline void strcpy_s(char* destination, const char* source) { strcpy(destination, source); } #endif #define TODO_ERROR() if (1) { __debugbreak(); abort(); } else (void)0 #define FATAL_ERROR() if (1) { __debugbreak(); abort(); } else (void)0 #if defined(_MSC_VER) #define CP_DLL_EXPORT __declspec(dllexport) #else #define CP_DLL_EXPORT #endif #pragma warning(push) #pragma warning(disable: 26490 26474 26408 26409) struct DeviceMemory; class Buffer; class BufferView; class CommandBuffer; class CommandPool; class CompiledShaderModule; class ComputePipeline; class DescriptorPool; class DescriptorSet; class DescriptorSetLayout; class Device; class Event; class Fence; class Framebuffer; class GraphicsPipeline; class Image; class ImageView; class Instance; class PhysicalDevice; class Pipeline; class PipelineCache; class PipelineLayout; class QueryPool; class Queue; class RenderPass; class Sampler; class Semaphore; class ShaderModule; #if defined(VK_NV_ray_tracing) class RayTracingPipeline; #endif template<typename LocalType> struct VulkanTypeHelper; #define VK_TYPE_HELPER(VulkanType, LocalType, NonDispatchable) template<> struct VulkanTypeHelper<LocalType> { static constexpr auto IsNonDispatchable = NonDispatchable; using Type = VulkanType; } VK_TYPE_HELPER(VkInstance, Instance, false); VK_TYPE_HELPER(VkPhysicalDevice, PhysicalDevice, false); VK_TYPE_HELPER(VkDevice, Device, false); VK_TYPE_HELPER(VkQueue, Queue, false); VK_TYPE_HELPER(VkSemaphore, Semaphore, true); VK_TYPE_HELPER(VkCommandBuffer, CommandBuffer, false); VK_TYPE_HELPER(VkFence, Fence, true); VK_TYPE_HELPER(VkDeviceMemory, DeviceMemory, true); VK_TYPE_HELPER(VkBuffer, Buffer, true); VK_TYPE_HELPER(VkImage, Image, true); VK_TYPE_HELPER(VkEvent, Event, true); VK_TYPE_HELPER(VkQueryPool, QueryPool, true); VK_TYPE_HELPER(VkBufferView, BufferView, true); VK_TYPE_HELPER(VkImageView, ImageView, true); VK_TYPE_HELPER(VkShaderModule, ShaderModule, true); VK_TYPE_HELPER(VkPipelineCache, PipelineCache, true); VK_TYPE_HELPER(VkPipelineLayout, PipelineLayout, true); VK_TYPE_HELPER(VkRenderPass, RenderPass, true); VK_TYPE_HELPER(VkPipeline, Pipeline, true); VK_TYPE_HELPER(VkPipeline, ComputePipeline, true); VK_TYPE_HELPER(VkPipeline, GraphicsPipeline, true); #if defined(VK_NV_ray_tracing) VK_TYPE_HELPER(VkPipeline, RayTracingPipeline, true); #endif VK_TYPE_HELPER(VkDescriptorSetLayout, DescriptorSetLayout, true); VK_TYPE_HELPER(VkSampler, Sampler, true); VK_TYPE_HELPER(VkDescriptorPool, DescriptorPool, true); VK_TYPE_HELPER(VkDescriptorSet, DescriptorSet, true); VK_TYPE_HELPER(VkFramebuffer, Framebuffer, true); VK_TYPE_HELPER(VkCommandPool, CommandPool, true); #if defined(VK_VERSION_1_1) class DescriptorUpdateTemplate; class SamplerYcbcrConversion; VK_TYPE_HELPER(VkSamplerYcbcrConversion, SamplerYcbcrConversion, true); VK_TYPE_HELPER(VkDescriptorUpdateTemplate, DescriptorUpdateTemplate, true); #endif #if defined(VK_KHR_surface) VK_TYPE_HELPER(VkSurfaceKHR, VkIcdSurfaceBase, true); #if defined(VK_USE_PLATFORM_WIN32_KHR) VK_TYPE_HELPER(VkSurfaceKHR, VkIcdSurfaceWin32, true); #endif #if defined(VK_USE_PLATFORM_XCB_KHR) VK_TYPE_HELPER(VkSurfaceKHR, VkIcdSurfaceXcb, true); #endif #if defined(VK_USE_PLATFORM_XLIB_KHR) VK_TYPE_HELPER(VkSurfaceKHR, VkIcdSurfaceXlib, true); #endif #endif #if defined(VK_KHR_swapchain) class Swapchain; VK_TYPE_HELPER(VkSwapchainKHR, Swapchain, true); #endif #if defined(VK_KHR_display) class VDisplay; class DisplayMode; VK_TYPE_HELPER(VkDisplayKHR, VDisplay, true); VK_TYPE_HELPER(VkDisplayModeKHR, DisplayMode, true); #endif #if defined(VK_EXT_debug_report) class DebugReportCallback; VK_TYPE_HELPER(VkDebugReportCallbackEXT, DebugReportCallback, true); #endif #if defined(VK_NVX_device_generated_commands) class IndirectCommandsLayout; class ObjectTable; VK_TYPE_HELPER(VkObjectTableNVX, ObjectTable, true); VK_TYPE_HELPER(VkIndirectCommandsLayoutNVX, IndirectCommandsLayout, true); #endif #if defined(VK_EXT_debug_utils) class DebugUtilsMessenger; VK_TYPE_HELPER(VkDebugUtilsMessengerEXT, DebugUtilsMessenger, true); #endif #if defined(VK_EXT_validation_cache) class ValidationCache; VK_TYPE_HELPER(VkValidationCacheEXT, ValidationCache, true); #endif #if defined(VK_NV_ray_tracing) class AccelerationStructure; VK_TYPE_HELPER(VkAccelerationStructureNV, AccelerationStructure, true); #endif #if defined(VK_INTEL_performance_query) class PerformanceConfiguration; VK_TYPE_HELPER(VkPerformanceConfigurationINTEL, PerformanceConfiguration, true); #endif #undef VK_TYPE_HELPER template<typename T, class... Types> T* Allocate(const VkAllocationCallbacks* pAllocator, VkSystemAllocationScope allocationScope, Types&& ... args) { constexpr auto size = VulkanTypeHelper<T>::IsNonDispatchable ? sizeof(T) : sizeof(T) + 16; const auto data = pAllocator ? static_cast<uint8_t*>(pAllocator->pfnAllocation(pAllocator->pUserData, size, 16, allocationScope)) : static_cast<uint8_t*>(malloc(size)); if (!data) { return nullptr; } if (VulkanTypeHelper<T>::IsNonDispatchable) { return new(data) T(std::forward<Types>(args)...); } *static_cast<uintptr_t*>(static_cast<void*>(data)) = ICD_LOADER_MAGIC; return new(data + 16) T(std::forward<Types>(args)...); } template<typename T> void Free(T* value, const VkAllocationCallbacks* pAllocator) noexcept { value->OnDelete(pAllocator); value->~T(); const auto data = static_cast<uint8_t*>(static_cast<void*>(value)) - (VulkanTypeHelper<T>::IsNonDispatchable ? 0 : 16); if (pAllocator) { pAllocator->pfnFree(pAllocator->pUserData, data); } else { free(data); } } #if defined(VK_USE_PLATFORM_WIN32_KHR) template<> inline void Free(VkIcdSurfaceWin32* value, const VkAllocationCallbacks* pAllocator) noexcept { if (pAllocator) { pAllocator->pfnFree(pAllocator->pUserData, value); } else { free(value); } } #endif #if defined(VK_USE_PLATFORM_XCB_KHR) template<> inline void Free(VkIcdSurfaceXcb* value, const VkAllocationCallbacks* pAllocator) noexcept { if (pAllocator) { pAllocator->pfnFree(pAllocator->pUserData, value); } else { free(value); } } #endif #if defined(VK_USE_PLATFORM_XLIB_KHR) template<> inline void Free(VkIcdSurfaceXlib* value, const VkAllocationCallbacks* pAllocator) noexcept { if (pAllocator) { pAllocator->pfnFree(pAllocator->pUserData, value); } else { free(value); } } #endif template<bool IsNonDispatchable> void WrapVulkan(void* local, uint64_t* vulkan) noexcept; template<bool IsNonDispatchable> void* UnwrapVulkan(uint64_t vulkanValue) noexcept; template<> inline void WrapVulkan<false>(void* local, uint64_t* vulkan) noexcept { assert(local); assert(vulkan); const auto data = static_cast<uint8_t*>(local); *vulkan = reinterpret_cast<uint64_t>(data - 16); } template<> inline void* UnwrapVulkan<false>(uint64_t vulkanValue) noexcept { assert(vulkanValue); return reinterpret_cast<void*>(vulkanValue + 16); } template<> inline void WrapVulkan<true>(void* local, uint64_t* vulkan) noexcept { assert(local); assert(vulkan); *vulkan = reinterpret_cast<uint64_t>(local); } template<> inline void* UnwrapVulkan<true>(uint64_t vulkanValue) noexcept { assert(vulkanValue); return reinterpret_cast<void*>(vulkanValue); } template<typename LocalType> void WrapVulkan(LocalType* local, typename VulkanTypeHelper<LocalType>::Type* vulkan) noexcept { WrapVulkan<VulkanTypeHelper<LocalType>::IsNonDispatchable>(local, reinterpret_cast<uint64_t*>(vulkan)); } template<typename LocalType> LocalType* UnwrapVulkan(typename VulkanTypeHelper<LocalType>::Type vulkanValue) noexcept { return reinterpret_cast<LocalType*>(UnwrapVulkan<VulkanTypeHelper<LocalType>::IsNonDispatchable>(reinterpret_cast<uint64_t>(vulkanValue))); } #pragma warning(pop) constexpr auto PI = 3.14159265358979323846;
{ "alphanum_fraction": 0.7963119966, "avg_line_length": 24.1948717949, "ext": "h", "hexsha": "bbe3d077fc884fd555e3740c60b4bcc1c2507036", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "d96f2f6db4cbbabcc41c2023a48ec63d1950dec0", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "MatthewSmit/CPVulkan", "max_forks_repo_path": "CPVulkanBase/Base.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "d96f2f6db4cbbabcc41c2023a48ec63d1950dec0", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "MatthewSmit/CPVulkan", "max_issues_repo_path": "CPVulkanBase/Base.h", "max_line_length": 196, "max_stars_count": 1, "max_stars_repo_head_hexsha": "d96f2f6db4cbbabcc41c2023a48ec63d1950dec0", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "MatthewSmit/CPVulkan", "max_stars_repo_path": "CPVulkanBase/Base.h", "max_stars_repo_stars_event_max_datetime": "2019-11-13T00:47:05.000Z", "max_stars_repo_stars_event_min_datetime": "2019-11-13T00:47:05.000Z", "num_tokens": 2366, "size": 9436 }
#include <float.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_spmatrix.h> #include <gsl/gsl_vector.h> #include <osqp/osqp.h> #include "qdm.h" #define QDM_THETA_MIN_THRESHOLD 0.0001 int qdm_theta_optimize( gsl_vector *result, gsl_vector *emperical_quantiles, gsl_matrix *ix ) { int status = 0; gsl_matrix *p = gsl_matrix_alloc(ix->size2, ix->size2); gsl_matrix *a = gsl_matrix_alloc(ix->size2, ix->size2); gsl_vector *q = gsl_vector_alloc(ix->size2); gsl_vector *l = gsl_vector_alloc(ix->size2); gsl_vector *u = gsl_vector_alloc(ix->size2); // FIXME check c_malloc... OSQPData *data = c_malloc(sizeof(OSQPData)); OSQPSettings *settings = c_malloc(sizeof(OSQPSettings)); OSQPWorkspace *work = NULL; /* Ensure all data fields are initialized before use. */ *data = (OSQPData) { .n = 0, .m = 0, .P = NULL, .A = NULL, .q = NULL, .l = NULL, .u = NULL, }; status = qdm_matrix_tmm(ix, p); if (status != 0) { goto cleanup; } qdm_matrix_select_upper_triangle(p); gsl_matrix_set_identity(a); gsl_vector_set_all(l, QDM_THETA_MIN_THRESHOLD); gsl_vector_set_all(u, INFINITY); status = gsl_blas_dgemv(CblasTrans, -1.0, ix, emperical_quantiles, 0, q); if (status != 0) { goto cleanup; } /* Solve... */ data->n = ix->size2; data->m = ix->size2; status = qdm_matrix_to_csc_matrix(&data->P, p); if (status != 0) { goto cleanup; } status = qdm_matrix_to_csc_matrix(&data->A, a); if (status != 0) { goto cleanup; } data->q = q->data; data->l = l->data; data->u = u->data; osqp_set_default_settings(settings); settings->verbose = 0; status = osqp_setup(&work, data, settings); if (status != 0) { goto cleanup; } status = osqp_solve(work); if (status != 0) { goto cleanup; } gsl_vector_view beta0 = gsl_vector_view_array(work->solution->x, ix->size2); status = gsl_vector_memcpy(result, &beta0.vector); if (status != 0) { goto cleanup; } cleanup: if (data != NULL) { if (data->A != NULL) { free(data->A->p); free(data->A->i); free(data->A->x); } c_free(data->A); if (data->P != NULL) { free(data->P->p); free(data->P->i); free(data->P->x); } c_free(data->P); c_free(data); } c_free(settings); osqp_cleanup(work); gsl_vector_free(u); gsl_vector_free(l); gsl_vector_free(q); gsl_matrix_free(a); gsl_matrix_free(p); return status; } void qdm_theta_matrix_constrain( gsl_matrix *theta, double min ) { /* First row is constrained to be greater than zero. */ for (size_t j = 0; j < theta->size2; j++) { if (gsl_matrix_get(theta, 0, j) < 0) { gsl_matrix_set(theta, 0, j, min); } } /* Remaining cells are set to zero if the sum of the column is negative. * * NOTE: The first column is not modified. */ for (size_t i = 1; i < theta->size1; i++) { for (size_t j = 1; j < theta->size2; j++) { gsl_vector_view column = gsl_matrix_column(theta, j); double sum = qdm_vector_sum(&column.vector); if (sum < 0) { gsl_matrix_set(theta, i, j, 0); } } } }
{ "alphanum_fraction": 0.6118892001, "avg_line_length": 20.2075471698, "ext": "c", "hexsha": "14a6f04e6b9b2a4e4eb9839fa25e7870e05d8924", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "calebcase/qdm", "max_forks_repo_path": "src/theta.c", "max_issues_count": 3, "max_issues_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_issues_repo_issues_event_max_datetime": "2020-03-22T20:22:53.000Z", "max_issues_repo_issues_event_min_datetime": "2020-03-06T18:09:06.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "calebcase/qdm", "max_issues_repo_path": "src/theta.c", "max_line_length": 78, "max_stars_count": null, "max_stars_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "calebcase/qdm", "max_stars_repo_path": "src/theta.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1015, "size": 3213 }
#pragma once #include <gsl/assert> constexpr char deathstring[] = "Expected Death"; constexpr char failed_set_terminate_deathstring[] = ".*"; // This prevents a failed call to set_terminate from failing the test suite. constexpr const char* GetExpectedDeathString(std::terminate_handler handle) { return handle ? deathstring : failed_set_terminate_deathstring; }
{ "alphanum_fraction": 0.7631578947, "avg_line_length": 31.6666666667, "ext": "h", "hexsha": "7bf242393f7bcff62c12cd985a87824f48f7bb0b", "lang": "C", "max_forks_count": 616, "max_forks_repo_forks_event_max_datetime": "2019-05-02T13:56:27.000Z", "max_forks_repo_forks_event_min_datetime": "2015-09-16T20:40:37.000Z", "max_forks_repo_head_hexsha": "4377f6e603c64a86c934f1546aa9db482f2e1a4e", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Batfing/GSL", "max_forks_repo_path": "tests/deathTestCommon.h", "max_issues_count": 716, "max_issues_repo_head_hexsha": "4377f6e603c64a86c934f1546aa9db482f2e1a4e", "max_issues_repo_issues_event_max_datetime": "2019-05-05T16:08:33.000Z", "max_issues_repo_issues_event_min_datetime": "2015-09-16T09:04:54.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "Batfing/GSL", "max_issues_repo_path": "tests/deathTestCommon.h", "max_line_length": 77, "max_stars_count": 3645, "max_stars_repo_head_hexsha": "4377f6e603c64a86c934f1546aa9db482f2e1a4e", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Batfing/GSL", "max_stars_repo_path": "tests/deathTestCommon.h", "max_stars_repo_stars_event_max_datetime": "2019-05-06T15:06:09.000Z", "max_stars_repo_stars_event_min_datetime": "2015-09-16T08:10:27.000Z", "num_tokens": 78, "size": 380 }
#include <stdio.h> #include <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include "fermi.h" int main(int argc, char *argv[]) { int num_bands = 2; double t = 1.0; double E0 = 6.0; double deltaE = 14.0; void Efn(double k[3], gsl_vector *energies) { double cx = cos(2.0 * M_PI * k[0]); double cy = cos(2.0 * M_PI * k[1]); double cz = cos(2.0 * M_PI * k[2]); double tk = -2.0 * t * (cx + cy + cz); int i; double E0_band; for (i = 0; i < num_bands; i++) { E0_band = E0 + ((double)i) * deltaE; gsl_vector_set(energies, i, E0_band + tk); } } int na = 8; int nb = 8; int nc = 8; int G_order[3] = {0, 1, 2}; int G_neg[3] = {1, 1, 1}; bool use_cache = true; EnergyCache *Ecache = init_EnergyCache(na, nb, nc, num_bands, G_order, G_neg, Efn, use_cache); double num_electrons = 1.0; double E_Fermi = 0.0; int err = FindFermi(num_electrons, Ecache, &E_Fermi); printf("Got E_Fermi = %f\n", E_Fermi); if (err != CTETRA_BISECT_OK) { printf("Error = %d returned from FindFermi.\n", err); return err; } double expected = 13.0; if (E_Fermi < 12.0 || E_Fermi > 14.0) { printf("Incorrect E_Fermi; got %f, expected %f\n", E_Fermi, expected); return 1; } num_electrons = 0.5; err = FindFermi(num_electrons, Ecache, &E_Fermi); printf("Got E_Fermi = %f\n", E_Fermi); if (err != CTETRA_BISECT_OK) { printf("Error = %d returned from FindFermi.\n", err); return err; } double tol = 1e-8; expected = 6.0; if (fabs(E_Fermi - expected) > tol) { printf("Incorrect E_Fermi; got %f, expected %f\n", E_Fermi, expected); return 1; } printf("Fermi test passed.\n"); return 0; }
{ "alphanum_fraction": 0.5502702703, "avg_line_length": 28.0303030303, "ext": "c", "hexsha": "8e1dffcba4329b7523dfab12e6186a64220de3bc", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "tflovorn/ctetra", "max_forks_repo_path": "fermi_test.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1", "max_issues_repo_issues_event_max_datetime": "2016-11-30T15:23:35.000Z", "max_issues_repo_issues_event_min_datetime": "2016-11-19T22:44:14.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "tflovorn/ctetra", "max_issues_repo_path": "fermi_test.c", "max_line_length": 98, "max_stars_count": null, "max_stars_repo_head_hexsha": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "tflovorn/ctetra", "max_stars_repo_path": "fermi_test.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 663, "size": 1850 }
/** * @file common.h * @brief Public header file containing the common objects, API used by different applications */ #ifndef COMMON_H #define COMMON_H #include <petsc.h> /** * @brief The communicator context */ struct _p_COMM { MPI_Comm type; /**< MPI communicator SELF or WORLD */ PetscMPIInt rank; /**< Process rank */ PetscMPIInt size; /**< Communicator size */ PetscInt refct; /**< Reference count to know how many objects are sharing the communicator */ }; typedef struct _p_COMM *COMM; /** * @brief Creates the communicator object COMM * @param [in] MPI_Comm mpicomm - The MPI communicator * @param [out] COMM* outcomm - The COMM object */ extern PetscErrorCode COMMCreate(MPI_Comm,COMM*); /** * @brief Destroys the communicator object COMM created with COMMCreate * @param [in] COMM* outcomm - The COMM object */ extern PetscErrorCode COMMDestroy(COMM*); /** * @brief NOT IMPLIMENTED */ extern PetscErrorCode SetMatrixValues(Mat,PetscInt,PetscInt[],PetscInt,PetscInt[],PetscScalar[]); #endif
{ "alphanum_fraction": 0.7131857555, "avg_line_length": 26.641025641, "ext": "h", "hexsha": "bfa6caa86ae8423e7b548a8db21f27fffd236914", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2019-09-11T00:24:08.000Z", "max_forks_repo_forks_event_min_datetime": "2019-09-11T00:24:08.000Z", "max_forks_repo_head_hexsha": "85b21a84514f438b6b956f024e4b753c0f3ccc95", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "pflow-team/PFLOW", "max_forks_repo_path": "include/common.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "85b21a84514f438b6b956f024e4b753c0f3ccc95", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "pflow-team/PFLOW", "max_issues_repo_path": "include/common.h", "max_line_length": 99, "max_stars_count": null, "max_stars_repo_head_hexsha": "85b21a84514f438b6b956f024e4b753c0f3ccc95", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "pflow-team/PFLOW", "max_stars_repo_path": "include/common.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 252, "size": 1039 }
#include <stdio.h> #include <math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_odeiv2.h> #include <gsl/gsl_math.h> #define pi M_PI //############################################################################# //############################################################################# //Ray path solver //Data structure for pointers to julia cavity data and functions typedef struct { //pointer to Boundary object void *bnd; //pointer to radius function double (*rfunc_p)(void *bnd,double theta); //pointer to (mutating) radius and normal vector angle function void (*rsys_p)(void *bnd, double theta, double results[]); //pointer to RefractiveIndex object void *idx; //pointer to refractive index value function double (*nfunc_p)(void *idx, double r, double theta); //pointer to (mutating) refractive index value and derivative function void (*nderiv_p)(void *idx, double r, double theta, double results[]); } cavinfo; //############################################################################# //Functions for ODE //ODE derivatives function int odefunc(double t, const double y[], double f[], void *params){ //Get Julia pointers cavinfo *cip = (cavinfo *)params; //Calculate n and its derivatives and store in results array double results[3]; (*(*cip).nderiv_p)((*cip).idx,y[0],y[1],results); //results[0] = n, results[1] = dn/dr, results[2] = dn/dtheta //Debugging purposes //printf("n = %.5f, dr_n = %.5f, dtheta_n = %.5f\n",n,dr_n,dtheta_n); //Calculate and store derivative of ODE coordinate vector //Equations are: //r' = p_r/n //theta' = p_theta/(r^2*n) //p_r' = p_theta^2/(r^3*n) + dn/dr //p_theta' = dn/dtheta f[0] = y[2]/results[0]; f[1] = y[3]/(y[0]*y[0]*results[0]); f[2] = y[3]*y[3]/(y[0]*y[0]*y[0]*results[0]) + results[1]; f[3] = results[2]; return GSL_SUCCESS; } //ODE Jacobian function int odejac(double t, const double y[], double *dfdy, double dfdt[], void *params){ //RK8PD does not require the Jacobian return GSL_SUCCESS; } //############################################################################# //Solver functions //Ray reflection //Re-compute a ray coordinate vector to simulate a bounce, using the ODE coordinate vectors S0 and S immediately before and after the bounce, where S0 = (r0,theta0,pr0,ptheta0), and S = (r,theta,pr,ptheta). double raybounce(cavinfo *cip, double S0[], double S[]){ //Binary search for intersection of trajectory with cavity boundary //Assume that light trajectory between (r0,theta0) and (r,theta) is a straight line //(fastest way to interpolate, after all this is already within 1 stepsize of time) const double x0 = S0[0]*cos(S0[1]), y0 = S0[0]*sin(S0[1]); const double x1 = S[0]*cos(S[1]), y1 = S[0]*sin(S[1]); double uA = 0.0, uB = 1.0; //bounds of the binary search double xC,yC,rC,thetaC,RC,uC; do{ uC = 0.5*(uA+uB); //get middle point xC = (1-uC)*x0 + uC*x1; yC = (1-uC)*y0 + uC*y1; rC = hypot(xC,yC); thetaC = atan2(yC,xC); RC = (*(*cip).rfunc_p)((*cip).bnd,thetaC); //Change boundary if(rC > RC) uB = uC; else uA = uC; } while(fabs(rC-RC) > 1e-12); //Get angle of incidence and store in results array double results[2]; (*(*cip).rsys_p)((*cip).bnd,thetaC,results); //results[0] = rC, results[1] = alpha //Use linear interpolation to find ray angle phi at intersection const double phi0 = S0[1] + atan2(S0[3],S0[0]*S0[2]); const double phi1 = S[1] + atan2(S[3],S[0]*S[2]); const double phiC = (1-uC)*phi0 + uC*phi1; //Angle of incidence const double chi = phiC - results[1]; //Store interpolated and reflected ODE coordinate vector const double phi = pi - chi + results[1]; //ray angle after reflection const double n = (*(*cip).nfunc_p)((*cip).idx,rC,thetaC); const double pr = n*cos(phi-thetaC); const double ptheta = n*rC*sin(phi-thetaC); S[0] = rC; S[1] = thetaC; S[2] = pr; S[3] = ptheta; //Report bounce information return chi; } //Ray evolution void rayevolve( //Storage arrays double raypath_r[], double raypath_theta[], long bounceindices[], double bouncepts_chi[], long lengths[], //Initial conditions double r0, double theta0, double pr0, double ptheta0, //Simulation parameters double tmax, long bouncemax, double reltol, double abstol, //Cavity parameters void *bnd, double (*rfunc_p)(void *bnd,double theta), void (*rsys_p)(void *bnd, double theta,double results[]), void *idx, double (*nfunc_p)(void *idx, double r, double theta), void (*nderiv_p)(void *idx, double r, double theta,double results[])){ //Condense input cavity data into cavinfo struct cavinfo ci = {bnd,rfunc_p,rsys_p,idx,nfunc_p,nderiv_p}; //Initialize solver gsl_odeiv2_system sys = {odefunc,odejac,4,&ci}; const gsl_odeiv2_step_type *steptype = gsl_odeiv2_step_rk8pd; gsl_odeiv2_step *step = gsl_odeiv2_step_alloc(steptype,4); gsl_odeiv2_control *control = gsl_odeiv2_control_y_new(abstol,reltol); gsl_odeiv2_evolve *evolve = gsl_odeiv2_evolve_alloc(4); //Initialize parameters double t = 0.0, dt = 0.0001; double y0[4], y[4] = {r0,theta0,pr0,ptheta0}; //Prepare results record long bouncenum = 0, stepnum = 1; //indicates postion to record next const long prealloc = 250*ceil(tmax); //length of preallocated raypath array raypath_r[0] = y[0]; raypath_theta[0] = y[1]; //Solver loop while(t < tmax && bouncenum < bouncemax && stepnum < prealloc){ //Record initial position y0[0] = y[0], y0[1] = y[1], y0[2] = y[2], y0[3] = y[3]; //Run Solver int status = gsl_odeiv2_evolve_apply(evolve,control,step,&sys,&t,tmax,&dt,y); if(status != GSL_SUCCESS) break; //Check Hamiltonian once in a while for sanity check if(stepnum%1000 == 0){ double H = y[2]*y[2]+y[3]*y[3]/(y[0]*y[0]) - gsl_pow_2((*ci.nfunc_p)(ci.idx,y[0],y[1])); if(H > 1e-9) printf("Warning: Error in Hamiltonian is %.f\n",H); } //Check difference in ray and boundary radial positions double dr = y[0] - (*ci.rfunc_p)(ci.bnd,y[1]); if(dr > 0){ //Boundary crossing! //get chi and corrected y bouncepts_chi[bouncenum] = raybounce(&ci,y0,y); //store (Julia's 1-based) index for thetaC values recorded in //raypath_theta array bounceindices[bouncenum] = stepnum+1; bouncenum += 1; } //Record position raypath_r[stepnum] = y[0]; raypath_theta[stepnum] = y[1]; stepnum += 1; //Display progress for debugging //printf("t = %.5f, y = [%.5f,%.5f,%.5f,%.5f]\n",t,y[0],y[1],y[2],y[3]); } //Store lengths of arrays lengths[0] = stepnum; lengths[1] = bouncenum; //Free memory gsl_odeiv2_step_free(step); gsl_odeiv2_control_free(control); gsl_odeiv2_evolve_free(evolve); }
{ "alphanum_fraction": 0.5705119636, "avg_line_length": 38.1683673469, "ext": "c", "hexsha": "ceaa11cf8a1a376f571e03987ba8b733ba224e6d", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "f4a2f9801af5e67a5648d37901a4e5cd377c064d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "amyascwk/CavChaos.jl", "max_forks_repo_path": "src/ray.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "f4a2f9801af5e67a5648d37901a4e5cd377c064d", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "amyascwk/CavChaos.jl", "max_issues_repo_path": "src/ray.c", "max_line_length": 206, "max_stars_count": null, "max_stars_repo_head_hexsha": "f4a2f9801af5e67a5648d37901a4e5cd377c064d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "amyascwk/CavChaos.jl", "max_stars_repo_path": "src/ray.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2214, "size": 7481 }
#include "../precision.h" #undef SKIP #ifdef GSL_FLOAT #ifdef MATLAB_FLOAT_H #define SKIP #else #define MATLAB_FLOAT_H #endif #endif #ifdef GSL_DOUBLE #ifdef MATLAB_H #define SKIP #else #define MATLAB_H #endif #endif #ifdef GSL_LONG_DOUBLE #ifdef MATLAB_LONG_DOUBLE_H #define SKIP #else #define MATLAB_LONG_DOUBLE_H #endif #endif #ifndef SKIP #include <gsl/gsl_matrix.h> #include <gsl/gsl_permutation.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_vector.h> #include <limits> #include <string> namespace MATLAB_NAMESPACE { // Functions VECTOR_T* abs(const VECTOR_T* v); MATRIX_T* abs(const MATRIX_T* m); int all(const VECTOR_T* v); VECTOR_T* all(const MATRIX_T* m, int dim = 1); int any(const VECTOR_T* v); VECTOR_T* any(const MATRIX_T* m, int dim = 1); std::string dec2bin(int n); std::string dec2bin(int n, int len); MATRIX_T* diag(const VECTOR_T* v, int k = 0); VECTOR_T* diag(const MATRIX_T* m, int k = 0); MATRIX_T* eye(int size); MATRIX_T* eye(int size1, int size2); VECTOR_T* find(const VECTOR_T* v, int n = std::numeric_limits<int>::max(), const std::string& direction = "first"); VECTOR_T* find(const MATRIX_T* m, int n = std::numeric_limits<int>::max(), const std::string& direction = "first"); MATRIX_T* find_ij(const MATRIX_T* m, int n = std::numeric_limits<int>::max(), const std::string& direction = "first"); VECTOR_T* hist(const VECTOR_T* v, int n = 10); VECTOR_T* hist(const VECTOR_T* v, const VECTOR_T* centers); MATRIX_T* inv(const MATRIX_T* m); int length(const VECTOR_T* v); int length(const MATRIX_T* m); FP_T max(FP_T x, FP_T y); FP_T max(const VECTOR_T* v); VECTOR_T* max(const MATRIX_T* m, int dim = 1); FP_T mean(const VECTOR_T* v, const std::string& opt = "a"); VECTOR_T* mean(const MATRIX_T* m, int dim = 1, const std::string& opt = "a"); FP_T min(FP_T x, FP_T y); FP_T min(const VECTOR_T* v); VECTOR_T* min(const MATRIX_T* m, int dim = 1); int nnz(const VECTOR_T* v); int nnz(const MATRIX_T* m); VECTOR_T* nonzeros(const MATRIX_T* m); FP_T norm(const VECTOR_T* v, int p); VECTOR_T* normpdf(const VECTOR_T* v, FP_T mean, FP_T stdev); MATRIX_T* ones(int size); MATRIX_T* ones(int size1, int size2); VECTOR_T* ones_vector(int size); FP_T prod(const VECTOR_T* v); VECTOR_T* prod(const MATRIX_T* m, int dim = 1); MATRIX_T* rand(int size); MATRIX_T* rand(int size1, int size2); VECTOR_T* rand_vector(int size); gsl_permutation* randperm(int size); VECTOR_T* reverse(const VECTOR_T* v); VECTOR_T* setxor(const VECTOR_T* v1, const VECTOR_T* v2); VECTOR_T* sort(const VECTOR_T* v, const std::string& mode = "ascend", VECTOR_T** ind = NULL); MATRIX_T* sort(const MATRIX_T* m, int dim = 1, const std::string& mode = "ascend", MATRIX_T** ind = NULL); VECTOR_T* sortrows(const VECTOR_T* v, VECTOR_T** ind = NULL); MATRIX_T* sortrows(const MATRIX_T* m, VECTOR_T** ind = NULL); FP_T std(const VECTOR_T* v, int opt = 0); VECTOR_T* std(const MATRIX_T* m, int opt = 0, int dim = 1); FP_T sum(const VECTOR_T* v); VECTOR_T* sum(const MATRIX_T* m, int dim = 1); MATRIX_T* toeplitz(const VECTOR_T* column, const VECTOR_T* row = NULL); MATRIX_T* tril(const MATRIX_T* m, int k = 0); MATRIX_T* triu(const MATRIX_T* m, int k = 0); VECTOR_T* unique(const VECTOR_T* v, const std::string& first_or_last = "last", VECTOR_T** i = NULL, VECTOR_T** j = NULL); VECTOR_T* unique(const MATRIX_T* m, const std::string& first_or_last = "last", VECTOR_T** i = NULL, VECTOR_T** j = NULL); MATRIX_T* unique_rows(const MATRIX_T* m, const std::string& first_or_last = "last", VECTOR_T** i = NULL, VECTOR_T** j = NULL); MATRIX_T* zeros(int size); MATRIX_T* zeros(int size1, int size2); VECTOR_T* zeros_vector(int size); // Operators VECTOR_T* concatenate(const VECTOR_T* v, FP_T x); VECTOR_T* concatenate(FP_T x, const VECTOR_T* v); VECTOR_T* concatenate(const VECTOR_T* v1, const VECTOR_T* v2); MATRIX_T* concatenate_columns(const VECTOR_T* v1, const VECTOR_T* v2); MATRIX_T* concatenate_columns(const MATRIX_T* m, const VECTOR_T* v); MATRIX_T* concatenate_columns(const VECTOR_T* v, const MATRIX_T* m); MATRIX_T* concatenate_columns(const MATRIX_T* m1, const MATRIX_T* m2); MATRIX_T* concatenate_rows(const VECTOR_T* v1, const VECTOR_T* v2); MATRIX_T* concatenate_rows(const MATRIX_T* m, const VECTOR_T* v); MATRIX_T* concatenate_rows(const VECTOR_T* v, const MATRIX_T* m); MATRIX_T* concatenate_rows(const MATRIX_T* m1, const MATRIX_T* m2); VECTOR_T* copy(const VECTOR_T* v); MATRIX_T* copy(const MATRIX_T* m); MATRIX_T* div_left(const MATRIX_T* m1, const MATRIX_T* m2); MATRIX_T* div_right(const MATRIX_T* m1, const MATRIX_T* m2); VECTOR_T* logical_and(const VECTOR_T* v1, const VECTOR_T* v2); MATRIX_T* logical_and(const MATRIX_T* m1, const MATRIX_T* m2); VECTOR_T* logical_not(const VECTOR_T* v); MATRIX_T* logical_not(const MATRIX_T* m); VECTOR_T* logical_or(const VECTOR_T* v1, const VECTOR_T* v2); MATRIX_T* logical_or(const MATRIX_T* m1, const MATRIX_T* m2); MATRIX_T* mul(const MATRIX_T* m1, const MATRIX_T* m2); MATRIX_T* pow(const MATRIX_T* m, int power); VECTOR_T* pow_elements(const VECTOR_T* v, FP_T power); VECTOR_T* pow_elements(const VECTOR_T* v, const VECTOR_T* powers); MATRIX_T* pow_elements(const MATRIX_T* m, FP_T power); MATRIX_T* pow_elements(const MATRIX_T* m, const MATRIX_T* powers); VECTOR_T* sequence(int start, int end); VECTOR_T* sequence(int start, int step, int end); // Floating-point comparison extern FP_T epsilon; int fp_compare(FP_T x, FP_T y); bool fp_zero(FP_T x); bool fp_nonzero(FP_T x); bool fp_equal(FP_T x, FP_T y); bool fp_not_equal(FP_T x, FP_T y); bool fp_less(FP_T x, FP_T y); bool fp_less_or_equal(FP_T x, FP_T y); bool fp_greater(FP_T x, FP_T y); bool fp_greater_or_equal(FP_T x, FP_T y); // Vector/matrix comparison typedef bool (*comparator)(FP_T, FP_T); int compare_vectors(const VECTOR_T* v1, const VECTOR_T* v2); bool vector_less(VECTOR_T* v1, VECTOR_T* v2); int compare_matrices(const MATRIX_T* m1, const MATRIX_T* m2); bool matrix_less(MATRIX_T* m1, MATRIX_T* m2); VECTOR_T* compare_elements(const VECTOR_T* v, comparator compare, FP_T x); VECTOR_T* compare_elements(const VECTOR_T* v1, comparator compare, const VECTOR_T* v2); MATRIX_T* compare_elements(const MATRIX_T* m, comparator compare, FP_T x); MATRIX_T* compare_elements(const MATRIX_T* m1, comparator compare, const MATRIX_T* m2); // Vector-by-vector indexing VECTOR_T* ordinal_index(const VECTOR_T* v, const VECTOR_T* indices); void ordinal_index_assign(VECTOR_T* v, const VECTOR_T* indices, FP_T value); void ordinal_index_assign(VECTOR_T* v, const VECTOR_T* indices, const VECTOR_T* values); VECTOR_T* logical_index(const VECTOR_T* v, const VECTOR_T* logical_v); void logical_index_assign(VECTOR_T* v, const VECTOR_T* logical_v, FP_T value); void logical_index_assign(VECTOR_T* v, const VECTOR_T* logical_v, const VECTOR_T* values); // Matrix-by-integer indexing FP_T ordinal_index(const MATRIX_T* m, int index); void ordinal_index_assign(MATRIX_T* m, int index, FP_T value); // Matrix-by-vector indexing VECTOR_T* ordinal_index(const MATRIX_T* m, const VECTOR_T* indices); void ordinal_index_assign(MATRIX_T* m, const VECTOR_T* indices, FP_T value); void ordinal_index_assign(MATRIX_T* m, const VECTOR_T* indices, const VECTOR_T* values); VECTOR_T* logical_index(const MATRIX_T* m, const VECTOR_T* logical_v); void logical_index_assign(MATRIX_T* m, const VECTOR_T* logical_v, FP_T value); void logical_index_assign(MATRIX_T* m, const VECTOR_T* logical_v, const VECTOR_T* values); // Matrix-by-two-vectors indexing (non-mixed) MATRIX_T* ordinal_index(const MATRIX_T* m, const VECTOR_T* rows, const VECTOR_T* columns); void ordinal_index_assign(MATRIX_T* m, const VECTOR_T* rows, const VECTOR_T* columns, FP_T value); void ordinal_index_assign(MATRIX_T* m, const VECTOR_T* rows, const VECTOR_T* columns, const MATRIX_T* values); MATRIX_T* logical_index(const MATRIX_T* m, const VECTOR_T* logical_rows, const VECTOR_T* logical_columns); void logical_index_assign(MATRIX_T* m, const VECTOR_T* logical_rows, const VECTOR_T* logical_columns, FP_T value); void logical_index_assign(MATRIX_T* m, const VECTOR_T* logical_rows, const VECTOR_T* logical_columns, const MATRIX_T* values); // Matrix-by-two-vectors indexing (mixed) MATRIX_T* ord_log_index(const MATRIX_T* m, const VECTOR_T* rows, const VECTOR_T* logical_columns); void ord_log_index_assign(MATRIX_T* m, const VECTOR_T* rows, const VECTOR_T* logical_columns, FP_T value); void ord_log_index_assign(MATRIX_T* m, const VECTOR_T* rows, const VECTOR_T* logical_columns, const MATRIX_T* values); MATRIX_T* log_ord_index(const MATRIX_T* m, const VECTOR_T* logical_rows, const VECTOR_T* columns); void log_ord_index_assign(MATRIX_T* m, const VECTOR_T* logical_rows, const VECTOR_T* columns, FP_T value); void log_ord_index_assign(MATRIX_T* m, const VECTOR_T* logical_rows, const VECTOR_T* columns, const MATRIX_T* values); // Matrix-by-matrix indexing MATRIX_T* ordinal_index(const MATRIX_T* m, const MATRIX_T* indices); void ordinal_index_assign(MATRIX_T* m, const MATRIX_T* indices, FP_T value); void ordinal_index_assign(MATRIX_T* m, const MATRIX_T* indices, const MATRIX_T* values); VECTOR_T* logical_index(const MATRIX_T* m, const MATRIX_T* logical_m); void logical_index_assign(MATRIX_T* m, const MATRIX_T* logical_m, FP_T value); void logical_index_assign(MATRIX_T* m, const MATRIX_T* logical_m, const VECTOR_T* values); // Vector/matrix conversion void to_array(const VECTOR_T* v, FP_T* array); bool to_bool(const VECTOR_T* v); bool to_bool(const MATRIX_T* m); VECTOR_T* to_vector(const gsl_vector* v_d); gsl_vector* to_vector_double(const VECTOR_T* v); VECTOR_T* to_vector(const MATRIX_T* m); MATRIX_T* to_column_matrix(const VECTOR_T* v); MATRIX_T* to_row_matrix(const VECTOR_T* v); MATRIX_T* to_matrix(const gsl_matrix* m_d); gsl_matrix* to_matrix_double(const MATRIX_T* m); VECTOR_T* to_vector(const gsl_permutation* p); gsl_permutation* to_permutation(const VECTOR_T* v); // Utility gsl_rng* get_rng(); void seed_rng(const gsl_rng* rng, unsigned long seed); VECTOR_T* permute(const gsl_permutation* p, const VECTOR_T* v); MATRIX_T* permute_columns(const gsl_permutation* p, const MATRIX_T* m); MATRIX_T* permute_rows(const gsl_permutation* p, const MATRIX_T* m); } #endif
{ "alphanum_fraction": 0.7510638298, "avg_line_length": 46.1607142857, "ext": "h", "hexsha": "5f625d629f70ae90ca598e4f84046e9ed7703a9b", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "bbb33f476bffbb5669e051841f00c3241f4d6f69", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "devuci/bct-cpp", "max_forks_repo_path": "matlab/matlab.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "bbb33f476bffbb5669e051841f00c3241f4d6f69", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "devuci/bct-cpp", "max_issues_repo_path": "matlab/matlab.h", "max_line_length": 127, "max_stars_count": null, "max_stars_repo_head_hexsha": "bbb33f476bffbb5669e051841f00c3241f4d6f69", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "devuci/bct-cpp", "max_stars_repo_path": "matlab/matlab.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2948, "size": 10340 }
// The MIT License (MIT) // // Copyright (c) 2018 Mateusz Pusz // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #pragma once #include <units/bits/external/hacks.h> #include <units/bits/math_concepts.h> #include <units/bits/ratio_maths.h> #include <units/bits/pow.h> #include <units/bits/root.h> #include <cstdint> #include <numeric> #include <type_traits> #include <tuple> #include <gsl/gsl-lite.hpp> namespace units { struct ratio; constexpr ratio inverse(const ratio& r); /** * @brief Provides compile-time rational arithmetic support. * * This class is really similar to @c std::ratio but gets an additional `Exp` * template parameter that defines the exponent of the ratio. Another important * difference is the fact that the objects of that class are used as class NTTPs * rather then a type template parameter kind. */ struct ratio { std::intmax_t num; std::intmax_t den; std::intmax_t exp; constexpr explicit ratio(std::intmax_t n, std::intmax_t d = 1, std::intmax_t e = 0): num(n), den(d), exp(e) { gsl_Expects(den != 0); detail::normalize(num, den, exp); } [[nodiscard]] friend constexpr bool operator==(const ratio&, const ratio&) = default; [[nodiscard]] friend constexpr ratio operator*(const ratio& lhs, const ratio& rhs) { const std::intmax_t gcd1 = std::gcd(lhs.num, rhs.den); const std::intmax_t gcd2 = std::gcd(rhs.num, lhs.den); return ratio(detail::safe_multiply(lhs.num / gcd1, rhs.num / gcd2), detail::safe_multiply(lhs.den / gcd2, rhs.den / gcd1), lhs.exp + rhs.exp); } [[nodiscard]] friend constexpr ratio operator/(const ratio& lhs, const ratio& rhs) { return lhs * inverse(rhs); } }; [[nodiscard]] constexpr ratio inverse(const ratio& r) { return ratio(r.den, r.num, -r.exp); } [[nodiscard]] constexpr bool is_integral(const ratio& r) { if(r.exp < 0) { return false; } else { return detail::gcdpow(r.num, r.exp, r.den) == r.den; } } namespace detail { [[nodiscard]] constexpr auto make_exp_align(const ratio& r, std::intmax_t alignment) { gsl_Expects(alignment > 0); const std::intmax_t rem = r.exp % alignment; if (rem == 0) { // already aligned return std::array{r.num, r.den, r.exp}; } if (r.exp > 0) { // remainder is positive return std::array{r.num * ipow10(rem), r.den, r.exp - rem}; } // remainder is negative return std::array{r.num, r.den * ipow10(-rem), r.exp - rem}; } template<std::intmax_t N> requires gt_zero<N> [[nodiscard]] constexpr ratio root(const ratio& r) { if constexpr (N == 1) { return r; } else { if (r.num == 0) { return ratio(0); } const auto aligned = make_exp_align(r, N); return ratio(iroot<N>(aligned[0]), iroot<N>(aligned[1]), aligned[2] / N); } } } // namespace detail template<std::intmax_t Num, std::intmax_t Den = 1> requires detail::non_zero<Den> [[nodiscard]] constexpr ratio pow(const ratio& r) { if constexpr (Num == 0) { return ratio(1); } else if constexpr (Num == Den) { return r; } else { // simplify factors first and compute power for positive exponent constexpr std::intmax_t gcd = std::gcd(Num, Den); constexpr std::intmax_t num = detail::abs(Num / gcd); constexpr std::intmax_t den = detail::abs(Den / gcd); // integer root loses precision so do pow first const ratio result = detail::root<den>(detail::pow_impl<num>(r)); if constexpr (Num * Den < 0) { // account for negative exponent return inverse(result); } else { return result; } } } [[nodiscard]] constexpr ratio sqrt(const ratio& r) { return pow<1, 2>(r); } [[nodiscard]] constexpr ratio cbrt(const ratio& r) { return pow<1, 3>(r); } // common_ratio [[nodiscard]] constexpr ratio common_ratio(const ratio& r1, const ratio& r2) { const auto res = detail::gcd_frac(r1.num, r1.den, r1.exp, r2.num, r2.den, r2.exp); return ratio(res[0], res[1], res[2]); } } // namespace units
{ "alphanum_fraction": 0.6778711485, "avg_line_length": 30.2909090909, "ext": "h", "hexsha": "17a97613056660c9dc4c64ac93dc68d2fd87c382", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "1d2b9205383f967e4d21df20ac2fd4168b6ff7a8", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "HazardyKnusperkeks/units", "max_forks_repo_path": "src/core/include/units/ratio.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "1d2b9205383f967e4d21df20ac2fd4168b6ff7a8", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "HazardyKnusperkeks/units", "max_issues_repo_path": "src/core/include/units/ratio.h", "max_line_length": 109, "max_stars_count": null, "max_stars_repo_head_hexsha": "1d2b9205383f967e4d21df20ac2fd4168b6ff7a8", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "HazardyKnusperkeks/units", "max_stars_repo_path": "src/core/include/units/ratio.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1319, "size": 4998 }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "fitsio.h" #include <gsl/gsl_fit.h> #include <gsl/gsl_multifit.h> //The Function Declarations int read_image(char[],float[],long[]); int read_table(char[]); int write_image(char[],float[],long[]); int image_size(char[], long[]); int fit(double[],double[],double[],float[],int); int calc_pr(float[],float[],float,int,int,long[]); void printerror(int);
{ "alphanum_fraction": 0.698630137, "avg_line_length": 25.7647058824, "ext": "h", "hexsha": "0b5d30baffb170c00b35b2c7334a91709c49f3cb", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "c1bfedf5f8e5b0e9f77c6d1194bf1e0266d7efd8", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "boada/ICD", "max_forks_repo_path": "src/header.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "c1bfedf5f8e5b0e9f77c6d1194bf1e0266d7efd8", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "boada/ICD", "max_issues_repo_path": "src/header.h", "max_line_length": 50, "max_stars_count": null, "max_stars_repo_head_hexsha": "c1bfedf5f8e5b0e9f77c6d1194bf1e0266d7efd8", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "boada/ICD", "max_stars_repo_path": "src/header.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 110, "size": 438 }
//Gets deltas (1st order) and delta-deltas (2nd order) differences of X. //Only the deltas and delta-deltas are output in Y. //Thus, Y must be pre-allocated to have twice the size of X. //I implement this just like FIR for speed and shorter code, //except non-causal and mid-sample of B is 0, //so I don't explicitly make B (e.g., B[n] just equals sc*n). //Note that this may treat edge samples differently than other code. //But this could be changed with a few lines of additional code here, //without changing the super-efficient FIR implementation. //That is, since out-of-range samps were assumed to be 0, nothing was //added to Y for them, so can just add something later. #include <stdio.h> #include <cblas.h> #ifdef __cplusplus namespace ov { extern "C" { #endif int get_delta_deltas_s (float *Y, const float *X, const int iscolmajor, const int R, const int C, const int dim, const int N); int get_delta_deltas_d (double *Y, const double *X, const int iscolmajor, const int R, const int C, const int dim, const int N); int get_delta_deltas_s (float *Y, const float *X, const int iscolmajor, const int R, const int C, const int dim, const int N) { const float z = 0.0f; int r, c, n; float sc = 1.0f; //Checks if (R<1) { fprintf(stderr,"error in get_delta_deltas_s: R (nrows Y) must be positive\n"); return 1; } if (C<1) { fprintf(stderr,"error in get_delta_deltas_s: C (ncols Y) must be positive\n"); return 1; } if (N<1) { fprintf(stderr,"error in get_delta_deltas_s: N (delta winlength) must be positive\n"); return 1; } //Get sc (normalizer) for (n=2; n<=N; n++) { sc += n*n; } sc = 0.5f/sc; //Initialize Y cblas_scopy(2*R*C,&z,0,&Y[0],1); if (dim==0) { if (iscolmajor) { for (c=0; c<C; c++) { for (n=1; n<=N; n++) { cblas_saxpy(n,-sc*n,&X[c*R],0,&Y[c*R],1); //beg edge samps cblas_saxpy(R-n,-sc*n,&X[c*R],1,&Y[c*R+n],1); //past samps cblas_saxpy(R-n,sc*n,&X[c*R+n],1,&Y[c*R],1); //future samps cblas_saxpy(n,sc*n,&X[c*R+R-1],0,&Y[c*R+R-n],1); //end edge samps } for (n=1; n<=N; n++) { cblas_saxpy(n,-sc*n,&Y[c*R],0,&Y[R*C+c*R],1); //beg edge samps cblas_saxpy(R-n,-sc*n,&Y[c*R],1,&Y[R*C+c*R+n],1); //past samps cblas_saxpy(R-n,sc*n,&Y[c*R+n],1,&Y[R*C+c*R],1); //future samps cblas_saxpy(n,sc*n,&Y[c*R+R-1],0,&Y[R*C+c*R+R-n],1); //end edge samps } } } else { for (c=0; c<C; c++) { for (n=1; n<=N; n++) { cblas_saxpy(n,-sc*n,&X[c],0,&Y[c],2*C); //beg edge samps cblas_saxpy(R-n,-sc*n,&X[c],C,&Y[c+n*2*C],2*C); //past samps cblas_saxpy(R-n,sc*n,&X[c+n*C],C,&Y[c],2*C); //future samps cblas_saxpy(n,sc*n,&X[c+C*(R-1)],0,&Y[c+2*C*(R-n)],2*C); //end edge samps } for (n=1; n<=N; n++) { cblas_saxpy(n,-sc*n,&Y[c],0,&Y[C+c],2*C); //beg edge samps cblas_saxpy(R-n,-sc*n,&Y[c],2*C,&Y[C+c+n*2*C],2*C); //past samps cblas_saxpy(R-n,sc*n,&Y[c+n*2*C],2*C,&Y[C+c],2*C); //future samps cblas_saxpy(n,sc*n,&Y[c+2*C*(R-1)],0,&Y[C+c+2*C*(R-n)],2*C); //end edge samps } } } } else if (dim==1) { if (iscolmajor) { for (r=0; r<R; r++) { for (n=1; n<=N; n++) { cblas_saxpy(n,-sc*n,&X[r],0,&Y[r],2*R); //beg edge samps cblas_saxpy(C-n,-sc*n,&X[r],R,&Y[r+n*2*R],2*R); //past samps cblas_saxpy(C-n,sc*n,&X[r+n*R],R,&Y[r],2*R); //future samps cblas_saxpy(n,sc*n,&X[r+R*(C-1)],0,&Y[r+2*R*(C-n)],2*R); //end edge samps } for (n=1; n<=N; n++) { cblas_saxpy(n,-sc*n,&Y[r],0,&Y[R+r],2*R); //beg edge samps cblas_saxpy(C-n,-sc*n,&Y[r],2*R,&Y[R+r+n*2*R],2*R); //past samps cblas_saxpy(C-n,sc*n,&Y[r+n*2*R],2*R,&Y[R+r],2*R); //future samps cblas_saxpy(n,sc*n,&Y[r+2*R*(C-1)],0,&Y[R+r+2*R*(C-n)],2*R); //end edge samps } } } else { for (r=0; r<R; r++) { for (n=1; n<=N; n++) { cblas_saxpy(n,-sc*n,&X[r*C],0,&Y[r*C],1); //beg edge samps cblas_saxpy(C-n,-sc*n,&X[r*C],1,&Y[r*C+n],1); //past samps cblas_saxpy(C-n,sc*n,&X[r*C+n],1,&Y[r*C],1); //future samps cblas_saxpy(n,sc*n,&X[r*C+C-1],0,&Y[r*C+C-n],1); //end edge samps } for (n=1; n<=N; n++) { cblas_saxpy(n,-sc*n,&Y[r*C],0,&Y[R*C+r*C],1); //beg edge samps cblas_saxpy(C-n,-sc*n,&Y[r*C],1,&Y[R*C+r*C+n],1); //past samps cblas_saxpy(C-n,sc*n,&Y[r*C+n],1,&Y[R*C+r*C],1); //future samps cblas_saxpy(n,sc*n,&Y[r*C+C-1],0,&Y[R*C+r*C+C-n],1); //end edge samps } } } } else { fprintf(stderr,"error in get_delta_deltas_s: dim must be 0 or 1.\n"); return 1; } return 0; } int get_delta_deltas_d (double *Y, const double *X, const int iscolmajor, const int R, const int C, const int dim, const int N) { const double z = 0.0; int r, c, n; double sc = 1.0; //Checks if (R<1) { fprintf(stderr,"error in get_delta_deltas_d: R (nrows Y) must be positive\n"); return 1; } if (C<1) { fprintf(stderr,"error in get_delta_deltas_d: C (ncols Y) must be positive\n"); return 1; } if (N<1) { fprintf(stderr,"error in get_delta_deltas_d: N (delta winlength) must be positive\n"); return 1; } //Get sc (normalizer) for (n=2; n<=N; n++) { sc += n*n; } sc = 0.5/sc; //Initialize Y cblas_dcopy(2*R*C,&z,0,&Y[0],1); if (dim==0) { if (iscolmajor) { for (c=0; c<C; c++) { for (n=1; n<=N; n++) { cblas_daxpy(n,-sc*n,&X[c*R],0,&Y[c*R],1); //beg edge samps cblas_daxpy(R-n,-sc*n,&X[c*R],1,&Y[c*R+n],1); //past samps cblas_daxpy(R-n,sc*n,&X[c*R+n],1,&Y[c*R],1); //future samps cblas_daxpy(n,sc*n,&X[c*R+R-1],0,&Y[c*R+R-n],1); //end edge samps } for (n=1; n<=N; n++) { cblas_daxpy(n,-sc*n,&Y[c*R],0,&Y[R*C+c*R],1); //beg edge samps cblas_daxpy(R-n,-sc*n,&Y[c*R],1,&Y[R*C+c*R+n],1); //past samps cblas_daxpy(R-n,sc*n,&Y[c*R+n],1,&Y[R*C+c*R],1); //future samps cblas_daxpy(n,sc*n,&Y[c*R+R-1],0,&Y[R*C+c*R+R-n],1); //end edge samps } } } else { for (c=0; c<C; c++) { for (n=1; n<=N; n++) { cblas_daxpy(n,-sc*n,&X[c],0,&Y[c],2*C); //beg edge samps cblas_daxpy(R-n,-sc*n,&X[c],C,&Y[c+n*2*C],2*C); //past samps cblas_daxpy(R-n,sc*n,&X[c+n*C],C,&Y[c],2*C); //future samps cblas_daxpy(n,sc*n,&X[c+C*(R-1)],0,&Y[c+2*C*(R-n)],2*C); //end edge samps } for (n=1; n<=N; n++) { cblas_daxpy(n,-sc*n,&Y[c],0,&Y[C+c],2*C); //beg edge samps cblas_daxpy(R-n,-sc*n,&Y[c],2*C,&Y[C+c+n*2*C],2*C); //past samps cblas_daxpy(R-n,sc*n,&Y[c+n*2*C],2*C,&Y[C+c],2*C); //future samps cblas_daxpy(n,sc*n,&Y[c+2*C*(R-1)],0,&Y[C+c+2*C*(R-n)],2*C); //end edge samps } } } } else if (dim==1) { if (iscolmajor) { for (r=0; r<R; r++) { for (n=1; n<=N; n++) { cblas_daxpy(n,-sc*n,&X[r],0,&Y[r],2*R); //beg edge samps cblas_daxpy(C-n,-sc*n,&X[r],R,&Y[r+n*2*R],2*R); //past samps cblas_daxpy(C-n,sc*n,&X[r+n*R],R,&Y[r],2*R); //future samps cblas_daxpy(n,sc*n,&X[r+R*(C-1)],0,&Y[r+2*R*(C-n)],2*R); //end edge samps } for (n=1; n<=N; n++) { cblas_daxpy(n,-sc*n,&Y[r],0,&Y[R+r],2*R); //beg edge samps cblas_daxpy(C-n,-sc*n,&Y[r],2*R,&Y[R+r+n*2*R],2*R); //past samps cblas_daxpy(C-n,sc*n,&Y[r+n*2*R],2*R,&Y[R+r],2*R); //future samps cblas_daxpy(n,sc*n,&Y[r+2*R*(C-1)],0,&Y[R+r+2*R*(C-n)],2*R); //end edge samps } } } else { for (r=0; r<R; r++) { for (n=1; n<=N; n++) { cblas_daxpy(n,-sc*n,&X[r*C],0,&Y[r*C],1); //beg edge samps cblas_daxpy(C-n,-sc*n,&X[r*C],1,&Y[r*C+n],1); //past samps cblas_daxpy(C-n,sc*n,&X[r*C+n],1,&Y[r*C],1); //future samps cblas_daxpy(n,sc*n,&X[r*C+C-1],0,&Y[r*C+C-n],1); //end edge samps } for (n=1; n<=N; n++) { cblas_daxpy(n,-sc*n,&Y[r*C],0,&Y[R*C+r*C],1); //beg edge samps cblas_daxpy(C-n,-sc*n,&Y[r*C],1,&Y[R*C+r*C+n],1); //past samps cblas_daxpy(C-n,sc*n,&Y[r*C+n],1,&Y[R*C+r*C],1); //future samps cblas_daxpy(n,sc*n,&Y[r*C+C-1],0,&Y[R*C+r*C+C-n],1); //end edge samps } } } } else { fprintf(stderr,"error in get_delta_deltas_d: dim must be 0 or 1.\n"); return 1; } return 0; } #ifdef __cplusplus } } #endif
{ "alphanum_fraction": 0.4148078725, "avg_line_length": 41.3565891473, "ext": "c", "hexsha": "6bb37181782fdc7ab460bac3356e5d5f3fb66f9d", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "ee7adeb3b65d4ec45ad026cc915196b92c4b1c2b", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "erikedwards4/aud", "max_forks_repo_path": "c/get_delta_deltas.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "ee7adeb3b65d4ec45ad026cc915196b92c4b1c2b", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "erikedwards4/aud", "max_issues_repo_path": "c/get_delta_deltas.c", "max_line_length": 128, "max_stars_count": null, "max_stars_repo_head_hexsha": "ee7adeb3b65d4ec45ad026cc915196b92c4b1c2b", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "erikedwards4/aud", "max_stars_repo_path": "c/get_delta_deltas.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3507, "size": 10670 }
#include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <math.h> #include <gsl/gsl_errno.h> #include "ccl.h" // Debug mode policy: whether to print error messages as they are raised. // Defualt is ON. static CCLDebugModePolicy _ccl_debug_mode_policy = CCL_DEBUG_MODE_ON; // Set debug mode policy void ccl_set_debug_policy(CCLDebugModePolicy debug_policy) { _ccl_debug_mode_policy = debug_policy; } // Convenience function to handle warnings void ccl_raise_warning(int err, const char* msg, ...) { char message[256]; va_list va; va_start(va, msg); vsnprintf(message, 250, msg, va); va_end(va); // For now just print warning to stderr if debug is enabled. // TODO: Implement some kind of error stack that can be passed on to, e.g., // the python binding. if (_ccl_debug_mode_policy == CCL_DEBUG_MODE_ON) { fprintf(stderr, "WARNING %d: %s\n", err, message); } } // Convenience function to handle warnings void ccl_raise_gsl_warning(int gslstatus, const char* msg, ...) { char message[256]; va_list va; va_start(va, msg); vsnprintf(message, 250, msg, va); va_end(va); ccl_raise_warning(gslstatus, "%s: GSL ERROR: %s", message, gsl_strerror(gslstatus)); return; }
{ "alphanum_fraction": 0.7154538021, "avg_line_length": 25.4791666667, "ext": "c", "hexsha": "4ffbb0552df9d5e6382173b4fabd8d0640780433", "lang": "C", "max_forks_count": 54, "max_forks_repo_forks_event_max_datetime": "2022-02-06T13:12:10.000Z", "max_forks_repo_forks_event_min_datetime": "2017-07-12T13:08:25.000Z", "max_forks_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "Jappenn/CCL", "max_forks_repo_path": "src/ccl_error.c", "max_issues_count": 703, "max_issues_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_issues_repo_issues_event_max_datetime": "2022-03-30T14:40:10.000Z", "max_issues_repo_issues_event_min_datetime": "2017-07-07T16:27:17.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "Jappenn/CCL", "max_issues_repo_path": "src/ccl_error.c", "max_line_length": 86, "max_stars_count": 91, "max_stars_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "Jappenn/CCL", "max_stars_repo_path": "src/ccl_error.c", "max_stars_repo_stars_event_max_datetime": "2022-03-28T08:55:54.000Z", "max_stars_repo_stars_event_min_datetime": "2017-07-14T02:45:59.000Z", "num_tokens": 334, "size": 1223 }
#include "asf.h" #include "asf_meta.h" #include "dateUtil.h" #include <assert.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_multiroots.h> static FILE *fopen_workreport_ext(const char *fileName, report_level_t level) { char *path = getPath(fileName); char *basename = get_basename(fileName); char *txtFile = MALLOC(sizeof(char) * (strlen(path)+strlen(fileName)+20)); char *p; if (strncmp_case(basename, "LED-", 4)==0) p = basename + 4; else p = basename; if (strlen(path) > 0) sprintf(txtFile, "%s/%s", path, p); else strcpy(txtFile, p); char *workreport_filename = appendExt(txtFile, ".txt"); // first attempt: basename.txt FILE *fp; if (!fileExists(workreport_filename)) { // second attempt: path/'workreport' FREE(workreport_filename); workreport_filename = MALLOC(sizeof(char) * (strlen(path) + 20)); if (strlen(path) > 0) sprintf(workreport_filename, "%s/workreport", path); else strcpy(workreport_filename, "workreport"); if (!fileExists(workreport_filename)) { // third attempt: path/'summary.txt' if (strlen(path) > 0) sprintf(workreport_filename, "%s/summary.txt", path); else strcpy(workreport_filename, "summary.txt"); if (!fileExists(workreport_filename)) { // failed! fp = NULL; } else { // success with 'summary.txt' asfReport(level, "workreport file found as: summary.txt\n"); fp = FOPEN(workreport_filename, "r"); } } else { // success with 'workreport' asfReport(level, "workreport file found as: workreport\n"); fp = FOPEN(workreport_filename, "r"); } } else { // success with 'basename.txt' char *basename = get_basename(workreport_filename); asfReport(level, "workreport file found as: %s\n", basename); fp = FOPEN(workreport_filename, "r"); FREE(basename); } FREE(workreport_filename); FREE(txtFile); FREE(path); FREE(basename); return fp; } FILE *fopen_workreport(const char *fileName) { return fopen_workreport_ext(fileName, REPORT_LEVEL_STATUS); } // Get the delta image time for ALOS data out of the summary file int get_alos_delta_time (const char *fileName, double *delta) { struct dataset_sum_rec dssr; hms_time dssr_time, summary_time, start_time, end_time; ymd_date dssr_date, summary_date, start_date, end_date; char line[512], dateStr[30], *str; get_dssr(fileName, &dssr); date_dssr2date(dssr.inp_sctim, &dssr_date, &dssr_time); FILE *fp = fopen_workreport(fileName); if (!fp) { // no workreport file... *delta = 0; return FALSE; } while (fgets(line, 512, fp)) { if (strstr(line, "Img_SceneCenterDateTime")) { str = strchr(line, '"'); sprintf(dateStr, "%s", str+1); dateStr[strlen(dateStr)-2] = '\0'; date_alos2date(dateStr, &summary_date, &summary_time); // bumped up the tolerance to 2 seconds... can't see how this would // introduce any false positives, and definitely reduces false negatives if (date_difference(&dssr_date, &dssr_time, &summary_date, &summary_time) > 2.0) { asfPrintWarning("Summary file does not correspond to leader file.\n" "DSSR: %s\nSummary: %s\n", dssr.inp_sctim, dateStr); *delta = 0; FCLOSE(fp); return FALSE; } } else if (strstr(line, "Img_SceneStartDateTime")) { str = strchr(line, '"'); sprintf(dateStr, "%s", str+1); dateStr[strlen(dateStr)-2] = '\0'; date_alos2date(dateStr, &start_date, &start_time); } else if (strstr(line, "Img_SceneEndDateTime")) { str = strchr(line, '"'); sprintf(dateStr, "%s", str+1); dateStr[strlen(dateStr)-2] = '\0'; date_alos2date(dateStr, &end_date, &end_time); } } *delta = date_difference(&start_date, &start_time, &end_date, &end_time); FCLOSE(fp); return TRUE; } // Get the SAR processor version from the workreport int get_alos_processor_version (const char *fileName, double *version) { char line[512], versionStr[10], *str; FILE *fp = fopen_workreport_ext(fileName, REPORT_LEVEL_NONE); if (!fp) { // no workreport file... *version = 0.0; return FALSE; } while (fgets(line, 512, fp)) { if (strstr(line, "Ver_PSR_CorPrcSigmaSAR")) { str = strchr(line, '"'); sprintf(versionStr, "%s", str+1); versionStr[strlen(versionStr)-2] = '\0'; *version = atof(versionStr); } } FCLOSE(fp); return TRUE; } // ------------------------------------------------------------------------ // helper code for refine_slc_geolocation_from_workreport() struct refine_shift_params { meta_parameters *meta; double center_lat, center_lon; double ul_lat, ul_lon; double ur_lat, ur_lon; double ll_lat, ll_lon; double lr_lat, lr_lon; }; static double lldist(double lat1, double lat2, double lon1, double lon2) { double dlat = lat1 - lat2; double dlon; // some kludgery to handle crossing the meridian // get lat1,lon1 to be on the same side as lat2,lon2 if (fabs(lon1-lon2) > 300) { if (lon2 < 0 && lon1 > 0) lon1 -= 360; if (lon2 > 0 && lon1 < 0) lon1 += 360; } dlon = lon1 - lon2; // Scale longitude difference to take into accound the fact // that longitude lines are a lot closer at the pole. dlon *= cos (lat2 * PI / 180.0); return dlat * dlat + dlon * dlon; } static double err_at_pixel(struct refine_shift_params *p, double off_t, double off_x, double line, double samp, double real_lat, double real_lon) { const double huge_err = 999999.9; meta_parameters *meta = p->meta; double lat, lon; int bad=0; bad = meta_get_latLon(meta, line, samp, 0.0, &lat, &lon); if (bad) return huge_err; return lldist(lat, real_lat, lon, real_lon); } static int getObjective(const gsl_vector *x, void *params, gsl_vector *f) { double dt = gsl_vector_get(x,0); double ds = gsl_vector_get(x,1); if (!meta_is_valid_double(ds) || !meta_is_valid_double(dt)) { // This does happen sometimes, when we've already found the root return GSL_FAILURE; } struct refine_shift_params *p = (struct refine_shift_params *)params; meta_parameters *meta = p->meta; int nl = meta->general->line_count; int ns = meta->general->sample_count; double saved_timeOffset = meta->sar->time_shift; double saved_slant = meta->sar->slant_shift; meta->sar->time_shift += dt; meta->sar->slant_shift += ds; double err = 0.0; // add up the errors for the 5 known points err += err_at_pixel(p, dt, ds, nl/2, ns/2, p->center_lat, p->center_lon); if (meta->general->orbit_direction=='A') { err += err_at_pixel(p, dt, ds, 0, 0, p->ll_lat, p->ll_lon); err += err_at_pixel(p, dt, ds, nl-1, 0, p->ul_lat, p->ul_lon); err += err_at_pixel(p, dt, ds, 0, ns-1, p->lr_lat, p->lr_lon); err += err_at_pixel(p, dt, ds, nl-1, ns-1, p->ur_lat, p->ur_lon); } else { err += err_at_pixel(p, dt, ds, 0, 0, p->ul_lat, p->ur_lon); err += err_at_pixel(p, dt, ds, nl-1, 0, p->ll_lat, p->lr_lon); err += err_at_pixel(p, dt, ds, 0, ns-1, p->ur_lat, p->ul_lon); err += err_at_pixel(p, dt, ds, nl-1, ns-1, p->lr_lat, p->ll_lon); } meta->sar->time_shift = saved_timeOffset; meta->sar->slant_shift = saved_slant; gsl_vector_set(f,0,err); gsl_vector_set(f,1,err); return GSL_SUCCESS; } static void coarse_search(double t_extent_min, double t_extent_max, double s_extent_min, double s_extent_max, double *t_min, double *s_min, struct refine_shift_params *params) { double the_min = 9999999; double min_t=99, min_s=99; int i,j,k=6; double t_extent = t_extent_max - t_extent_min; double s_extent = s_extent_max - s_extent_min; gsl_vector *v = gsl_vector_alloc(2); gsl_vector *u = gsl_vector_alloc(2); //printf(" "); //for (j = 0; j <= k; ++j) { // double s = s_extent_min + ((double)j)/k*s_extent; // printf("%9.3f ", s); //} //printf("\n "); //for (j = 0; j <= k; ++j) // printf("--------- "); //printf("\n"); for (i = 0; i <= k; ++i) { double t = t_extent_min + ((double)i)/k*t_extent; //printf("%9.3f | ", t); for (j = 0; j <= k; ++j) { double s = s_extent_min + ((double)j)/k*s_extent; gsl_vector_set(v, 0, t); gsl_vector_set(v, 1, s); getObjective(v,(void*)params, u); double n = gsl_vector_get(u,0); //printf("%9.3f ", n); if (n<the_min) { the_min=n; min_t=gsl_vector_get(v,0); min_s=gsl_vector_get(v,1); } } //printf("\n"); } *t_min = min_t; *s_min = min_s; gsl_vector_free(v); gsl_vector_free(u); } /* this one can be used to do a time-only search (no slant adjustment) static void coarse_search_t(double t_extent_min, double t_extent_max, double *t_min, struct refine_shift_params *params) { double the_min = 9999999; double min_t=99; int i,k=10; double t_extent = t_extent_max - t_extent_min; gsl_vector *v = gsl_vector_alloc(2); gsl_vector *u = gsl_vector_alloc(2); for (i = 0; i <= k; ++i) { double t = t_extent_min + ((double)i)/k*t_extent; gsl_vector_set(v, 0, t); gsl_vector_set(v, 1, 0); getObjective(v,(void*)params, u); double n = gsl_vector_get(u,0); if (n<the_min) { the_min=n; min_t=gsl_vector_get(v,0); } } *t_min = min_t; gsl_vector_free(v); gsl_vector_free(u); } */ static void generate_start(struct refine_shift_params *params, double *start_t, double *start_s) { int i; double extent_t_min = -20; double extent_t_max = 20; double extent_s_min = -5000; double extent_s_max = 5000; double t_range = extent_t_max - extent_t_min; double s_range = extent_s_max - extent_s_min; for (i = 0; i < 12; ++i) { coarse_search(extent_t_min, extent_t_max, extent_s_min, extent_s_max, start_t, start_s, params); //coarse_search_t(extent_t_min, extent_t_max, start_t, params); t_range /= 3; s_range /= 3; extent_t_min = *start_t - t_range/2; extent_t_max = *start_t + t_range/2; extent_s_min = *start_s - s_range/2; extent_s_max = *start_s + s_range/2; //printf("refining search to region: (%9.3f,%9.3f)\n" // " (%9.3f,%9.3f)\n", // extent_t_min, extent_t_max, // extent_s_min, extent_s_max); } } /* small debug func static void print_state(int iter, gsl_multiroot_fsolver *s) { printf("iter = %3d x = (%.3f %.3f) f(x) = %.8f\n", iter, gsl_vector_get(s->x, 0), gsl_vector_get(s->x, 1), gsl_vector_get(s->f, 0)); } */ // This won't change the passed-in metadata -- afterwards, if you want // to apply the found corrections, do this: // meta->sar->slant_shift += slant_shift_adjustment; // meta->sar->time_shift += time_shift_adjustment; // usually you will only want to do this if the function returns TRUE // (on success), though if it returns FALSE (failed) these two parameters // will be 0 int refine_slc_geolocation_from_workreport(const char *metaName, const char *basename, meta_parameters *meta, double *time_shift_adjustment, double *slant_shift_adjustment) { char *fileName = MALLOC(sizeof(char)*(10+strlen(basename)+strlen(metaName))); char *dirname = get_dirname(metaName); if (strlen(dirname)>0) sprintf(fileName, "%s%s", dirname, basename); else strcpy(fileName, basename); FILE *fp = fopen_workreport(fileName); FREE(dirname); if (!fp) { // failed to open workreport file asfPrintWarning( "Attempted to refine the geolocation with the workreport file. However,\n" "this file could not be found. To get the most accurate geolocations with\n" "Palsar SLC data, include the workreport file in the same directory as the\n" "data file. First <basename>.txt is checked, then 'workreport'.\n\n" "Proceeding... however, extremely poor geolocations may result.\n"); *slant_shift_adjustment = 0.0; *time_shift_adjustment = 0.0; FREE(fileName); return FALSE; } // Read the workreport file, find the 4 corners and scene center // lat and long info. We also check to make sure this is the right // workreport file... struct dataset_sum_rec dssr; hms_time dssr_time, summary_time; ymd_date dssr_date, summary_date; char line[512], tmp[512], *p; get_dssr(metaName, &dssr); date_dssr2date(dssr.inp_sctim, &dssr_date, &dssr_time); double center_lat=-999, center_lon=-999; double ul_lat=-999, ul_lon=-999; double ur_lat=-999, ur_lon=-999; double ll_lat=-999, ll_lon=-999; double lr_lat=-999, lr_lon=-999; while (fgets(line, 512, fp)) { if (strstr(line, "Img_SceneCenterDateTime")) { p = strchr(line, '"'); sprintf(tmp, "%s", p+1); tmp[strlen(tmp)-2] = '\0'; date_alos2date(tmp, &summary_date, &summary_time); if (date_difference(&dssr_date, &dssr_time, &summary_date, &summary_time) > 10.0) { asfPrintWarning( "Summary file does not correspond to leader file.\n" " DSSR: %s\n Summary: %s\n" "This is most likely because you have a mismatched workreport file. Since\n" "by default these files are all named 'workreport' this file may have been\n" "overwritten with another scene's workreport file. You may wish to rename\n" "your workreport files using the <basename>.txt convention, for example:\n" " %s.txt\n" "Proceeding... however, extremely poor geolocations may result.\n", dssr.inp_sctim, tmp, fileName); *slant_shift_adjustment = 0; *time_shift_adjustment = 0; FCLOSE(fp); FREE(fileName); return 0; } } else if (strstr(line, "ImageSceneCenterLatitude")) { p = strchr(line, '"'); if (p) center_lat = atof(p+1); } else if (strstr(line, "ImageSceneCenterLongitude")) { p = strchr(line, '"'); if (p) center_lon = atof(p+1); } else if (strstr(line, "ImageSceneLeftTopLatitude")) { p = strchr(line, '"'); if (p) ul_lat = atof(p+1); } else if (strstr(line, "ImageSceneLeftTopLongitude")) { p = strchr(line, '"'); if (p) ul_lon = atof(p+1); } else if (strstr(line, "ImageSceneRightTopLatitude")) { p = strchr(line, '"'); if (p) ur_lat = atof(p+1); } else if (strstr(line, "ImageSceneRightTopLongitude")) { p = strchr(line, '"'); if (p) ur_lon = atof(p+1); } else if (strstr(line, "ImageSceneLeftBottomLatitude")) { p = strchr(line, '"'); if (p) ll_lat = atof(p+1); } else if (strstr(line, "ImageSceneLeftBottomLongitude")) { p = strchr(line, '"'); if (p) ll_lon = atof(p+1); } else if (strstr(line, "ImageSceneRightBottomLatitude")) { p = strchr(line, '"'); if (p) lr_lat = atof(p+1); } else if (strstr(line, "ImageSceneRightBottomLongitude")) { p = strchr(line, '"'); if (p) lr_lon = atof(p+1); } } FREE(fileName); fclose(fp); // Did we get all that we needed? int ok = TRUE; if (center_lat == -999) { asfPrintStatus("Missing: ImageSceneCenterLatitude\n"); ok = FALSE; } if (center_lon == -999) { asfPrintStatus("Missing: ImageSceneCenterLongitude\n"); ok = FALSE; } if (ul_lat == -999) { asfPrintStatus("Missing: ImageSceneTopLeftLatitude\n"); ok = FALSE; } if (ul_lon == -999) { asfPrintStatus("Missing: ImageSceneTopLeftLongitude\n"); ok = FALSE; } if (ur_lat == -999) { asfPrintStatus("Missing: ImageSceneTopRightLatitude\n"); ok = FALSE; } if (ur_lon == -999) { asfPrintStatus("Missing: ImageSceneTopRightLongitude\n"); ok = FALSE; } if (ll_lat == -999) { asfPrintStatus("Missing: ImageSceneBottomLeftLatitude\n"); ok = FALSE; } if (ll_lon == -999) { asfPrintStatus("Missing: ImageSceneBottomLeftLongitude\n"); ok = FALSE; } if (lr_lat == -999) { asfPrintStatus("Missing: ImageSceneBottomRightLatitude\n"); ok = FALSE; } if (lr_lon == -999) { asfPrintStatus("Missing: ImageSceneBottomRightLongitude\n"); ok = FALSE; } if (!ok) { asfPrintWarning("Not all necessary information is available in the " "workreport file.\nProceeding... however, extremely " "poor geolocations may result.\n"); *slant_shift_adjustment = 0.0; *time_shift_adjustment = 0.0; return FALSE; } // all required info is present-- search for min slant and time shifts struct refine_shift_params params; params.meta = meta; params.center_lat = center_lat; params.center_lon = center_lon; params.ul_lat = ul_lat; params.ul_lon = ul_lon; params.ur_lat = ur_lat; params.ur_lon = ur_lon; params.ll_lat = ll_lat; params.ll_lon = ll_lon; params.lr_lat = lr_lat; params.lr_lon = lr_lon; //int status; //int iter = 0, max_iter = 1000; //const gsl_multiroot_fsolver_type *T; //gsl_multiroot_fsolver *s; //gsl_error_handler_t *prev; //const size_t n = 2; //gsl_multiroot_function F = {&getObjective, n, &params}; //gsl_vector *x = gsl_vector_alloc(n); double start_t, start_s; generate_start(&params, &start_t, &start_s); //printf("Starting point at (%f, %f)\n", start_t, start_s); /* gsl_vector_set (x, 0, start_t); gsl_vector_set (x, 1, start_s); T = gsl_multiroot_fsolver_hybrid; s = gsl_multiroot_fsolver_alloc(T, n); gsl_multiroot_fsolver_set(s, &F, x); prev = gsl_set_error_handler_off(); do { ++iter; status = gsl_multiroot_fsolver_iterate(s); //print_state(iter, s); // abort if stuck if (status) break; status = gsl_multiroot_test_residual (s->f, 1e-8); } while (status == GSL_CONTINUE && iter < max_iter); *time_shift_adjustment = gsl_vector_get(s->x, 0); *slant_shift_adjustment = gsl_vector_get(s->x, 1); gsl_vector *retrofit = gsl_vector_alloc(n); gsl_vector_set(retrofit, 0, *time_shift_adjustment); gsl_vector_set(retrofit, 1, *slant_shift_adjustment); gsl_vector *output = gsl_vector_alloc(n); getObjective(retrofit, (void*)&params, output); double val= gsl_vector_get(output,0); printf("GSL Result: %f at (%f,%f)\n", val, *time_shift_adjustment, *slant_shift_adjustment); gsl_vector_free(retrofit); gsl_vector_free(output); gsl_multiroot_fsolver_free(s); gsl_vector_free(x); gsl_set_error_handler(prev); */ *time_shift_adjustment = start_t; *slant_shift_adjustment = start_s; // the rest of this is a bunch of debug code /* int nl = meta->general->line_count; int ns = meta->general->sample_count; double lat,lon; if (meta->general->orbit_direction=='A') { printf("BEFORE-->\n"); meta_get_latLon(meta, nl/2, ns/2, 0, &lat, &lon); printf(" CN: mgll: %f,%f - wr:%f,%f - err:%f\n", lat,lon,center_lat,center_lon, lldist(lat,center_lat,lon,center_lon)); meta_get_latLon(meta, nl-1, 0, 0, &lat, &lon); printf(" UL: mgll: %f,%f - wr:%f,%f - err:%f\n", lat,lon,ul_lat,ul_lon,lldist(lat,ul_lat,lon,ul_lon)); meta_get_latLon(meta, nl-1, ns-1, 0, &lat, &lon); printf(" UR: mgll: %f,%f - wr:%f,%f - err:%f\n", lat,lon,ur_lat,ur_lon,lldist(lat,ur_lat,lon,ur_lon)); meta_get_latLon(meta, 0, 0, 0, &lat, &lon); printf(" LL: mgll: %f,%f - wr:%f,%f - err:%f\n", lat,lon,ll_lat,ll_lon,lldist(lat,ll_lat,lon,ll_lon)); meta_get_latLon(meta, 0, ns-1, 0, &lat, &lon); printf(" LR: mgll: %f,%f - wr:%f,%f - err:%f\n", lat,lon,lr_lat,lr_lon,lldist(lat,lr_lat,lon,lr_lon)); double saved_timeOffset = meta->sar->time_shift; double saved_slant = meta->sar->slant_shift; meta->sar->time_shift += *time_shift_adjustment; meta->sar->slant_shift += *slant_shift_adjustment; printf("AFTER-->\n"); meta_get_latLon(meta, nl/2, ns/2, 0, &lat, &lon); printf(" CN: mgll: %f,%f - wr:%f,%f - err:%f\n", lat,lon,center_lat,center_lon, lldist(lat,center_lat,lon,center_lon)); meta_get_latLon(meta, nl-1, 0, 0, &lat, &lon); printf(" UL: mgll: %f,%f - wr:%f,%f - err:%f\n", lat,lon,ul_lat,ul_lon,lldist(lat,ul_lat,lon,ul_lon)); meta_get_latLon(meta, nl-1, ns-1, 0, &lat, &lon); printf(" UR: mgll: %f,%f - wr:%f,%f - err:%f\n", lat,lon,ur_lat,ur_lon,lldist(lat,ur_lat,lon,ur_lon)); meta_get_latLon(meta, 0, 0, 0, &lat, &lon); printf(" LL: mgll: %f,%f - wr:%f,%f - err:%f\n", lat,lon,ll_lat,ll_lon,lldist(lat,ll_lat,lon,ll_lon)); meta_get_latLon(meta, 0, ns-1, 0, &lat, &lon); printf(" LR: mgll: %f,%f - wr:%f,%f - err:%f\n", lat,lon,lr_lat,lr_lon,lldist(lat,lr_lat,lon,lr_lon)); meta->sar->time_shift = saved_timeOffset; meta->sar->slant_shift = saved_slant; } else { printf("BEFORE-->\n"); meta_get_latLon(meta, nl/2, ns/2, 0, &lat, &lon); printf(" CN: mgll: %f,%f - wr:%f,%f - err:%f\n", lat,lon,center_lat,center_lon, lldist(lat,center_lat,lon,center_lon)); meta_get_latLon(meta, 0, ns-1, 0, &lat, &lon); printf(" UL: mgll: %f,%f - wr:%f,%f - err:%f\n", lat,lon,ul_lat,ul_lon,lldist(lat,ul_lat,lon,ul_lon)); meta_get_latLon(meta, 0, 0, 0, &lat, &lon); printf(" UR: mgll: %f,%f - wr:%f,%f - err:%f\n", lat,lon,ur_lat,ur_lon,lldist(lat,ur_lat,lon,ur_lon)); meta_get_latLon(meta, nl-1, ns-1, 0, &lat, &lon); printf(" LL: mgll: %f,%f - wr:%f,%f - err:%f\n", lat,lon,ll_lat,ll_lon,lldist(lat,ll_lat,lon,ll_lon)); meta_get_latLon(meta, nl-1, 0, 0, &lat, &lon); printf(" LR: mgll: %f,%f - wr:%f,%f - err:%f\n", lat,lon,lr_lat,lr_lon,lldist(lat,lr_lat,lon,lr_lon)); double saved_timeOffset = meta->sar->time_shift; double saved_slant = meta->sar->slant_shift; meta->sar->time_shift += *time_shift_adjustment; meta->sar->slant_shift += *slant_shift_adjustment; printf("AFTER-->\n"); meta_get_latLon(meta, nl/2, ns/2, 0, &lat, &lon); printf(" CN: mgll: %f,%f - wr:%f,%f - err:%f\n", lat,lon,center_lat,center_lon, lldist(lat,center_lat,lon,center_lon)); meta_get_latLon(meta, 0, ns-1, 0, &lat, &lon); printf(" UL: mgll: %f,%f - wr:%f,%f - err:%f\n", lat,lon,ul_lat,ul_lon,lldist(lat,ul_lat,lon,ul_lon)); meta_get_latLon(meta, 0, 0, 0, &lat, &lon); printf(" UR: mgll: %f,%f - wr:%f,%f - err:%f\n", lat,lon,ur_lat,ur_lon,lldist(lat,ur_lat,lon,ur_lon)); meta_get_latLon(meta, nl-1, ns-1, 0, &lat, &lon); printf(" LL: mgll: %f,%f - wr:%f,%f - err:%f\n", lat,lon,ll_lat,ll_lon,lldist(lat,ll_lat,lon,ll_lon)); meta_get_latLon(meta, nl-1, 0, 0, &lat, &lon); printf(" LR: mgll: %f,%f - wr:%f,%f - err:%f\n", lat,lon,lr_lat,lr_lon,lldist(lat,lr_lat,lon,lr_lon)); meta->sar->time_shift = saved_timeOffset; meta->sar->slant_shift = saved_slant; } */ return TRUE; }
{ "alphanum_fraction": 0.6072779225, "avg_line_length": 32.2466124661, "ext": "c", "hexsha": "4e4f27b6de496cc66fe8d938636a3c7c013d67a5", "lang": "C", "max_forks_count": 7, "max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z", "max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z", "max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "glshort/MapReady", "max_forks_repo_path": "src/asf_meta/workreport.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "glshort/MapReady", "max_issues_repo_path": "src/asf_meta/workreport.c", "max_line_length": 79, "max_stars_count": 3, "max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "glshort/MapReady", "max_stars_repo_path": "src/asf_meta/workreport.c", "max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z", "max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z", "num_tokens": 7200, "size": 23798 }
// Copyright (C) 2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 #ifndef _HEBench_ClearText_EltAdd_H_7e5fa8c2415240ea93eff148ed73539b #define _HEBench_ClearText_EltAdd_H_7e5fa8c2415240ea93eff148ed73539b #include <gsl/gsl> #include "hebench/api_bridge/cpp/hebench.hpp" #include "clear_benchmark.h" template <class T> class EltAdd_Benchmark : public ClearTextBenchmark { private: HEBERROR_DECLARE_CLASS_NAME(EltAdd_Benchmark) public: EltAdd_Benchmark(hebench::cpp::BaseEngine &engine, const hebench::APIBridge::BenchmarkDescriptor &bench_desc, const hebench::APIBridge::WorkloadParams &bench_params); ~EltAdd_Benchmark() override; hebench::APIBridge::Handle encode(const hebench::APIBridge::DataPackCollection *p_parameters) override; void decode(hebench::APIBridge::Handle encoded_data, hebench::APIBridge::DataPackCollection *p_native) override; hebench::APIBridge::Handle load(const hebench::APIBridge::Handle *p_local_data, std::uint64_t count) override; void store(hebench::APIBridge::Handle remote_data, hebench::APIBridge::Handle *p_local_data, std::uint64_t count) override; hebench::APIBridge::Handle operate(hebench::APIBridge::Handle h_remote_packed, const hebench::APIBridge::ParameterIndexer *p_param_indexers) override; protected: std::uint64_t m_vector_size; private: static void eltAdd(gsl::span<T> &result, const gsl::span<const T> &M0, const gsl::span<const T> &M1, std::size_t element_count); }; #include "inl/bench_eltadd.inl" #endif // defined _HEBench_ClearText_EltAdd_H_7e5fa8c2415240ea93eff148ed73539b
{ "alphanum_fraction": 0.7312572088, "avg_line_length": 36.125, "ext": "h", "hexsha": "07934aa3a428c0d3c7790bb28a6c541f49aa16c8", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-11-05T18:01:48.000Z", "max_forks_repo_forks_event_min_datetime": "2021-11-05T18:01:48.000Z", "max_forks_repo_head_hexsha": "83e4398d9271f3e077bb4dfc0a8fb04ce36e23f6", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "hebench/backend-cpu-cleartext", "max_forks_repo_path": "benchmarks/Vector/EltwiseAdd/include/bench_eltadd.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "83e4398d9271f3e077bb4dfc0a8fb04ce36e23f6", "max_issues_repo_issues_event_max_datetime": "2021-12-16T23:37:53.000Z", "max_issues_repo_issues_event_min_datetime": "2021-12-06T19:37:42.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "hebench/backend-cpu-cleartext", "max_issues_repo_path": "benchmarks/Vector/EltwiseAdd/include/bench_eltadd.h", "max_line_length": 116, "max_stars_count": 1, "max_stars_repo_head_hexsha": "83e4398d9271f3e077bb4dfc0a8fb04ce36e23f6", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "hebench/backend-cpu-cleartext", "max_stars_repo_path": "benchmarks/Vector/EltwiseAdd/include/bench_eltadd.h", "max_stars_repo_stars_event_max_datetime": "2022-02-28T17:57:32.000Z", "max_stars_repo_stars_event_min_datetime": "2022-02-28T17:57:32.000Z", "num_tokens": 464, "size": 1734 }
#include <gsl/gsl_statistics_double.h> #include "qdm.h" gsl_matrix * qdm_bias_values( qdm_evaluation *h, qdm_evaluation *f ) { size_t n = f->mcmc->r.tau->size2; size_t s = f->mcmc->r.s; double tau_low = h->parameters.tau_low; double tau_high = h->parameters.tau_high; double lower_bound = h->lower_bound; double upper_bound = h->upper_bound; gsl_matrix *r = gsl_matrix_calloc(n, s); fprintf(stderr, "r[%zu, %zu]\n", r->size1, r->size2 ); fprintf(stderr, "r.tau[%zu, %zu, %zu]\n", f->mcmc->r.tau->size1, f->mcmc->r.tau->size2, f->mcmc->r.tau->size3 ); fprintf(stderr, "r.theta[%zu, %zu, %zu]\n", f->mcmc->r.theta->size1, f->mcmc->r.theta->size2, f->mcmc->r.theta->size3 ); fprintf(stderr, "r.xi[%zu, %zu, %zu]\n", f->mcmc->r.xi->size1, f->mcmc->r.xi->size2, f->mcmc->r.xi->size3 ); for (size_t j = 0; j < n; j++) { for (size_t k = 0; k < s; k++) { double tau = qdm_ijk_get(f->mcmc->r.tau, 0, j, k); double value = 0; gsl_matrix_view theta = qdm_ijk_get_ij(h->mcmc->r.theta, k); gsl_vector_view mmm = gsl_matrix_row(&theta.matrix, 0); if (tau_low <= tau && tau <= tau_high) { value = qdm_tau_ispline_mmm( h->t, tau, &mmm.vector ); } else if (tau < tau_low) { double is = qdm_tau_ispline_mmm( h->t, tau_low, &mmm.vector ); double ms = qdm_tau_ispline_mmm( h->t, tau_low, &mmm.vector ); double xi_low = qdm_ijk_get(h->mcmc->r.xi, 0, 0, k); value = is - tau_low / ms * (pow(tau / tau_low, -xi_low) - 1); value = fmax(value, lower_bound); } else { // tau_high < tau double is = qdm_tau_ispline_mmm( h->t, tau_high, &mmm.vector ); double ms = qdm_tau_ispline_mmm( h->t, tau_high, &mmm.vector ); double xi_high = qdm_ijk_get(h->mcmc->r.xi, 0, 1, k); value = is - tau_high / ms * (pow((1 - tau) / (1 - tau_high), -xi_high) - 1); value = fmin(value, upper_bound); } gsl_matrix_set(r, j, k, value); } } return r; } gsl_matrix * qdm_bias_correct( const gsl_vector *years, const double month, const gsl_vector *days, const gsl_vector *y, qdm_evaluation *fp, qdm_evaluation *ho, qdm_evaluation *hc ) { gsl_matrix *hov = qdm_bias_values(ho, fp); gsl_matrix *hcv = qdm_bias_values(hc, fp); gsl_vector *row = gsl_vector_calloc(hov->size2); gsl_matrix *r = gsl_matrix_calloc(hov->size1, 5); fprintf(stderr, "years[%zu]\n", years->size); fprintf(stderr, "month %f\n", month); fprintf(stderr, "days[%zu]\n", days->size); fprintf(stderr, "y[%zu]\n", y->size); fprintf(stderr, "hov[%zu, %zu]\n", hov->size1, hov->size2); fprintf(stderr, "hcv[%zu, %zu]\n", hcv->size1, hcv->size2); fprintf(stderr, "row[%zu]\n", row->size); for (size_t i = 0; i < hov->size1; i++) { for (size_t j = 0; j < hov->size2; j++) { gsl_vector_set(row, j, gsl_matrix_get(hov, i, j) + (gsl_vector_get(y, i) - gsl_matrix_get(hcv, i, j))); double mean = gsl_stats_mean(row->data, row->stride, row->size); double sd = gsl_stats_sd(row->data, row->stride, row->size); gsl_matrix_set(r, i, 0, gsl_vector_get(years, i)); gsl_matrix_set(r, i, 1, month); gsl_matrix_set(r, i, 2, gsl_vector_get(days, i)); gsl_matrix_set(r, i, 3, mean); gsl_matrix_set(r, i, 4, sd); } } gsl_vector_free(row); gsl_matrix_free(hcv); gsl_matrix_free(hov); return r; }
{ "alphanum_fraction": 0.5562130178, "avg_line_length": 24.7866666667, "ext": "c", "hexsha": "e22cde43a63a98c0ad69688c8430bcd31854abe0", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "calebcase/qdm", "max_forks_repo_path": "src/bias.c", "max_issues_count": 3, "max_issues_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_issues_repo_issues_event_max_datetime": "2020-03-22T20:22:53.000Z", "max_issues_repo_issues_event_min_datetime": "2020-03-06T18:09:06.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "calebcase/qdm", "max_issues_repo_path": "src/bias.c", "max_line_length": 109, "max_stars_count": null, "max_stars_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "calebcase/qdm", "max_stars_repo_path": "src/bias.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1241, "size": 3718 }
#ifndef BANDED_FLOAT_IMAGE_H #define BANDED_FLOAT_IMAGE_H #include <stdio.h> #include <sys/types.h> #include <glib.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_histogram.h> #include "float_image.h" typedef struct { int nbands; FloatImage **images; } BandedFloatImage; BandedFloatImage * banded_float_image_new(int nbands, size_t size_x, size_t size_y); BandedFloatImage * banded_float_image_new_with_value(int nBands, ssize_t size_x, ssize_t size_y, float value); int banded_float_image_store (BandedFloatImage *self, const char *file, float_image_byte_order_t byte_order); void banded_float_image_free(BandedFloatImage *self); float banded_float_image_get_pixel(BandedFloatImage *self, int nband, ssize_t x, ssize_t y); void banded_float_image_set_pixel(BandedFloatImage *self, int nband, ssize_t x, ssize_t y, float value); FloatImage * banded_float_image_get_band(BandedFloatImage *self, int nband); BandedFloatImage * banded_float_image_new_from_model_scaled (BandedFloatImage *model, ssize_t scale_factor); void banded_float_image_export_as_jpeg(BandedFloatImage *self, const char *output_name); #endif
{ "alphanum_fraction": 0.7149496514, "avg_line_length": 23.9074074074, "ext": "h", "hexsha": "609b0d084c35c75ae41b5333f8edb4fa0d5ec4c3", "lang": "C", "max_forks_count": 7, "max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z", "max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z", "max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "glshort/MapReady", "max_forks_repo_path": "src/libasf_raster/banded_float_image.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "glshort/MapReady", "max_issues_repo_path": "src/libasf_raster/banded_float_image.h", "max_line_length": 78, "max_stars_count": 3, "max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "glshort/MapReady", "max_stars_repo_path": "src/libasf_raster/banded_float_image.h", "max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z", "max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z", "num_tokens": 311, "size": 1291 }
#pragma once #include <gsl\gsl> #include <winrt\Windows.Foundation.h> #include <d3d11.h> #include <map> #include "DrawableGameComponent.h" #include "FullScreenRenderTarget.h" #include "Bloom.h" namespace Rendering { class DiffuseLightingDemo; class BloomDemo final : public Library::DrawableGameComponent { public: BloomDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera); BloomDemo(const BloomDemo&) = delete; BloomDemo(BloomDemo&&) = default; BloomDemo& operator=(const BloomDemo&) = default; BloomDemo& operator=(BloomDemo&&) = default; ~BloomDemo(); std::shared_ptr<DiffuseLightingDemo> DiffuseLighting() const; bool BloomEnabled() const; void SetBloomEnabled(bool enabled); void ToggleBloom(); Library::BloomDrawModes DrawMode() const; const std::string& DrawModeString() const; void SetDrawMode(Library::BloomDrawModes drawMode); const Library::BloomSettings& GetBloomSettings() const; void SetBloomSettings(Library::BloomSettings& settings); virtual void Initialize() override; virtual void Update(const Library::GameTime& gameTime) override; virtual void Draw(const Library::GameTime& gameTime) override; private: std::shared_ptr<DiffuseLightingDemo> mDiffuseLightingDemo; Library::FullScreenRenderTarget mRenderTarget; Library::Bloom mBloom; bool mBloomEnabled{ true }; }; }
{ "alphanum_fraction": 0.7591240876, "avg_line_length": 28.5416666667, "ext": "h", "hexsha": "bf59c208e0d6d3f4fc01fdfae0719fefc226605f", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_path": "source/7.3_Bloom/BloomDemo.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_path": "source/7.3_Bloom/BloomDemo.h", "max_line_length": 81, "max_stars_count": null, "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_path": "source/7.3_Bloom/BloomDemo.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 361, "size": 1370 }
#include "compute_signal.h" #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_histogram.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #include "parameters.h" void compute_signal(double * signal, const size_t length, const double delta, gsl_rng * r, gsl_histogram * hist){ static double x0 = XINIT; puts("Building signal ..."); double x = x0; double t_begin = 0.0; //Distance from the beginning of time discretization //interval to current point in time for(size_t j=0; j<length; j++){ //Perfom integration using method of rectangles. double sum = 0.0; //Sum of signal areas double delta_t = t_begin; //part of time step in the new interval while(t_begin < delta) { sum += x*delta_t; double z = gsl_ran_gaussian_ziggurat(r,1.0); //Milstein approximation: x += 0.5*KAPPA*KAPPA*XMIN + KAPPA*x*z + 0.5*KAPPA*KAPPA*x*(z*z-1.0); //Euler-Marujama approximation: //x += 0.5*KAPPA*KAPPA*XMIN + KAPPA*x*z if(x > XOVER) {x = XINIT; puts("Too large");} if(x < 0) {x = -x; puts("Negative");} delta_t = KAPPA*KAPPA/(SIGMA*SIGMA*x); gsl_histogram_accumulate(hist, x, delta_t); t_begin += delta_t; //increase distance from the beginning } t_begin -= delta; /* remaining part of the time step is equal to the difference of the full * time step and of the part of the time step outside the interval. * Part outside the interval is t_begin */ sum += x*(delta_t - t_begin); signal[j] = sum/delta; //assign effective height to the signal. } x0 = x; }
{ "alphanum_fraction": 0.6378575776, "avg_line_length": 28.8245614035, "ext": "c", "hexsha": "91fafc8cb82d0883ba3127b778f042a1f469238a", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "6204ac9d212fd6c73751d215c49e95373b573430", "max_forks_repo_licenses": [ "Unlicense" ], "max_forks_repo_name": "JuliusRuseckas/numerical-sde-variable-step", "max_forks_repo_path": "compute_signal.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "6204ac9d212fd6c73751d215c49e95373b573430", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Unlicense" ], "max_issues_repo_name": "JuliusRuseckas/numerical-sde-variable-step", "max_issues_repo_path": "compute_signal.c", "max_line_length": 77, "max_stars_count": 2, "max_stars_repo_head_hexsha": "6204ac9d212fd6c73751d215c49e95373b573430", "max_stars_repo_licenses": [ "Unlicense" ], "max_stars_repo_name": "JuliusRuseckas/numerical-sde-variable-step", "max_stars_repo_path": "compute_signal.c", "max_stars_repo_stars_event_max_datetime": "2022-03-25T07:04:28.000Z", "max_stars_repo_stars_event_min_datetime": "2017-03-28T09:12:48.000Z", "num_tokens": 473, "size": 1643 }
// // Created by pedram pakseresht on 2/18/21. // #include <petsc.h> int main( int argc, char *argv[] ) { Vec a,b,c; DM packer; PetscErrorCode ierr; PetscInt i[4] = {0,1,2,3}; PetscReal v[4] = {1.5,2.5,3.5,4.5}; PetscReal w[4] = {5.5,6.5,7.5,8.5}; // initialize Petsc ... ierr = PetscInitialize(&argc, &argv, NULL, "");CHKERRQ(ierr); ierr= VecCreate(PETSC_COMM_WORLD, &a); CHKERRQ(ierr); ierr= VecCreate(PETSC_COMM_WORLD, &b); CHKERRQ(ierr); ierr= VecSetSizes(a,PETSC_DECIDE,4); CHKERRQ(ierr); ierr = VecSetFromOptions(a); CHKERRQ(ierr); ierr= VecSetValues(a,4,i,v,INSERT_VALUES);CHKERRQ(ierr); ierr= VecAssemblyBegin(a);CHKERRQ(ierr); ierr = VecAssemblyEnd(a);CHKERRQ(ierr); ierr = VecView(a,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr); ierr= VecSetSizes(b,PETSC_DECIDE,4); CHKERRQ(ierr); ierr = VecSetFromOptions(b); CHKERRQ(ierr); ierr= VecSetValues(b,4,i,w,INSERT_VALUES);CHKERRQ(ierr); ierr= VecAssemblyBegin(b);CHKERRQ(ierr); ierr = VecAssemblyEnd(b);CHKERRQ(ierr); ierr = VecView(b,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr); ierr = PetscFinalize();exit(ierr); }
{ "alphanum_fraction": 0.6555839727, "avg_line_length": 24.9574468085, "ext": "c", "hexsha": "0d87c0476290454ea28b83c7b138f818ffab5d76", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "c7bb7cf4a4ec706170efd7c06bf8589e30ece47b", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "pakserep/ablateClient", "max_forks_repo_path": "test_vec.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "c7bb7cf4a4ec706170efd7c06bf8589e30ece47b", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "pakserep/ablateClient", "max_issues_repo_path": "test_vec.c", "max_line_length": 65, "max_stars_count": null, "max_stars_repo_head_hexsha": "c7bb7cf4a4ec706170efd7c06bf8589e30ece47b", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "pakserep/ablateClient", "max_stars_repo_path": "test_vec.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 369, "size": 1173 }
/* MPCOTool: The Multi-Purposes Calibration and Optimization Tool. A software to perform calibrations or optimizations of empirical parameters. AUTHORS: Javier Burguete and Borja Latorre. Copyright 2012-2019, AUTHORS. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY AUTHORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * \file mpcotool.c * \brief Main function source file. * \authors Javier Burguete and Borja Latorre. * \copyright Copyright 2012-2019, all rights reserved. */ #define _GNU_SOURCE #include "config.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <getopt.h> #include <math.h> #include <locale.h> #include <gsl/gsl_rng.h> #include <libxml/parser.h> #include <libintl.h> #include <glib.h> #include <json-glib/json-glib.h> #ifdef G_OS_WIN32 #include <windows.h> #endif #if HAVE_MPI #include <mpi.h> #endif #if HAVE_GTK #include <gio/gio.h> #include <gtk/gtk.h> #endif #include "genetic/genetic.h" #include "utils.h" #include "experiment.h" #include "variable.h" #include "input.h" #include "optimize.h" #if HAVE_GTK #include "interface.h" #endif #include "mpcotool.h" #define DEBUG_MPCOTOOL 0 ///< Macro to debug main functions. GMutex mutex[1]; ///< GMutex struct. int ntasks; ///< Tasks number. unsigned int nthreads; ///< Threads number. /** * Main function. * * \return 0 on success, >0 on error. */ int mpcotool (int argn, ///< Arguments number. char **argc) ///< Arguments pointer. { const struct option options[] = { {"seed", required_argument, NULL, 's'}, {"nthreads", required_argument, NULL, 't'}, {NULL, 0, NULL, 0} }; #if HAVE_GTK GtkApplication *application; char *buffer; #endif int o, option_index; // Starting pseudo-random numbers generator #if DEBUG_MPCOTOOL fprintf (stderr, "mpcotool: starting pseudo-random numbers generator\n"); #endif optimize->rng = gsl_rng_alloc (gsl_rng_taus2); // Allowing spaces in the XML data file #if DEBUG_MPCOTOOL fprintf (stderr, "mpcotool: allowing spaces in the XML data file\n"); #endif xmlKeepBlanksDefault (0); // Starting MPI #if HAVE_MPI #if DEBUG_MPCOTOOL fprintf (stderr, "mpcotool: starting MPI\n"); #endif MPI_Init (&argn, &argc); MPI_Comm_size (MPI_COMM_WORLD, &ntasks); MPI_Comm_rank (MPI_COMM_WORLD, &optimize->mpi_rank); printf ("rank=%d tasks=%d\n", optimize->mpi_rank, ntasks); #else ntasks = 1; #endif // Getting threads number and pseudo-random numbers generator seed nthreads_climbing = nthreads = cores_number (); optimize->seed = DEFAULT_RANDOM_SEED; // Parsing command line arguments while (1) { o = getopt_long (argn, argc, "s:t:", options, &option_index); if (o == -1) break; switch (o) { case 's': optimize->seed = atol (optarg); break; case 't': nthreads_climbing = nthreads = atoi (optarg); break; default: printf ("%s\n%s\n", _("ERROR!"), _("Unknown option")); return 1; } } argn -= optind; // Resetting result and variables file names #if DEBUG_MPCOTOOL fprintf (stderr, "mpcotool: resetting result and variables file names\n"); #endif input->result = input->variables = NULL; #if HAVE_GTK // Setting local language and international floating point numbers notation setlocale (LC_ALL, ""); setlocale (LC_NUMERIC, "C"); window->application_directory = g_get_current_dir (); buffer = g_build_filename (window->application_directory, LOCALE_DIR, NULL); bindtextdomain (PROGRAM_INTERFACE, buffer); bind_textdomain_codeset (PROGRAM_INTERFACE, "UTF-8"); textdomain (PROGRAM_INTERFACE); // Initing GTK+ gtk_disable_setlocale (); application = gtk_application_new ("es.csic.eead.auladei.sprinkler", G_APPLICATION_FLAGS_NONE); g_signal_connect (application, "activate", G_CALLBACK (window_new), NULL); // Opening the main window g_application_run (G_APPLICATION (application), 0, NULL); // Freeing memory input_free (); g_free (buffer); gtk_widget_destroy (GTK_WIDGET (window->window)); g_object_unref (application); g_free (window->application_directory); #else // Checking syntax if (argn < 1 || argn > 3) { printf ("The syntax is:\n" "./mpcotoolbin [-nthreads x] [-seed s] data_file [result_file] " "[variables_file]\n"); return 2; } if (argn > 1) input->result = (char *) xmlStrdup ((xmlChar *) argc[optind + 1]); if (argn == 2) input->variables = (char *) xmlStrdup ((xmlChar *) argc[optind + 2]); // Making optimization #if DEBUG_MPCOTOOL fprintf (stderr, "mpcotool: making optimization\n"); #endif if (input_open (argc[optind])) optimize_open (); // Freeing memory #if DEBUG_MPCOTOOL fprintf (stderr, "mpcotool: freeing memory and closing\n"); #endif optimize_free (); #endif // Closing MPI #if HAVE_MPI MPI_Finalize (); #endif // Freeing memory gsl_rng_free (optimize->rng); // Closing return 0; }
{ "alphanum_fraction": 0.6882220796, "avg_line_length": 28.0720720721, "ext": "c", "hexsha": "dd82af21ecf63664b272324cfe398bae3ceef6a7", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "e8a6a9713d4ef73b0aa8a0a552d91117ebd22610", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "jburguete/mpcotool", "max_forks_repo_path": "4.0.5/mpcotool.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "e8a6a9713d4ef73b0aa8a0a552d91117ebd22610", "max_issues_repo_issues_event_max_datetime": "2016-03-08T17:02:14.000Z", "max_issues_repo_issues_event_min_datetime": "2016-03-08T17:02:14.000Z", "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "jburguete/mpcotool", "max_issues_repo_path": "4.0.5/mpcotool.c", "max_line_length": 80, "max_stars_count": 1, "max_stars_repo_head_hexsha": "e8a6a9713d4ef73b0aa8a0a552d91117ebd22610", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "jburguete/mpcotool", "max_stars_repo_path": "4.0.5/mpcotool.c", "max_stars_repo_stars_event_max_datetime": "2018-12-17T14:59:29.000Z", "max_stars_repo_stars_event_min_datetime": "2018-12-17T14:59:29.000Z", "num_tokens": 1562, "size": 6232 }
/* ======================================= * SUSY * * TODO: * - still giving qualitatively wrong answer * ======================================= */ #include <stdlib.h> #include <stdio.h> #include <math.h> #define sq(x) pow((x),2.0) #define cb(x) pow((x),3.0) #define qd(x) pow((x),4.0) // GSL Random Number Generator (https://www.gnu.org/software/gsl/) #include <gsl/gsl_rng.h> const gsl_rng_type * T; gsl_rng * r; // GSL Spline (for smoothing) #include <gsl/gsl_errno.h> #include <gsl/gsl_spline.h> gsl_interp_accel *spline_accel; gsl_spline *spline; #define N_spl 5 // Factor of N_bin +1 (end points inclusive) // Parameters #define N_lat 2000 // Lattice size #define a 0.1 // Lattice spacing #define N_therm 500 // Thermalization #define N_meas 1000 // Number of configuration to measure #define N_skip 50 // Decorrelation #define alpha 0 // Strength of potential (harmonic) #define lambda 1 // Strength of potential (anharmonic) #define epsilon 0.2 // Size of fluctuation // SUSY Parameters #define epsilon_susy 0.4 // Size of fluctuation #define N_bin 100 #define dx 0.04 // x_range*2 / bin #define x_range 2 // x in [-range, range] // Globals double x[N_lat]; // Lattice int N_acc,N_tot; // Acceptance rate = acc/tot double E0; // Ground state energy double C[N_lat]; // Correlator double psi[N_bin]; // Wavefunction double psip[N_bin]; // 1st derivative of wavefunction double psipp[N_bin]; // 2nd derivative of wavefunction double H_susy[N_bin]; // SUSY action // Output Files FILE *fE0, *fpsi0, *fpsi; // Prototypes void setup(); void cleanup(); void update(); void update_susy(); int xtoi(double x); double itox(int i); int main(void){ setup(); // Thermalize for(int n=0;n<N_therm;n++){ update(); } // Calculate Wavefunction for(int n=0;n<N_meas;n++){ // Decorrelate for(int m=0;m<N_skip;m++){ update(); } for(int i=0;i<N_lat;i++){ if(abs(x[i])<x_range){ psi[xtoi(x[i])]+=1; } } } printf("1st round acceptance rate: %f \n", (double)N_acc/N_tot); // Normalize wavefunction for(int i=0;i<N_bin;i++){ psi[i] = sqrt(psi[i]/(dx*N_meas*N_lat)); } // Pick points for smoothing spline double x_arr[N_spl]; double y_arr[N_spl]; int skip = nearbyint(N_bin/(N_spl-1)); for(int i=0;i<N_bin;i++){ if(i%skip==0){ x_arr[(i/skip)]=itox(i); y_arr[(i/skip)]=psi[i]; } } // manual add end point x_arr[N_spl-1]=x_range; y_arr[N_spl-1]=psi[N_bin-1]; // Smoothing spline gsl_spline_init(spline, x_arr, y_arr, N_spl); for(int i=0;i<N_bin;i++){ psi[i] = gsl_spline_eval(spline,itox(i),spline_accel); if(psi[i]<0){psi[i]=0;} psip[i] = gsl_spline_eval_deriv(spline, itox(i), spline_accel); psipp[i] = gsl_spline_eval_deriv2(spline, itox(i), spline_accel); } // Smoothing second derivative for(int i=0;i<N_bin;i++){ if(i%skip==0){ y_arr[(i/skip)]=psipp[i]; } } // manual add end point y_arr[N_spl-1]=psipp[N_bin-1]; // Smoothing spline gsl_spline_init(spline, x_arr, y_arr, N_spl); for(int i=0;i<N_bin;i++){ psipp[i] = gsl_spline_eval(spline,itox(i),spline_accel); if(psi[i]>0){ H_susy[i] = - (psipp[i]/psi[i]-sq(psip[i]/psi[i]))/sqrt(2); // TODO: This is technically wrong... }else{ H_susy[i]=9999999; } } // Plot wavefunction and derivatives for(int i=0;i<N_bin;i++){ fprintf(fpsi0,"%f %f %f %f\n", itox(i), psi[i], psip[i], psipp[i]); fprintf(fE0,"%f %f\n", itox(i), H_susy[i]); } // Reinitialize for(int i=0;i<N_bin;i++){psi[i]=0;} for(int i=0;i<N_lat;i++){x[i]=0;} N_acc=0;N_tot=0; // Thermalize for(int n=0;n<N_therm*10;n++){ update_susy(); } // Calculate Wavefunction for(int n=0;n<N_meas;n++){ // Decorrelate for(int m=0;m<N_skip*2;m++){ update_susy(); } for(int i=0;i<N_lat;i++){ if(abs(x[i])<x_range){ psi[xtoi(x[i])]+=1; } } } printf("2nd round acceptance rate: %f \n", (double)N_acc/N_tot); // Plot wavefunction for(int i=0;i<N_bin;i++){ fprintf(fpsi,"%f, %f\n", itox(i), sqrt(psi[i]/(dx*N_meas*N_lat))); } cleanup(); return 0; } // Convert x into bin index int xtoi(double x){ return nearbyint((x+x_range)/dx); } // Convert bin index to x double itox(int i){ return i*dx-x_range; } // Calculate difference in action double dS(int i, double x_old){ return (x[i]*(x[i]-x[(i+1)%N_lat]-x[(i-1+N_lat)%N_lat])/a + alpha*a*sq(x[i]) + lambda*a*qd(x[i])) - (x_old*(x_old-x[(i+1)%N_lat]-x[(i-1+N_lat)%N_lat])/a + alpha*a*sq(x_old) + lambda*a*qd(x_old)); } double dS_susy(int i, double x_old){ return (x[i]*(x[i]-x[(i+1)%N_lat]-x[(i-1+N_lat)%N_lat])/a + a*H_susy[xtoi(x[i])]) - (x_old*(x_old-x[(i+1)%N_lat]-x[(i-1+N_lat)%N_lat])/a + a*H_susy[xtoi(x_old)]); } void update(){ double x_old; double d; // Difference in action for(int i=0;i<N_lat;i++){ x_old=x[i]; x[i]=x[i] + epsilon * (gsl_rng_uniform(r)-0.5)*2; N_acc++; N_tot++; d=dS(i,x_old); if(d>0){ if(exp(-d)<gsl_rng_uniform(r)){ x[i]=x_old; N_acc--; } // Revert to old value } } } void update_susy(){ double x_old; double d; // Difference in action for(int i=0;i<N_lat;i++){ x_old=x[i]; x[i]=x[i] + epsilon_susy * (gsl_rng_uniform(r)-0.5)*2; N_acc++; N_tot++; d=dS_susy(i,x_old); if(d>0){ if(exp(-d)<gsl_rng_uniform(r)){ x[i]=x_old; N_acc--; } // Revert to old value } } } void setup(){ // Cold start for(int i=0;i<N_lat;i++){ x[i]=0; C[i]=0; } // Initialize variables N_acc = 0; N_tot = 0; E0 = 0; for(int i=0;i<N_bin;i++){ psi[i]=0; psip[i]=0; psipp[i]=0; H_susy[i]=0;} // Create Files fE0=fopen("E0.txt", "w+"); fpsi0=fopen("psi0.txt", "w+"); fpsi=fopen("psi.txt", "w+"); // Setup random environment gsl_rng_env_setup(); T = gsl_rng_mt19937; r = gsl_rng_alloc (T); // Setup spline spline_accel = gsl_interp_accel_alloc(); spline = gsl_spline_alloc(gsl_interp_cspline, N_spl); } void cleanup(){ gsl_rng_free (r); gsl_spline_free(spline); gsl_interp_accel_free(spline_accel); // Close Files fclose(fE0); fclose(fpsi0); fclose(fpsi); }
{ "alphanum_fraction": 0.5911532385, "avg_line_length": 23.6194029851, "ext": "c", "hexsha": "622b7f880ada673881a0e2c05f5f845bc9a7c624", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "b73f218593cecf0313e3d97b7ce2262844baab2e", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "uchuutamashi/lqcd", "max_forks_repo_path": "susy/susy_metro.c", "max_issues_count": 5, "max_issues_repo_head_hexsha": "b73f218593cecf0313e3d97b7ce2262844baab2e", "max_issues_repo_issues_event_max_datetime": "2015-06-11T18:46:57.000Z", "max_issues_repo_issues_event_min_datetime": "2015-04-23T03:08:28.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "uchuutamashi/lqcd", "max_issues_repo_path": "susy/susy_metro.c", "max_line_length": 104, "max_stars_count": null, "max_stars_repo_head_hexsha": "b73f218593cecf0313e3d97b7ce2262844baab2e", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "uchuutamashi/lqcd", "max_stars_repo_path": "susy/susy_metro.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2124, "size": 6330 }
/*! \file allvars.h * \brief declares global variables. * * This file declares all global variables and structures. Further variables should be added here, and declared as * \e \b extern. The actual existence of these variables is provided by the file \ref allvars.cxx. To produce * \ref allvars.cxx from \ref allvars.h, do the following: * * \arg Erase all \#define's, typedef's, and enum's * \arg add \#include "allvars.h", delete the \#ifndef ALLVARS_H conditional * \arg delete all keywords 'extern' * \arg delete all struct definitions enclosed in {...}, e.g. * "extern struct global_data_all_processes {....} All;" * becomes "struct global_data_all_processes All;" */ #ifndef ALLVARS_H #define ALLVARS_H #include <cstdio> #include <cstdlib> #include <iostream> #include <iomanip> #include <fstream> #include <cmath> #include <string> #include <vector> #include <algorithm> #include <getopt.h> #include <sys/stat.h> #include <sys/timeb.h> #include <gsl/gsl_heapsort.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_math.h> #include <gsl/gsl_roots.h> ///\name Include for NBodyFramework library. //@{ ///nbody code #include <NBody.h> ///Math code #include <NBodyMath.h> ///Binary KD-Tree code #include <KDTree.h> ///Extra routines that analyze a distribution of particles #include <Analysis.h> //@} // ///\name for checking the endian of floats //#include <endianutils.h> ///if using OpenMP API #ifdef USEOPENMP #include <omp.h> #endif ///if using HDF API #ifdef USEHDF #include "H5Cpp.h" #ifndef H5_NO_NAMESPACE using namespace H5; #endif #endif ///if using ADIOS API #ifdef USEADIOS #include "adios.h" #endif //#include "swiftinterface.h" // //using namespace Swift; using namespace std; using namespace Math; using namespace NBody; //-- Structures and external variables /// \defgroup PARTTYPES Particle types //@{ #define GASTYPE 0 #define DARKTYPE 1 #define DARK2TYPE 2 #define DARK3TYPE 3 #define STARTYPE 4 #define BHTYPE 5 #define WINDTYPE 6 #define NPARTTYPES 7 //number of baryon types +1, to store all baryons #define NBARYONTYPES 5 //@} /// \defgroup SEARCHTYPES Specify particle type to be searched, all, dm only, separate //@{ #define PSTALL 1 #define PSTDARK 2 #define PSTSTAR 3 #define PSTGAS 4 #define PSTBH 5 #define PSTNOBH 6 //@} /// \defgroup STRUCTURETYPES Specific structure type, allow for other types beside HALO //@{ /// \todo note that here I have set background group type to a halo structure type but that can be changed #define HALOSTYPE 10 #define HALOCORESTYPE 5 #define WALLSTYPE 1 #define VOIDSTYPE 2 #define FILAMENTSTYPE 3 #define BGTYPE 10 #define GROUPNOPARENT -1 #define FOF3DTYPE 7 #define FOF3DGROUP -2 //@} /// \defgroup FOFTYPES FOF search types //@{ //subsets made ///call \ref FOFStreamwithprob #define FOFSTPROB 1 ///6D FOF search but only with outliers #define FOF6DSUBSET 7 ///like \ref FOFStreamwithprob search but search is limited to nearest physical neighbours #define FOFSTPROBNN 9 ///like \ref FOFStreamwithprob search but here linking length adjusted by velocity offset, smaller lengths for larger velocity offsets #define FOFSTPROBLX 10 ///like \ref FOFSTPROBLX but for NN search #define FOFSTPROBNNLX 11 ///like \ref FOFSTPROBNN but there is not linking length applied just use nearest neighbours #define FOFSTPROBNNNODIST 12 //for iterative method with FOFStreamwithprob //#define FOFSTPROBIT 13 #define FOFSTPROBSCALEELL 13 //#define FOFSTPROBIT 13 #define FOFSTPROBSCALEELLNN 14 //solely phase-space tensor core growth substructure search #define FOF6DCORE 6 ///phase-space FOF but no subset produced #define FOFSTNOSUBSET 2 ///no subsets made, just 6d (with each 6dfof search using 3d fof velocity dispersion,) #define FOF6DADAPTIVE 3 ///6d fof but only use single velocity dispersion from largest 3d fof object #define FOF6D 4 ///3d search #define FOF3D 5 //@} /// \defgroup INTERATIVESEARCHPARAMS for iterative subsubstructure search //@{ /// this is minimum particle number size for a subsearch to proceed whereby substructure split up into CELLSPLITNUM new cells #define MINCELLSIZE 100 #define CELLSPLITNUM 8 #define MINSUBSIZE MINCELLSIZE*CELLSPLITNUM #define MAXSUBLEVEL 8 /// maximum fraction a cell can take of a halo #define MAXCELLFRACTION 0.1 //@} ///\defgroup GRIDTYPES Type of Grid structures //@{ #define PHYSENGRID 1 #define PHASEENGRID 2 #define PHYSGRID 3 //@} /// \name Max number of neighbouring cells used in interpolation of background velocity field. //@{ //if cells were cubes this would be all the neighbours that full enclose the cube, 6 faces+20 diagonals //using daganoals may not be ideal. Furthermore, code using adaptive grid that if effectively produces //cell that are rectangular prisms. Furthermore, not all cells will share a boundary with another cell. //So just consider "faces". #define MAXNGRID 6 //@} ///\defgroup INPUTTYPES defining types of input //@{ #define NUMINPUTS 5 #define IOGADGET 1 #define IOHDF 2 #define IOTIPSY 3 #define IORAMSES 4 #define IONCHILADA 5 //@} ///\defgroup OUTPUTTYPES defining format types of output //@{ #define OUTASCII 0 #define OUTBINARY 1 #define OUTHDF 2 #define OUTADIOS 3 //@} /// \name For Unbinding //@{ ///number below which just use PP calculation for potential, which occurs roughly at when n~2*log(n) (from scaling of n^2 vs n ln(n) for PP vs tree and factor of 2 is ///for extra overhead in producing tree. For reasonable values of n (>100) this occurs at ~100. Here to account for extra memory need for tree, we use n=3*log(n) or 150 #define UNBINDNUM 150 ///when unbinding check to see if system is bound and least bound particle is also bound #define USYSANDPART 0 ///when unbinding check to see if least bound particle is also bound #define UPART 1 ///use the bulk centre of mass velocity to define velocity reference frame when determining if particle bound #define CMVELREF 0 ///use the particle at potential minimum. Issues if too few particles used as particles will move in and out of deepest point of the potential well #define POTREF 1 //@} /// \name For Tree potential calculation //@{ ///leafflag indicating in tree-calculation of potential, reached a leaf node that does not satisfy mono-pole approx #define leafflag 1 ///split flag means node not used as subcells are searched #define splitflag -1 ///cellflag means a node that is not necessarily a leaf node can be approximated by mono-pole #define cellflag 0 //@} /// \defgroup OMPLIMS For determining whether loop contains enough for openm to be worthwhile. //@{ #define ompsearchnum 50000 #define ompunbindnum 1000 #define ompperiodnum 50000 #define omppropnum 50000 //@} ///\name halo id modifers used with current snapshot value to make temporally unique halo identifiers #ifdef LONGINT #define HALOIDSNVAL 1000000000000L #else #define HALOIDSNVAL 1000000 #endif ///\defgroup GASPARAMS Useful constants for gas //@{ ///mass of helium relative to hydrogen #define M_HetoM_H 4.0026 //@} /// Structure stores unbinding information struct UnbindInfo { ///\name flag whether unbind groups, keep bg potential when unbinding, type of unbinding and reference frame //@{ int unbindflag,bgpot,unbindtype,cmvelreftype; //@} ///boolean as to whether code calculate potentials or potentials are externally provided bool icalculatepotential; ///fraction of potential energy that kinetic energy is allowed to be and consider particle bound Double_t Eratio; ///minimum bound mass fraction Double_t minEfrac; ///when to recalculate kinetic energies if cmvel has changed enough Double_t cmdelta; ///maximum fraction of particles to remove when unbinding in one given unbinding step Double_t maxunbindfrac; ///minimum number of particles to use to calculate reference frame if using particles around deepest potential well as reference frame Int_t Npotref; ///fraction of number of particles to use to calculate reference frame if using particles around deepest potential well as reference frame Double_t fracpotref; ///\name gravity and tree potential calculation; //@{ int BucketSize; Double_t TreeThetaOpen; ///softening length Double_t eps; //@} UnbindInfo(){ icalculatepotential=true; unbindflag=0; bgpot=1; unbindtype=UPART; cmvelreftype=CMVELREF; cmdelta=0.02; Eratio=1.0; minEfrac=1.0; BucketSize=8; TreeThetaOpen=0.7; eps=0.0; maxunbindfrac=0.05; Npotref=10; fracpotref=0.1; } }; /// Structure stores information used when calculating bulk (sub)structure properties /// which is used in \ref substructureproperties.cxx struct PropInfo { //interate till this much mass in contained in a spherical region to calculate cm quantities Double_t cmfrac,cmadjustfac; PropInfo(){ cmfrac=0.1; cmadjustfac=0.7; } }; /* Structure to hold the location of a top-level cell. */ struct cell_loc { /* Coordinates x,y,z */ double loc[3]; }; /// Options structure stores useful variables that have user determined values which are altered by \ref GetArgs in \ref ui.cxx struct Options { ///\name filenames //@{ char *fname,*outname,*smname,*pname,*gname; char *ramsessnapname; //@} ///input format int inputtype; ///number of snapshots int num_files,snum; ///if parallel reading, number of files read in parallel int nsnapread; ///for output, specify the formats, ie. many separate files int iseparatefiles; ///for output specify the format HDF, binary or ascii \ref OUTHDF, \ref OUTBINARY, \ref OUTASCII int ibinaryout; ///for extended output allowing extraction of particles int iextendedoutput; /// output extra fields in halo properties int iextrahalooutput; ///disable particle id related output like fof.grp or catalog_group data. Useful if just want halo properties ///and not interested in tracking. Code writes halo properties catalog and exits. int inoidoutput; ///return propery data in in comoving little h units instead of standard physical units int icomoveunit; /// input is a cosmological simulation so can use box sizes, cosmological parameters, etc to set scales int icosmologicalin; /// input buffer size when reading data long int inputbufsize; /// mpi paritcle buffer size when sending input particle information long int mpiparticletotbufsize,mpiparticlebufsize; /// mpi factor by which to multiple the memory allocated, ie: buffer region /// to reduce likelihood of having to expand/allocate new memory Double_t mpipartfac; ///\name length,m,v,grav conversion units //@{ Double_t L, M, U, V, G; Double_t lengthtokpc, velocitytokms, masstosolarmass; //@} ///period (comove) Double_t p; ///\name scale factor, Hubunit, h, cosmology, virial density. These are used if linking lengths are scaled or trying to define virlevel using the cosmology //@{ Double_t a,H,h, Omega_m, Omega_b, Omega_cdm, Omega_Lambda, w_de, rhobg, virlevel, virBN98; int comove; /// to store the internal code unit to kpc and the distance^2 of 30 kpc, and 50 kpc Double_t lengthtokpc30pow2, lengthtokpc50pow2; //@} ///to store number of each particle types so that if only searching one particle type, assumes order of gas, dark (halo, disk,bulge), star, special or sink for pfof tipsy style output Int_t numpart[NPARTTYPES]; ///\name parameters that control the local and average volumes used to calculate the local velocity density and the mean field, also the size of the leafnode in the kd-tree used when searching the tree for fof neighbours //@{ int Nvel, Nsearch, Bsize; Int_t Ncell; Double_t Ncellfac; //@} ///minimum group size int MinSize; ///allows for field halos to have a different minimum size int HaloMinSize; ///Significance parameter for groups Double_t siglevel; ///whether to search for substructures at all int iSubSearch; ///type of search int foftype,fofbgtype; ///grid type, physical, physical+entropy splitting criterion, phase+entropy splitting criterion. Note that this parameter should not be changed from the default value int gridtype; ///flag indicating search all particle types or just dark matter int partsearchtype; ///flag indicating a separate baryonic search is run, looking for all particles that are associated in phase-space ///with dark matter particles that belong to a structure int iBaryonSearch; ///flag indicating if move to CM frame for substructure search int icmrefadjust; ///threshold on particle ELL value, normalized logarithmic distance from predicted maxwellian velocity density. Double_t ellthreshold; ///\name fofstream search parameters //@{ Double_t thetaopen,Vratio,ellphys; //@} ///fof6d search parameters Double_t ellvel; ///scaling for ellphs and ellvel Double_t ellxscale,ellvscale; ///flag to use iterative method int iiterflag; ///\name factors used to multiply the input values to find initial candidate particles and for mergering groups in interative search //@{ Double_t ellfac,ellxfac,vfac,thetafac,nminfac; Double_t fmerge; //@} ///factors to alter halo linking length search (related to substructure search) //@{ Double_t ellhalophysfac,ellhalovelfac; //@} ///\name parameters related to 3DFOF search & subsequent 6DFOF search //@{ Double_t ellhalo6dxfac; Double_t ellhalo6dvfac; int iKeepFOF; Int_t num3dfof; //@} //@{ ///\name factors used to check for halo mergers, large background substructures and store the velocity scale when searching for associated baryon substructures //@{ Double_t HaloMergerSize,HaloMergerRatio,HaloSigmaV,HaloVelDispScale,HaloLocalSigmaV; Double_t fmergebg; //@} ///flag indicating a single halo is passed or must run search for FOF haloes Int_t iSingleHalo; ///flag indicating haloes are to be check for self-boundness after being searched for substructure Int_t iBoundHalos; /// store denv ratio statistics //@{ int idenvflag; Double_t denvstat[3]; //@} ///verbose output flag int iverbose; ///whether or not to write a fof.grp tipsy like array file int iwritefof; ///whether mass properties for field objects are inclusive int iInclusiveHalo; ///if no mass value stored then store global mass value Double_t MassValue; ///structure that contains variables for unbinding UnbindInfo uinfo; ///structure that contains variables for property calculation PropInfo pinfo; ///effective resolution for zoom simulations Int_t Neff; ///if during substructure search, want to also search for larger substructures //using the more time consuming local velocity calculations (partly in lieu of using the faster core search) int iLargerCellSearch; ///\name extra stuff for halo merger check and identification of multiple halo core and flag for fully adaptive linking length using number density of candidate objects //@{ /// run halo core search for mergers int iHaloCoreSearch; ///maximum sublevel at which we search for phase-space cores int maxnlevelcoresearch; ///parameters associated with phase-space search for cores of mergers Double_t halocorexfac, halocorevfac, halocorenfac, halocoresigmafac; ///x and v space linking lengths calculated for each object int iAdaptiveCoreLinking; ///use phase-space tensor core assignment int iPhaseCoreGrowth; ///number of iterations int halocorenumloops; ///factor by which one multiples the configuration space dispersion when looping for cores Double_t halocorexfaciter; ///factor by which one multiples the velocity space dispersion when looping for cores Double_t halocorevfaciter; ///factor by which one multiples the min num when looping for cores Double_t halocorenumfaciter; ///factor by which a core must be seperated from main core in phase-space in sigma units Double_t halocorephasedistsig; //@} ///for storing a snapshot value to make halo ids unique across snapshots long long snapshotvalue; ///\name for reading gadget info with lots of extra sph, star and bh blocks //@{ int gnsphblocks,gnstarblocks,gnbhblocks; //@} /// \name Extra HDF flags indicating the existence of extra baryonic/dm particle types //@{ /// input naming convention int ihdfnameconvention; /// input contains star particles int iusestarparticles; /// input contains black hole/sink particles int iusesinkparticles; /// input contains wind particles int iusewindparticles; /// input contains tracer particles int iusetracerparticles; /// input contains extra dark type particles int iuseextradarkparticles; //@} /// if want full spherical overdensity, factor by which size is multiplied to get ///bucket of particles Double_t SphericalOverdensitySeachFac; ///if want to the particle IDs that are within the SO overdensity of a halo int iSphericalOverdensityPartList; /// \name Extra variables to store information useful in zoom simluations //@{ /// store the lowest dark matter particle mass Double_t zoomlowmassdm; //@} ///\name extra runtime flags //@{ ///scale lengths. Useful if searching single halo system and which to automatically scale linking lengths int iScaleLengths; // Swift simulation information //Swift::siminfo swiftsiminfo; double spacedimension[3]; /* Number of top-level cells. */ int numcells; /* Number of top-level cells in each dimension. */ int numcellsperdim; /* Locations of top-level cells. */ cell_loc *cellloc; /*! Top-level cell width. */ double cellwidth[3]; /*! Inverse of the top-level cell width. */ double icellwidth[3]; /*! Holds the node ID of each top-level cell. */ const int *cellnodeids; //@} Options() { L = 1.0; M = 1.0; V = 1.0; G = 1.0; p = 0.0; a = 1.0; H = 0.; h = 1.0; Omega_m = 1.0; Omega_Lambda = 0.0; Omega_b = 0.0; Omega_cdm = Omega_m; rhobg = 1.0; virlevel = -1; comove=0; H=100.0;//value of Hubble flow in h 1 km/s/Mpc MassValue=1.0; inputtype=IOGADGET; num_files=1; nsnapread=1; fname=outname=smname=pname=gname=outname=NULL; Bsize=16; Nvel=32; Nsearch=256; Ncellfac=0.01; iSubSearch=1; partsearchtype=PSTALL; for (int i=0;i<NPARTTYPES;i++)numpart[i]=0; foftype=FOFSTPROB; gridtype=PHYSENGRID; fofbgtype=FOF6D; idenvflag=0; iBaryonSearch=0; icmrefadjust=1; Neff=-1; ellthreshold=1.5; thetaopen=0.05; Vratio=1.25; ellphys=0.2; MinSize=20; HaloMinSize=-1; siglevel=2.0; ellvel=0.5; ellxscale=ellvscale=1.0; ellhalophysfac=ellhalovelfac=1.0; ellhalo6dxfac=1.0; ellhalo6dvfac=1.25; iiterflag=0; ellfac=2.5; ellxfac=3.0; vfac=1.0; thetafac=1.0; nminfac=0.5; fmerge=0.25; HaloMergerSize=10000; HaloMergerRatio=0.2; HaloVelDispScale=0; fmergebg=0.5; iSingleHalo=0; iBoundHalos=0; iInclusiveHalo=0; iKeepFOF=0; iLargerCellSearch=0; iHaloCoreSearch=0; iAdaptiveCoreLinking=0; iPhaseCoreGrowth=1; maxnlevelcoresearch=5; halocorexfac=0.5; halocorevfac=2.0; halocorenfac=0.1; halocoresigmafac=2.0; halocorenumloops=3; halocorexfaciter=0.75; halocorevfaciter=0.75; halocorenumfaciter=1.0; halocorephasedistsig=2.0; iverbose=0; iwritefof=0; iseparatefiles=0; ibinaryout=0; iextrahalooutput=0; iextendedoutput=0; inoidoutput=0; icomoveunit=0; icosmologicalin=1; iusestarparticles=1; iusesinkparticles=1; iusewindparticles=0; iusetracerparticles=0; #ifdef HIGHRES iuseextradarkparticles=1; #else iuseextradarkparticles=0; #endif snapshotvalue=0; gnsphblocks=4; gnstarblocks=2; gnbhblocks=2; iScaleLengths=0; inputbufsize=100000; mpiparticletotbufsize=-1; mpiparticlebufsize=-1; lengthtokpc=-1.0; velocitytokms=-1.0; masstosolarmass=-1.0; lengthtokpc30pow2=30.0*30.0; lengthtokpc30pow2=50.0*50.0; SphericalOverdensitySeachFac=1.25; iSphericalOverdensityPartList=0; mpipartfac=0.1; #if USEHDF ihdfnameconvention=0; #endif } }; struct ConfigInfo{ //list the name of the info vector<string> nameinfo; //vector<float> datainfo; vector<string> datainfo; //vector<int> datatype; ConfigInfo(Options &opt){ //if compiler is super old and does not have at least std 11 implementation to_string does not exist #ifndef OLDCCOMPILER //general search operations nameinfo.push_back("Particle_search_type"); datainfo.push_back(to_string(opt.partsearchtype)); nameinfo.push_back("FoF_search_type"); datainfo.push_back(to_string(opt.foftype)); nameinfo.push_back("FoF_Field_search_type"); datainfo.push_back(to_string(opt.fofbgtype)); nameinfo.push_back("Search_for_substructure"); datainfo.push_back(to_string(opt.iSubSearch)); nameinfo.push_back("Keep_FOF"); datainfo.push_back(to_string(opt.iKeepFOF)); nameinfo.push_back("Iterative_searchflag"); datainfo.push_back(to_string(opt.iiterflag)); nameinfo.push_back("Unbind_flag"); datainfo.push_back(to_string(opt.uinfo.unbindflag)); nameinfo.push_back("Baryon_searchflag"); datainfo.push_back(to_string(opt.iBaryonSearch)); nameinfo.push_back("CMrefadjustsubsearch_flag"); datainfo.push_back(to_string(opt.icmrefadjust)); nameinfo.push_back("Halo_core_search"); datainfo.push_back(to_string(opt.iHaloCoreSearch)); nameinfo.push_back("Use_adaptive_core_search"); datainfo.push_back(to_string(opt.iAdaptiveCoreLinking)); nameinfo.push_back("Use_phase_tensor_core_growth"); datainfo.push_back(to_string(opt.iPhaseCoreGrowth)); //local field parameters nameinfo.push_back("Cell_fraction"); datainfo.push_back(to_string(opt.Ncellfac)); nameinfo.push_back("Grid_type"); datainfo.push_back(to_string(opt.gridtype)); nameinfo.push_back("Nsearch_velocity"); datainfo.push_back(to_string(opt.Nvel)); nameinfo.push_back("Nsearch_physical"); datainfo.push_back(to_string(opt.Nsearch)); //substructure search parameters nameinfo.push_back("Outlier_threshold"); datainfo.push_back(to_string(opt.ellthreshold)); nameinfo.push_back("Significance_level"); datainfo.push_back(to_string(opt.siglevel)); nameinfo.push_back("Velocity_ratio"); datainfo.push_back(to_string(opt.Vratio)); nameinfo.push_back("Velocity_opening_angle"); datainfo.push_back(to_string(opt.thetaopen)); nameinfo.push_back("Physical_linking_length"); datainfo.push_back(to_string(opt.ellphys)); nameinfo.push_back("Velocity_linking_length"); datainfo.push_back(to_string(opt.ellvel)); nameinfo.push_back("Minimum_size"); datainfo.push_back(to_string(opt.MinSize)); //field object specific searches nameinfo.push_back("Minimum_halo_size"); datainfo.push_back(to_string(opt.HaloMinSize)); nameinfo.push_back("Halo_linking_length_factor"); datainfo.push_back(to_string(opt.ellhalophysfac)); nameinfo.push_back("Halo_velocity_linking_length_factor"); datainfo.push_back(to_string(opt.ellhalovelfac)); //specific to 6DFOF field search nameinfo.push_back("Halo_6D_linking_length_factor"); datainfo.push_back(to_string(opt.ellhalo6dxfac)); nameinfo.push_back("Halo_6D_vel_linking_length_factor"); datainfo.push_back(to_string(opt.ellhalo6dvfac)); //specific search for 6d fof core searches nameinfo.push_back("Halo_core_ellx_fac"); datainfo.push_back(to_string(opt.halocorexfac)); nameinfo.push_back("Halo_core_ellv_fac"); datainfo.push_back(to_string(opt.halocorevfac)); nameinfo.push_back("Halo_core_ncellfac"); datainfo.push_back(to_string(opt.halocorenfac)); nameinfo.push_back("Halo_core_adaptive_sigma_fac"); datainfo.push_back(to_string(opt.halocoresigmafac)); nameinfo.push_back("Halo_core_num_loops"); datainfo.push_back(to_string(opt.halocorenumloops)); nameinfo.push_back("Halo_core_loop_ellx_fac"); datainfo.push_back(to_string(opt.halocorexfaciter)); nameinfo.push_back("Halo_core_loop_ellv_fac"); datainfo.push_back(to_string(opt.halocorevfaciter)); nameinfo.push_back("Halo_core_loop_elln_fac"); datainfo.push_back(to_string(opt.halocorenumfaciter)); nameinfo.push_back("Halo_core_phase_significance"); datainfo.push_back(to_string(opt.halocorephasedistsig)); //for changing factors used in iterative search nameinfo.push_back("Iterative_threshold_factor"); datainfo.push_back(to_string(opt.ellfac)); nameinfo.push_back("Iterative_linking_length_factor"); datainfo.push_back(to_string(opt.ellxfac)); nameinfo.push_back("Iterative_Vratio_factor"); datainfo.push_back(to_string(opt.vfac)); nameinfo.push_back("Iterative_ThetaOp_factor"); datainfo.push_back(to_string(opt.thetafac)); //for changing effective resolution when rescaling linking lengh nameinfo.push_back("Effective_resolution"); datainfo.push_back(to_string(opt.Neff)); //for changing effective resolution when rescaling linking lengh nameinfo.push_back("Singlehalo_search"); datainfo.push_back(to_string(opt.iSingleHalo)); //units, cosmology nameinfo.push_back("Length_unit"); datainfo.push_back(to_string(opt.L)); nameinfo.push_back("Velocity_unit"); datainfo.push_back(to_string(opt.V)); nameinfo.push_back("Mass_unit"); datainfo.push_back(to_string(opt.M)); nameinfo.push_back("Hubble_unit"); datainfo.push_back(to_string(opt.H)); nameinfo.push_back("Gravity"); datainfo.push_back(to_string(opt.G)); nameinfo.push_back("Mass_value"); datainfo.push_back(to_string(opt.MassValue)); nameinfo.push_back("Length_unit_to_kpc"); datainfo.push_back(to_string(opt.lengthtokpc)); nameinfo.push_back("Velocity_to_kms"); datainfo.push_back(to_string(opt.velocitytokms)); nameinfo.push_back("Mass_to_solarmass"); datainfo.push_back(to_string(opt.masstosolarmass)); nameinfo.push_back("Period"); datainfo.push_back(to_string(opt.p)); nameinfo.push_back("Scale_factor"); datainfo.push_back(to_string(opt.a)); nameinfo.push_back("h_val"); datainfo.push_back(to_string(opt.h)); nameinfo.push_back("Omega_m"); datainfo.push_back(to_string(opt.Omega_m)); nameinfo.push_back("Omega_Lambda"); datainfo.push_back(to_string(opt.Omega_Lambda)); nameinfo.push_back("Critical_density"); datainfo.push_back(to_string(opt.rhobg)); nameinfo.push_back("Virial_density"); datainfo.push_back(to_string(opt.virlevel)); nameinfo.push_back("Omega_cdm"); datainfo.push_back(to_string(opt.Omega_cdm)); nameinfo.push_back("Omega_b"); datainfo.push_back(to_string(opt.Omega_b)); nameinfo.push_back("w_of_DE"); datainfo.push_back(to_string(opt.w_de)); //unbinding nameinfo.push_back("Softening_length"); datainfo.push_back(to_string(opt.uinfo.eps)); nameinfo.push_back("Allowed_kinetic_potential_ratio"); datainfo.push_back(to_string(opt.uinfo.Eratio)); nameinfo.push_back("Min_bound_mass_frac"); datainfo.push_back(to_string(opt.uinfo.minEfrac)); nameinfo.push_back("Bound_halos"); datainfo.push_back(to_string(opt.iBoundHalos)); nameinfo.push_back("Keep_background_potential"); datainfo.push_back(to_string(opt.uinfo.bgpot)); nameinfo.push_back("Kinetic_reference_frame_type"); datainfo.push_back(to_string(opt.uinfo.cmvelreftype)); nameinfo.push_back("Min_npot_ref"); datainfo.push_back(to_string(opt.uinfo.Npotref)); nameinfo.push_back("Frac_pot_ref"); datainfo.push_back(to_string(opt.uinfo.fracpotref)); nameinfo.push_back("Unbinding_type"); datainfo.push_back(to_string(opt.uinfo.unbindtype)); //other options nameinfo.push_back("Verbose"); datainfo.push_back(to_string(opt.iverbose)); nameinfo.push_back("Write_group_array_file"); datainfo.push_back(to_string(opt.iwritefof)); nameinfo.push_back("Snapshot_value"); datainfo.push_back(to_string(opt.snapshotvalue)); nameinfo.push_back("Inclusive_halo_masses"); datainfo.push_back(to_string(opt.iInclusiveHalo)); //io related nameinfo.push_back("Cosmological_input"); datainfo.push_back(to_string(opt.icosmologicalin)); nameinfo.push_back("Input_chunk_size"); datainfo.push_back(to_string(opt.inputbufsize)); nameinfo.push_back("MPI_particle_total_buf_size"); datainfo.push_back(to_string(opt.mpiparticletotbufsize)); nameinfo.push_back("Separate_output_files"); datainfo.push_back(to_string(opt.iseparatefiles)); nameinfo.push_back("Binary_output"); datainfo.push_back(to_string(opt.ibinaryout)); nameinfo.push_back("Comoving_units"); datainfo.push_back(to_string(opt.icomoveunit)); nameinfo.push_back("Extended_output"); datainfo.push_back(to_string(opt.iextendedoutput)); //gadget io related to extra info for sph, stars, bhs, nameinfo.push_back("NSPH_extra_blocks"); datainfo.push_back(to_string(opt.gnsphblocks)); nameinfo.push_back("NStar_extra_blocks"); datainfo.push_back(to_string(opt.gnstarblocks)); nameinfo.push_back("NBH_extra_blocks"); datainfo.push_back(to_string(opt.gnbhblocks)); //mpi related configuration nameinfo.push_back("MPI_part_allocation_fac"); datainfo.push_back(to_string(opt.mpiparticletotbufsize)); #endif } }; struct SimInfo{ //list the name of the info vector<string> nameinfo; vector<string> datainfo; SimInfo(Options &opt){ //if compiler is super old and does not have at least std 11 implementation to_string does not exist #ifndef OLDCCOMPILER nameinfo.push_back("Cosmological_Sim"); datainfo.push_back(to_string(opt.icosmologicalin)); if (opt.icosmologicalin) { nameinfo.push_back("ScaleFactor"); datainfo.push_back(to_string(opt.a)); nameinfo.push_back("h_val"); datainfo.push_back(to_string(opt.h)); nameinfo.push_back("Omega_m"); datainfo.push_back(to_string(opt.Omega_m)); nameinfo.push_back("Omega_Lambda"); datainfo.push_back(to_string(opt.Omega_Lambda)); nameinfo.push_back("Omega_cdm"); datainfo.push_back(to_string(opt.Omega_cdm)); nameinfo.push_back("Omega_b"); datainfo.push_back(to_string(opt.Omega_b)); nameinfo.push_back("w_of_DE"); datainfo.push_back(to_string(opt.w_de)); nameinfo.push_back("Period"); datainfo.push_back(to_string(opt.p)); nameinfo.push_back("Hubble_unit"); datainfo.push_back(to_string(opt.H)); } else{ nameinfo.push_back("Time"); datainfo.push_back(to_string(opt.a)); nameinfo.push_back("Period"); datainfo.push_back(to_string(opt.p)); } //units nameinfo.push_back("Length_unit"); datainfo.push_back(to_string(opt.L)); nameinfo.push_back("Velocity_unit"); datainfo.push_back(to_string(opt.V)); nameinfo.push_back("Mass_unit"); datainfo.push_back(to_string(opt.M)); nameinfo.push_back("Gravity"); datainfo.push_back(to_string(opt.G)); #ifdef NOMASS nameinfo.push_back("Mass_value"); datainfo.push_back(to_string(opt.MassValue)); #endif #endif } }; struct UnitInfo{ //list the name of the info vector<string> nameinfo; vector<string> datainfo; UnitInfo(Options &opt){ //if compiler is super old and does not have at least std 11 implementation to_string does not exist #ifndef OLDCCOMPILER nameinfo.push_back("Cosmological_Sim"); datainfo.push_back(to_string(opt.icosmologicalin)); nameinfo.push_back("Comoving_or_Physical"); datainfo.push_back(to_string(opt.icomoveunit)); //units nameinfo.push_back("Length_unit_to_kpc"); datainfo.push_back(to_string(opt.lengthtokpc)); nameinfo.push_back("Velocity_unit_to_kms"); datainfo.push_back(to_string(opt.velocitytokms)); nameinfo.push_back("Mass_unit_to_solarmass"); datainfo.push_back(to_string(opt.masstosolarmass)); #endif } }; /// N-dim grid cell struct GridCell { int ndim; Int_t gid; //middle of cell, and boundaries of cell Double_t xm[6], xbl[6],xbu[6]; //mass, radial size of in cell Double_t mass, rsize; //number of particles in cell Int_t nparts,*nindex; //neighbouring grid cells and distance from cell centers Int_t nnidcells[MAXNGRID]; Double_t nndist[MAXNGRID]; Double_t den; GridCell(int N=3){ ndim=N; nparts=0; den=0; } ~GridCell(){ if (nparts>0)delete nindex; } }; /*! structure stores bulk properties like \f$ m,\ (x,y,z)_{\rm cm},\ (vx,vy,vz)_{\rm cm},\ V_{\rm max},\ R_{\rm max}, \f$ which is calculated in \ref substructureproperties.cxx */ struct PropData { ///\name order in structure hierarchy and number of subhaloes //@{ long long haloid,hostid,directhostid, hostfofid; Int_t numsubs; //@} ///\name properties of total object including DM, gas, stars, bh, etc //@{ ///number of particles Int_t num; ///number of particles in FOF envelop Int_t gNFOF; ///centre of mass Coordinate gcm, gcmvel; ///Position of most bound particle Coordinate gpos, gvel; ///\name physical properties regarding mass, size //@{ Double_t gmass,gsize,gMvir,gRvir,gRmbp,gmaxvel,gRmaxvel,gMmaxvel,gRhalfmass; Double_t gM200c,gR200c,gM200m,gR200m,gMFOF,gM500c,gR500c,gMBN98,gRBN98; //@} ///\name physical properties for shape/mass distribution //@{ ///axis ratios Double_t gq,gs; ///eigenvector Matrix geigvec; //@} ///\name physical properties for velocity //@{ ///velocity dispersion Double_t gsigma_v; ///dispersion tensor Matrix gveldisp; //@} ///physical properties for dynamical state Double_t Efrac,Pot,T; ///physical properties for angular momentum Coordinate gJ, gJ200m, gJ200c; ///Keep track of position of least unbound particle and most bound particle pid Int_t iunbound,ibound; ///Type of structure int stype; ///concentration (and related quantity used to calculate a concentration) Double_t cNFW, VmaxVvir2; ///Bullock & Peebles spin parameters Double_t glambda_B,glambda_P; ///measure of rotational support Double_t Krot; //@} ///\name halo properties within RVmax //@{ Double_t RV_q,RV_s; Matrix RV_eigvec; Double_t RV_sigma_v; Matrix RV_veldisp; Coordinate RV_J; Double_t RV_lambda_B,RV_lambda_P; Double_t RV_Krot; //@} #ifdef GASON ///\name gas specific quantities //@{ ///number of particles int n_gas; ///mass Double_t M_gas, M_gas_rvmax,M_gas_30kpc,M_gas_50kpc, M_gas_500c; ///pos/vel info Coordinate cm_gas,cmvel_gas; ///velocity/angular momentum info Double_t Krot_gas; Coordinate L_gas; Matrix veldisp_gas; ///morphology Double_t Rhalfmass_gas,q_gas,s_gas; Matrix eigvec_gas; ///mean temperature,metallicty,star formation rate Double_t Temp_gas,Z_gas,SFR_gas; ///physical properties for dynamical state Double_t Efrac_gas,Pot_gas,T_gas; //@} #endif #ifdef STARON ///\name star specific quantities //@{ ///number of particles int n_star; ///mass Double_t M_star, M_star_rvmax, M_star_30kpc, M_star_50kpc, M_star_500c; ///pos/vel info Coordinate cm_star,cmvel_star; ///velocity/angular momentum info Double_t Krot_star; Coordinate L_star; Matrix veldisp_star; ///morphology Double_t Rhalfmass_star,q_star,s_star; Matrix eigvec_star; ///mean age,metallicty Double_t t_star,Z_star; ///physical properties for dynamical state Double_t Efrac_star,Pot_star,T_star; //@} #endif #ifdef BHON ///\name black hole specific quantities //@{ ///number of BH int n_bh; ///mass Double_t M_bh; ///mean accretion rate,metallicty Double_t acc_bh; //@} #endif #ifdef HIGHRES ///\name low resolution interloper particle specific quantities //@{ ///number of interloper low res particles int n_interloper; ///mass Double_t M_interloper; //@} #endif PropData(){ num=gNFOF=0; gmass=gsize=gRmbp=gmaxvel=gRmaxvel=gRvir=gR200m=gR200c=gRhalfmass=Efrac=Pot=T=0.; gMFOF=0; gM500c=gR500c=0; gMBN98=gRBN98=0; gcm[0]=gcm[1]=gcm[2]=gcmvel[0]=gcmvel[1]=gcmvel[2]=0.; gJ[0]=gJ[1]=gJ[2]=0; gJ200m[0]=gJ200m[1]=gJ200m[2]=0; gJ200c[0]=gJ200c[1]=gJ200c[2]=0; gveldisp=Matrix(0.); gq=gs=1.0; Krot=0.; RV_sigma_v=0; RV_q=RV_s=1.; RV_J[0]=RV_J[1]=RV_J[2]=0; RV_veldisp=Matrix(0.); RV_eigvec=Matrix(0.); RV_lambda_B=RV_lambda_P=RV_Krot=0; #ifdef GASON M_gas_rvmax=M_gas_30kpc=M_gas_50kpc=0; n_gas=M_gas=Efrac_gas=0; cm_gas[0]=cm_gas[1]=cm_gas[2]=cmvel_gas[0]=cmvel_gas[1]=cmvel_gas[2]=0.; L_gas[0]=L_gas[1]=L_gas[2]=0; q_gas=s_gas=1.0; Rhalfmass_gas=0; eigvec_gas=Matrix(1,0,0,0,1,0,0,0,1); Temp_gas=Z_gas=SFR_gas=0.0; veldisp_gas=Matrix(0.); Krot_gas=T_gas=Pot_gas=0; #endif #ifdef STARON M_star_rvmax=M_star_30kpc=M_star_50kpc=0; n_star=M_star=Efrac_star=0; cm_star[0]=cm_star[1]=cm_star[2]=cmvel_star[0]=cmvel_star[1]=cmvel_star[2]=0.; L_star[0]=L_star[1]=L_star[2]=0; q_star=s_star=1.0; Rhalfmass_star=0; eigvec_star=Matrix(1,0,0,0,1,0,0,0,1); t_star=Z_star=0.; veldisp_star=Matrix(0.); Krot_star=T_star=Pot_star=0; #endif #ifdef BHON n_bh=M_bh=0; acc_bh=0; #endif #ifdef HIGHRES n_interloper=M_interloper=0; #endif } ///equals operator, useful if want inclusive information before substructure search PropData& operator=(const PropData &p){ num=p.num; gcm=p.gcm;gcmvel=p.gcmvel; gpos=p.gpos;gvel=p.gvel; gmass=p.gmass;gsize=p.gsize; gMvir=p.gMvir;gRvir=p.gRvir;gRmbp=p.gRmbp; gmaxvel=gmaxvel=p.gmaxvel;gRmaxvel=p.gRmaxvel;gMmaxvel=p.gMmaxvel; gM200c=p.gM200c;gR200c=p.gR200c; gM200m=p.gM200m;gR200m=p.gR200m; gM500c=p.gM500c;gR500c=p.gR500c; gMBN98=p.gMBN98;gRBN98=p.gRBN98; gNFOF=p.gNFOF; gMFOF=p.gMFOF; return *this; } ///converts the properties data into comoving little h values ///so masses, positions have little h values and positions are comoving void ConverttoComove(Options &opt){ gcm=gcm*opt.h/opt.a; gpos=gpos*opt.h/opt.a; gmass*=opt.h; gMvir*=opt.h; gM200c*=opt.h; gM200m*=opt.h; gM500c*=opt.h; gMBN98*=opt.h; gMFOF*=opt.h; gsize*=opt.h/opt.a; gRmbp*=opt.h/opt.a; gRmaxvel*=opt.h/opt.a; gRvir*=opt.h/opt.a; gR200c*=opt.h/opt.a; gR200m*=opt.h/opt.a; gR500c*=opt.h/opt.a; gRBN98*=opt.h/opt.a; gJ=gJ*opt.h*opt.h/opt.a; gJ200m=gJ200m*opt.h*opt.h/opt.a; gJ200c=gJ200c*opt.h*opt.h/opt.a; RV_J=RV_J*opt.h*opt.h/opt.a; #ifdef GASON M_gas*=opt.h; M_gas_rvmax*=opt.h; M_gas_30kpc*=opt.h; M_gas_50kpc*=opt.h; M_gas_500c*=opt.h; cm_gas=cm_gas*opt.h/opt.a; Rhalfmass_gas*=opt.h/opt.a; L_gas=L_gas*opt.h*opt.h/opt.a; #endif #ifdef STARON M_star*=opt.h; M_star_rvmax*=opt.h; M_star_30kpc*=opt.h; M_star_50kpc*=opt.h; M_star_500c*=opt.h; cm_star=cm_star*opt.h/opt.a; Rhalfmass_star*=opt.h/opt.a; L_star=L_star*opt.h*opt.h/opt.a; #endif #ifdef BHON M_bh*=opt.h; #endif #ifdef HIGHRES M_interloper*=opt.h; #endif } ///write (append) the properties data to an already open binary file void WriteBinary(fstream &Fout, Options&opt){ long long lval; long unsigned idval; unsigned int ival; double val, val3[3],val9[9]; idval=haloid; Fout.write((char*)&idval,sizeof(idval)); lval=ibound; Fout.write((char*)&lval,sizeof(idval)); lval=hostid; Fout.write((char*)&lval,sizeof(idval)); idval=numsubs; Fout.write((char*)&idval,sizeof(idval)); idval=num; Fout.write((char*)&idval,sizeof(idval)); ival=stype; Fout.write((char*)&ival,sizeof(ival)); if (opt.iKeepFOF==1) { idval=directhostid; Fout.write((char*)&idval,sizeof(idval)); idval=hostfofid; Fout.write((char*)&idval,sizeof(idval)); } val=gMvir; Fout.write((char*)&val,sizeof(val)); for (int k=0;k<3;k++) val3[k]=gcm[k]; Fout.write((char*)val3,sizeof(val)*3); for (int k=0;k<3;k++) val3[k]=gpos[k]; Fout.write((char*)val3,sizeof(val)*3); for (int k=0;k<3;k++) val3[k]=gcmvel[k]; Fout.write((char*)val3,sizeof(val)*3); for (int k=0;k<3;k++) val3[k]=gvel[k]; Fout.write((char*)val3,sizeof(val)*3); val=gmass; Fout.write((char*)&val,sizeof(val)); val=gMFOF; Fout.write((char*)&val,sizeof(val)); val=gM200m; Fout.write((char*)&val,sizeof(val)); val=gM200c; Fout.write((char*)&val,sizeof(val)); val=gMBN98; Fout.write((char*)&val,sizeof(val)); val=Efrac; Fout.write((char*)&val,sizeof(val)); val=gRvir; Fout.write((char*)&val,sizeof(val)); val=gsize; Fout.write((char*)&val,sizeof(val)); val=gR200m; Fout.write((char*)&val,sizeof(val)); val=gR200c; Fout.write((char*)&val,sizeof(val)); val=gRBN98; Fout.write((char*)&val,sizeof(val)); val=gRhalfmass; Fout.write((char*)&val,sizeof(val)); val=gRmaxvel; Fout.write((char*)&val,sizeof(val)); val=gmaxvel; Fout.write((char*)&val,sizeof(val)); val=gsigma_v; Fout.write((char*)&val,sizeof(val)); for (int k=0;k<3;k++) for (int n=0;n<3;n++) val9[k*3+n]=gveldisp(k,n); Fout.write((char*)val9,sizeof(val)*9); val=glambda_B; Fout.write((char*)&val,sizeof(val)); for (int k=0;k<3;k++) val3[k]=gJ[k]; Fout.write((char*)val3,sizeof(val)*3); val=gq; Fout.write((char*)&val,sizeof(val)); val=gs; Fout.write((char*)&val,sizeof(val)); for (int k=0;k<3;k++) for (int n=0;n<3;n++) val9[k*3+n]=geigvec(k,n); Fout.write((char*)val9,sizeof(val)*9); val=cNFW; Fout.write((char*)&val,sizeof(val)); val=Krot; Fout.write((char*)&val,sizeof(val)); val=T; Fout.write((char*)&val,sizeof(val)); val=Pot; Fout.write((char*)&val,sizeof(val)); val=RV_sigma_v; Fout.write((char*)&val,sizeof(val)); for (int k=0;k<3;k++) for (int n=0;n<3;n++) val9[k*3+n]=RV_veldisp(k,n); Fout.write((char*)val9,sizeof(val)*9); val=RV_lambda_B; Fout.write((char*)&val,sizeof(val)); for (int k=0;k<3;k++) val3[k]=RV_J[k]; Fout.write((char*)val3,sizeof(val)*3); val=RV_q; Fout.write((char*)&val,sizeof(val)); val=RV_s; Fout.write((char*)&val,sizeof(val)); for (int k=0;k<3;k++) for (int n=0;n<3;n++) val9[k*3+n]=RV_eigvec(k,n); Fout.write((char*)val9,sizeof(val)*9); #ifdef GASON idval=n_gas; Fout.write((char*)&idval,sizeof(idval)); val=M_gas; Fout.write((char*)&val,sizeof(val)); val=M_gas_rvmax; Fout.write((char*)&val,sizeof(val)); val=M_gas_30kpc; Fout.write((char*)&val,sizeof(val)); val=M_gas_500c; Fout.write((char*)&val,sizeof(val)); for (int k=0;k<3;k++) val3[k]=cm_gas[k]; Fout.write((char*)val3,sizeof(val)*3); for (int k=0;k<3;k++) val3[k]=cmvel_gas[k]; Fout.write((char*)val3,sizeof(val)*3); val=Efrac_gas; Fout.write((char*)&val,sizeof(val)); val=Rhalfmass_gas; Fout.write((char*)&val,sizeof(val)); for (int k=0;k<3;k++) for (int n=0;n<3;n++) val9[k*3+n]=veldisp_gas(k,n); Fout.write((char*)val9,sizeof(val)*9); for (int k=0;k<3;k++) val3[k]=L_gas[k]; Fout.write((char*)val3,sizeof(val)*3); val=q_gas; Fout.write((char*)&val,sizeof(val)); val=s_gas; Fout.write((char*)&val,sizeof(val)); for (int k=0;k<3;k++) for (int n=0;n<3;n++) val9[k*3+n]=eigvec_gas(k,n); Fout.write((char*)val9,sizeof(val)*9); val=Krot_gas; Fout.write((char*)&val,sizeof(val)); val=Temp_gas; Fout.write((char*)&val,sizeof(val)); #ifdef STARON val=Z_gas; Fout.write((char*)&val,sizeof(val)); val=SFR_gas; Fout.write((char*)&val,sizeof(val)); #endif #endif #ifdef STARON idval=n_star; Fout.write((char*)&idval,sizeof(idval)); val=M_star; Fout.write((char*)&val,sizeof(val)); val=M_star_rvmax; Fout.write((char*)&val,sizeof(val)); val=M_star_30kpc; Fout.write((char*)&val,sizeof(val)); val=M_star_500c; Fout.write((char*)&val,sizeof(val)); for (int k=0;k<3;k++) val3[k]=cm_star[k]; Fout.write((char*)val3,sizeof(val)*3); for (int k=0;k<3;k++) val3[k]=cmvel_star[k]; Fout.write((char*)val3,sizeof(val)*3); val=Efrac_star; Fout.write((char*)&val,sizeof(val)); val=Rhalfmass_star; Fout.write((char*)&val,sizeof(val)); for (int k=0;k<3;k++) for (int n=0;n<3;n++) val9[k*3+n]=veldisp_star(k,n); Fout.write((char*)val9,sizeof(val)*9); for (int k=0;k<3;k++) val3[k]=L_star[k]; Fout.write((char*)val3,sizeof(val)*3); val=q_star; Fout.write((char*)&val,sizeof(val)); val=s_star; Fout.write((char*)&val,sizeof(val)); for (int k=0;k<3;k++) for (int n=0;n<3;n++) val9[k*3+n]=eigvec_star(k,n); Fout.write((char*)val9,sizeof(val)*9); val=Krot_star; Fout.write((char*)&val,sizeof(val)); val=t_star; Fout.write((char*)&val,sizeof(val)); val=Z_star; Fout.write((char*)&val,sizeof(val)); #endif #ifdef BHON idval=n_bh; Fout.write((char*)&idval,sizeof(idval)); val=M_bh; Fout.write((char*)&val,sizeof(val)); #endif #ifdef HIGHRES idval=n_interloper; Fout.write((char*)&idval,sizeof(idval)); val=M_interloper; Fout.write((char*)&val,sizeof(val)); #endif } ///write (append) the properties data to an already open ascii file void WriteAscii(fstream &Fout, Options&opt){ Fout<<haloid<<" "; Fout<<ibound<<" "; Fout<<hostid<<" "; Fout<<numsubs<<" "; Fout<<num<<" "; Fout<<stype<<" "; if (opt.iKeepFOF==1) { Fout<<directhostid<<" "; Fout<<hostfofid<<" "; } Fout<<gMvir<<" "; for (int k=0;k<3;k++) Fout<<gcm[k]<<" "; for (int k=0;k<3;k++) Fout<<gpos[k]<<" "; for (int k=0;k<3;k++) Fout<<gcmvel[k]<<" "; for (int k=0;k<3;k++) Fout<<gvel[k]<<" "; Fout<<gmass<<" "; Fout<<gMFOF<<" "; Fout<<gM200m<<" "; Fout<<gM200c<<" "; Fout<<gMBN98<<" "; Fout<<Efrac<<" "; Fout<<gRvir<<" "; Fout<<gsize<<" "; Fout<<gR200m<<" "; Fout<<gR200c<<" "; Fout<<gRBN98<<" "; Fout<<gRhalfmass<<" "; Fout<<gRmaxvel<<" "; Fout<<gmaxvel<<" "; Fout<<gsigma_v<<" "; for (int k=0;k<3;k++) for (int n=0;n<3;n++) Fout<<gveldisp(k,n)<<" "; Fout<<glambda_B<<" "; for (int k=0;k<3;k++) Fout<<gJ[k]<<" "; Fout<<gq<<" "; Fout<<gs<<" "; for (int k=0;k<3;k++) for (int n=0;n<3;n++) Fout<<geigvec(k,n)<<" "; Fout<<cNFW<<" "; Fout<<Krot<<" "; Fout<<T<<" "; Fout<<Pot<<" "; Fout<<RV_sigma_v<<" "; for (int k=0;k<3;k++) for (int n=0;n<3;n++) Fout<<RV_veldisp(k,n)<<" "; Fout<<RV_lambda_B<<" "; for (int k=0;k<3;k++) Fout<<RV_J[k]<<" "; Fout<<RV_q<<" "; Fout<<RV_s<<" "; for (int k=0;k<3;k++) for (int n=0;n<3;n++) Fout<<RV_eigvec(k,n)<<" "; #ifdef GASON Fout<<n_gas<<" "; Fout<<M_gas<<" "; Fout<<M_gas_rvmax<<" "; Fout<<M_gas_30kpc<<" "; //Fout<<M_gas_50kpc<<" "; Fout<<M_gas_500c<<" "; for (int k=0;k<3;k++) Fout<<cm_gas[k]<<" "; for (int k=0;k<3;k++) Fout<<cmvel_gas[k]<<" "; Fout<<Efrac_gas<<" "; Fout<<Rhalfmass_gas<<" "; for (int k=0;k<3;k++) for (int n=0;n<3;n++) Fout<<veldisp_gas(k,n)<<" "; for (int k=0;k<3;k++) Fout<<L_gas[k]<<" "; Fout<<q_gas<<" "; Fout<<s_gas<<" "; for (int k=0;k<3;k++) for (int n=0;n<3;n++) Fout<<eigvec_gas(k,n)<<" "; Fout<<Krot_gas<<" "; Fout<<Temp_gas<<" "; #ifdef STARON Fout<<Z_gas<<" "; Fout<<SFR_gas<<" "; #endif #endif #ifdef STARON Fout<<n_star<<" "; Fout<<M_star<<" "; Fout<<M_star_rvmax<<" "; Fout<<M_star_30kpc<<" "; //Fout<<M_star_50kpc<<" "; Fout<<M_star_500c<<" "; for (int k=0;k<3;k++) Fout<<cm_star[k]<<" "; for (int k=0;k<3;k++) Fout<<cmvel_star[k]<<" "; Fout<<Efrac_star<<" "; Fout<<Rhalfmass_star<<" "; for (int k=0;k<3;k++) for (int n=0;n<3;n++) Fout<<veldisp_star(k,n)<<" "; for (int k=0;k<3;k++) Fout<<L_star[k]<<" "; Fout<<q_star<<" "; Fout<<s_star<<" "; for (int k=0;k<3;k++) for (int n=0;n<3;n++) Fout<<eigvec_star(k,n)<<" "; Fout<<Krot_star<<" "; Fout<<t_star<<" "; Fout<<Z_star<<" "; #endif #ifdef BHON Fout<<n_bh<<" "; Fout<<M_bh<<" "; #endif #ifdef HIGHRES Fout<<n_interloper<<" "; Fout<<M_interloper<<" "; #endif Fout<<endl; } #ifdef USEHDF ///write (append) the properties data to an already open hdf file void WriteHDF(H5File &Fhdf, DataSpace *&dataspaces, DataSet *&datasets, Options&opt){ }; #endif }; /*! Structures stores header info of the data writen by the \ref PropData data structure, specifically the \ref PropData::WriteBinary, \ref PropData::WriteAscii, \ref PropData::WriteHDF routines Must ensure that these routines are all altered together so that the io makes sense. */ struct PropDataHeader{ //list the header info vector<string> headerdatainfo; #ifdef USEHDF vector<PredType> predtypeinfo; #endif #ifdef USEADIOS vector<ADIOS_DATATYPES> adiospredtypeinfo; #endif PropDataHeader(Options&opt){ int sizeval; #ifdef USEHDF vector<PredType> desiredproprealtype; if (sizeof(Double_t)==sizeof(double)) desiredproprealtype.push_back(PredType::NATIVE_DOUBLE); else desiredproprealtype.push_back(PredType::NATIVE_FLOAT); #endif #ifdef USEADIOS vector<ADIOS_DATATYPES> desiredadiosproprealtype; if (sizeof(Double_t)==sizeof(double)) desiredadiosproprealtype.push_back(ADIOS_DATATYPES::adios_double); else desiredadiosproprealtype.push_back(ADIOS_DATATYPES::adios_real); #endif headerdatainfo.push_back("ID"); headerdatainfo.push_back("ID_mbp"); headerdatainfo.push_back("hostHaloID"); headerdatainfo.push_back("numSubStruct"); headerdatainfo.push_back("npart"); headerdatainfo.push_back("Structuretype"); if (opt.iKeepFOF==1){ headerdatainfo.push_back("hostDirectHaloID"); headerdatainfo.push_back("hostFOFID"); } //if using hdf, store the type #ifdef USEHDF predtypeinfo.push_back(PredType::STD_U64LE); predtypeinfo.push_back(PredType::STD_I64LE); predtypeinfo.push_back(PredType::STD_I64LE); predtypeinfo.push_back(PredType::STD_U64LE); predtypeinfo.push_back(PredType::STD_U64LE); predtypeinfo.push_back(PredType::STD_I32LE); if (opt.iKeepFOF==1){ predtypeinfo.push_back(PredType::STD_I64LE); predtypeinfo.push_back(PredType::STD_I64LE); } #endif #ifdef USEADIOS adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_long); adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_long); adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_integer); if (opt.iKeepFOF==1){ adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_long); adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_long); } #endif headerdatainfo.push_back("Mvir"); headerdatainfo.push_back("Xc"); headerdatainfo.push_back("Yc"); headerdatainfo.push_back("Zc"); headerdatainfo.push_back("Xcmbp"); headerdatainfo.push_back("Ycmbp"); headerdatainfo.push_back("Zcmbp"); headerdatainfo.push_back("VXc"); headerdatainfo.push_back("VYc"); headerdatainfo.push_back("VZc"); headerdatainfo.push_back("VXcmbp"); headerdatainfo.push_back("VYcmbp"); headerdatainfo.push_back("VZcmbp"); headerdatainfo.push_back("Mass_tot"); headerdatainfo.push_back("Mass_FOF"); headerdatainfo.push_back("Mass_200mean"); headerdatainfo.push_back("Mass_200crit"); headerdatainfo.push_back("Mass_BN98"); headerdatainfo.push_back("Efrac"); headerdatainfo.push_back("Rvir"); headerdatainfo.push_back("R_size"); headerdatainfo.push_back("R_200mean"); headerdatainfo.push_back("R_200crit"); headerdatainfo.push_back("R_BN98"); headerdatainfo.push_back("R_HalfMass"); headerdatainfo.push_back("Rmax"); headerdatainfo.push_back("Vmax"); headerdatainfo.push_back("sigV"); headerdatainfo.push_back("veldisp_xx"); headerdatainfo.push_back("veldisp_xy"); headerdatainfo.push_back("veldisp_xz"); headerdatainfo.push_back("veldisp_yx"); headerdatainfo.push_back("veldisp_yy"); headerdatainfo.push_back("veldisp_yz"); headerdatainfo.push_back("veldisp_zx"); headerdatainfo.push_back("veldisp_zy"); headerdatainfo.push_back("veldisp_zz"); headerdatainfo.push_back("lambda_B"); headerdatainfo.push_back("Lx"); headerdatainfo.push_back("Ly"); headerdatainfo.push_back("Lz"); headerdatainfo.push_back("q"); headerdatainfo.push_back("s"); headerdatainfo.push_back("eig_xx"); headerdatainfo.push_back("eig_xy"); headerdatainfo.push_back("eig_xz"); headerdatainfo.push_back("eig_yx"); headerdatainfo.push_back("eig_yy"); headerdatainfo.push_back("eig_yz"); headerdatainfo.push_back("eig_zx"); headerdatainfo.push_back("eig_zy"); headerdatainfo.push_back("eig_zz"); headerdatainfo.push_back("cNFW"); headerdatainfo.push_back("Krot"); headerdatainfo.push_back("Ekin"); headerdatainfo.push_back("Epot"); //some properties within RVmax headerdatainfo.push_back("RVmax_sigV"); headerdatainfo.push_back("RVmax_veldisp_xx"); headerdatainfo.push_back("RVmax_veldisp_xy"); headerdatainfo.push_back("RVmax_veldisp_xz"); headerdatainfo.push_back("RVmax_veldisp_yx"); headerdatainfo.push_back("RVmax_veldisp_yy"); headerdatainfo.push_back("RVmax_veldisp_yz"); headerdatainfo.push_back("RVmax_veldisp_zx"); headerdatainfo.push_back("RVmax_veldisp_zy"); headerdatainfo.push_back("RVmax_veldisp_zz"); headerdatainfo.push_back("RVmax_lambda_B"); headerdatainfo.push_back("RVmax_Lx"); headerdatainfo.push_back("RVmax_Ly"); headerdatainfo.push_back("RVmax_Lz"); headerdatainfo.push_back("RVmax_q"); headerdatainfo.push_back("RVmax_s"); headerdatainfo.push_back("RVmax_eig_xx"); headerdatainfo.push_back("RVmax_eig_xy"); headerdatainfo.push_back("RVmax_eig_xz"); headerdatainfo.push_back("RVmax_eig_yx"); headerdatainfo.push_back("RVmax_eig_yy"); headerdatainfo.push_back("RVmax_eig_yz"); headerdatainfo.push_back("RVmax_eig_zx"); headerdatainfo.push_back("RVmax_eig_zy"); headerdatainfo.push_back("RVmax_eig_zz"); #ifdef USEHDF sizeval=predtypeinfo.size(); for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(desiredproprealtype[0]); #endif #ifdef USEADIOS sizeval=adiospredtypeinfo.size(); for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(desiredadiosproprealtype[0]); #endif #ifdef GASON headerdatainfo.push_back("n_gas"); #ifdef USEHDF predtypeinfo.push_back(PredType::STD_U64LE); #endif #ifdef USEADIOS adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_unsigned_long); #endif headerdatainfo.push_back("M_gas"); headerdatainfo.push_back("M_gas_Rvmax"); headerdatainfo.push_back("M_gas_30kpc"); //headerdatainfo.push_back("M_gas_50kpc"); headerdatainfo.push_back("M_gas_500c"); headerdatainfo.push_back("Xc_gas"); headerdatainfo.push_back("Yc_gas"); headerdatainfo.push_back("Zc_gas"); headerdatainfo.push_back("VXc_gas"); headerdatainfo.push_back("VYc_gas"); headerdatainfo.push_back("VZc_gas"); headerdatainfo.push_back("Efrac_gas"); headerdatainfo.push_back("R_HalfMass_gas"); headerdatainfo.push_back("veldisp_xx_gas"); headerdatainfo.push_back("veldisp_xy_gas"); headerdatainfo.push_back("veldisp_xz_gas"); headerdatainfo.push_back("veldisp_yx_gas"); headerdatainfo.push_back("veldisp_yy_gas"); headerdatainfo.push_back("veldisp_yz_gas"); headerdatainfo.push_back("veldisp_zx_gas"); headerdatainfo.push_back("veldisp_zy_gas"); headerdatainfo.push_back("veldisp_zz_gas"); headerdatainfo.push_back("Lx_gas"); headerdatainfo.push_back("Ly_gas"); headerdatainfo.push_back("Lz_gas"); headerdatainfo.push_back("q_gas"); headerdatainfo.push_back("s_gas"); headerdatainfo.push_back("eig_xx_gas"); headerdatainfo.push_back("eig_xy_gas"); headerdatainfo.push_back("eig_xz_gas"); headerdatainfo.push_back("eig_yx_gas"); headerdatainfo.push_back("eig_yy_gas"); headerdatainfo.push_back("eig_yz_gas"); headerdatainfo.push_back("eig_zx_gas"); headerdatainfo.push_back("eig_zy_gas"); headerdatainfo.push_back("eig_zz_gas"); headerdatainfo.push_back("Krot_gas"); headerdatainfo.push_back("T_gas"); #ifdef STARON headerdatainfo.push_back("Zmet_gas"); headerdatainfo.push_back("SFR_gas"); #endif #ifdef USEHDF sizeval=predtypeinfo.size(); for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(desiredproprealtype[0]); #endif #ifdef USEADIOS sizeval=adiospredtypeinfo.size(); for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(desiredadiosproprealtype[0]); #endif #endif #ifdef STARON headerdatainfo.push_back("n_star"); #ifdef USEHDF predtypeinfo.push_back(PredType::STD_U64LE); #endif #ifdef USEADIOS adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_unsigned_long); #endif headerdatainfo.push_back("M_star"); headerdatainfo.push_back("M_star_Rvmax"); headerdatainfo.push_back("M_star_30kpc"); //headerdatainfo.push_back("M_star_50kpc"); headerdatainfo.push_back("M_star_500c"); headerdatainfo.push_back("Xc_star"); headerdatainfo.push_back("Yc_star"); headerdatainfo.push_back("Zc_star"); headerdatainfo.push_back("VXc_star"); headerdatainfo.push_back("VYc_star"); headerdatainfo.push_back("VZc_star"); headerdatainfo.push_back("Efrac_star"); headerdatainfo.push_back("R_HalfMass_star"); headerdatainfo.push_back("veldisp_xx_star"); headerdatainfo.push_back("veldisp_xy_star"); headerdatainfo.push_back("veldisp_xz_star"); headerdatainfo.push_back("veldisp_yx_star"); headerdatainfo.push_back("veldisp_yy_star"); headerdatainfo.push_back("veldisp_yz_star"); headerdatainfo.push_back("veldisp_zx_star"); headerdatainfo.push_back("veldisp_zy_star"); headerdatainfo.push_back("veldisp_zz_star"); headerdatainfo.push_back("Lx_star"); headerdatainfo.push_back("Ly_star"); headerdatainfo.push_back("Lz_star"); headerdatainfo.push_back("q_star"); headerdatainfo.push_back("s_star"); headerdatainfo.push_back("eig_xx_star"); headerdatainfo.push_back("eig_xy_star"); headerdatainfo.push_back("eig_xz_star"); headerdatainfo.push_back("eig_yx_star"); headerdatainfo.push_back("eig_yy_star"); headerdatainfo.push_back("eig_yz_star"); headerdatainfo.push_back("eig_zx_star"); headerdatainfo.push_back("eig_zy_star"); headerdatainfo.push_back("eig_zz_star"); headerdatainfo.push_back("Krot_star"); headerdatainfo.push_back("tage_star"); headerdatainfo.push_back("Zmet_star"); #ifdef USEHDF sizeval=predtypeinfo.size(); for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(desiredproprealtype[0]); #endif #ifdef USEADIOS sizeval=adiospredtypeinfo.size(); for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(desiredadiosproprealtype[0]); #endif #endif #ifdef BHON headerdatainfo.push_back("n_bh"); #ifdef USEHDF predtypeinfo.push_back(PredType::STD_U64LE); #endif #ifdef USEADIOS adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_unsigned_long); #endif headerdatainfo.push_back("M_bh"); #ifdef USEHDF sizeval=predtypeinfo.size(); for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(desiredproprealtype[0]); #endif #ifdef USEADIOS sizeval=adiospredtypeinfo.size(); for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(desiredadiosproprealtype[0]); #endif #endif #ifdef HIGHRES headerdatainfo.push_back("n_interloper"); #ifdef USEHDF predtypeinfo.push_back(PredType::STD_U64LE); #endif #ifdef USEADIOS adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_unsigned_long); #endif headerdatainfo.push_back("M_interloper"); #ifdef USEHDF sizeval=predtypeinfo.size(); for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(desiredproprealtype[0]); #endif #ifdef USEADIOS sizeval=adiospredtypeinfo.size(); for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(desiredadiosproprealtype[0]); #endif #endif //additional information about a halo if (opt.iextrahalooutput) { } } }; /*! Structure used to keep track of a structure's parent structure note that level could be sim->halo->subhalo->subsubhalo or even sim->wall/void/filament->halo->substructure->subsubstructure here sim is stype=0,gid=0, and the other structure types are to be defined. The data structure is meant to be traversed from - level 0 structures ("field" objects) - level 0 pointer to nextlevel - nextlevel containing nginlevel objects */ struct StrucLevelData { ///structure type and number in current level of hierarchy Int_t stype,nsinlevel; ///points to the the head pfof address of the group and parent Particle **Phead; Int_t **gidhead; ///parent pointers point to the address of the parents gidhead and Phead Particle **Pparenthead; Int_t **gidparenthead; ///add uber parent pointer (that is pointer to field halo) Int_t **giduberparenthead; ///allowing for multiple structure types at a given level in the hierarchy Int_t *stypeinlevel; StrucLevelData *nextlevel; StrucLevelData(Int_t numgroups=-1){ if (numgroups<=0) { Phead=NULL; Pparenthead=NULL; gidhead=NULL; gidparenthead=NULL; giduberparenthead=NULL; nextlevel=NULL; stypeinlevel=NULL; nsinlevel=0; } else Allocate(numgroups); } ///just allocate memory void Allocate(Int_t numgroups){ nsinlevel=numgroups; Phead=new Particle*[numgroups+1]; gidhead=new Int_t*[numgroups+1]; stypeinlevel=new Int_t[numgroups+1]; gidparenthead=new Int_t*[numgroups+1]; giduberparenthead=new Int_t*[numgroups+1]; nextlevel=NULL; } ///initialize void Initialize(){ for (Int_t i=1;i<=nsinlevel;i++) {gidhead[i]=NULL;gidparenthead[i]=NULL;giduberparenthead[i]=NULL;} } ~StrucLevelData(){ if (nextlevel!=NULL) delete nextlevel; nextlevel=NULL; if (nsinlevel>0) { delete[] Phead; delete[] gidhead; delete[] stypeinlevel; delete[] gidparenthead; delete[] giduberparenthead; } } }; #if defined(USEHDF)||defined(USEADIOS) ///store the names of datasets in catalog output struct DataGroupNames { ///store names of catalog group files vector<string> prop; #ifdef USEHDF //store the data type vector<PredType> propdatatype; #endif #ifdef USEADIOS vector<ADIOS_DATATYPES> adiospropdatatype; #endif ///store names of catalog group files vector<string> group; #ifdef USEHDF vector<PredType> groupdatatype; #endif #ifdef USEADIOS vector<ADIOS_DATATYPES> adiosgroupdatatype; #endif ///store the names of catalog particle files vector<string> part; #ifdef USEHDF vector<PredType> partdatatype; #endif #ifdef USEADIOS vector<ADIOS_DATATYPES> adiospartdatatype; #endif ///store the names of catalog particle files vector<string> types; #ifdef USEHDF vector<PredType> typesdatatype; #endif #ifdef USEADIOS vector<ADIOS_DATATYPES> adiostypesdatatype; #endif ///store the names of catalog particle files vector<string> hierarchy; #ifdef USEHDF vector<PredType> hierarchydatatype; #endif #ifdef USEADIOS vector<ADIOS_DATATYPES> adioshierarchydatatype; #endif ///store names of catalog group files vector<string> SO; #ifdef USEHDF vector<PredType> SOdatatype; #endif #ifdef USEADIOS vector<ADIOS_DATATYPES> SOdatatype; #endif DataGroupNames(){ prop.push_back("File_id"); prop.push_back("Num_of_files"); prop.push_back("Num_of_groups"); prop.push_back("Total_num_of_groups"); prop.push_back("Cosmological_Sim"); prop.push_back("Comoving_or_Physical"); prop.push_back("Period"); prop.push_back("Time"); prop.push_back("Length_unit_to_kpc"); prop.push_back("Velocity_to_kms"); prop.push_back("Mass_unit_to_solarmass"); #ifdef USEHDF propdatatype.push_back(PredType::STD_I32LE); propdatatype.push_back(PredType::STD_I32LE); propdatatype.push_back(PredType::STD_U64LE); propdatatype.push_back(PredType::STD_U64LE); propdatatype.push_back(PredType::STD_U32LE); propdatatype.push_back(PredType::STD_U32LE); propdatatype.push_back(PredType::NATIVE_FLOAT); propdatatype.push_back(PredType::NATIVE_FLOAT); propdatatype.push_back(PredType::NATIVE_FLOAT); propdatatype.push_back(PredType::NATIVE_FLOAT); propdatatype.push_back(PredType::NATIVE_FLOAT); #endif #ifdef USEADIOS adiospropdatatype.push_back(ADIOS_DATATYPES::adios_integer); adiospropdatatype.push_back(ADIOS_DATATYPES::adios_integer); adiospropdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiospropdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiospropdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_integer); adiospropdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_integer); adiospropdatatype.push_back(ADIOS_DATATYPES::adios_real); adiospropdatatype.push_back(ADIOS_DATATYPES::adios_real); adiospropdatatype.push_back(ADIOS_DATATYPES::adios_real); adiospropdatatype.push_back(ADIOS_DATATYPES::adios_real); adiospropdatatype.push_back(ADIOS_DATATYPES::adios_real); #endif group.push_back("File_id"); group.push_back("Num_of_files"); group.push_back("Num_of_groups"); group.push_back("Total_num_of_groups"); group.push_back("Group_Size"); group.push_back("Offset"); group.push_back("Offset_unbound"); #ifdef USEHDF groupdatatype.push_back(PredType::STD_I32LE); groupdatatype.push_back(PredType::STD_I32LE); groupdatatype.push_back(PredType::STD_U64LE); groupdatatype.push_back(PredType::STD_U64LE); groupdatatype.push_back(PredType::STD_U32LE); groupdatatype.push_back(PredType::STD_U64LE); groupdatatype.push_back(PredType::STD_U64LE); #endif #ifdef USEADIOS adiosgroupdatatype.push_back(ADIOS_DATATYPES::adios_integer); adiosgroupdatatype.push_back(ADIOS_DATATYPES::adios_integer); adiosgroupdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiosgroupdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiosgroupdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_integer); adiosgroupdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiosgroupdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); #endif part.push_back("File_id"); part.push_back("Num_of_files"); part.push_back("Num_of_particles_in_groups"); part.push_back("Total_num_of_particles_in_all_groups"); part.push_back("Particle_IDs"); #ifdef USEHDF partdatatype.push_back(PredType::STD_I32LE); partdatatype.push_back(PredType::STD_I32LE); partdatatype.push_back(PredType::STD_U64LE); partdatatype.push_back(PredType::STD_U64LE); partdatatype.push_back(PredType::STD_I64LE); #endif #ifdef USEADIOS adiospartdatatype.push_back(ADIOS_DATATYPES::adios_integer); adiospartdatatype.push_back(ADIOS_DATATYPES::adios_integer); adiospartdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiospartdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiospartdatatype.push_back(ADIOS_DATATYPES::adios_long); #endif types.push_back("File_id"); types.push_back("Num_of_files"); types.push_back("Num_of_particles_in_groups"); types.push_back("Total_num_of_particles_in_all_groups"); types.push_back("Particle_types"); #ifdef USEHDF typesdatatype.push_back(PredType::STD_I32LE); typesdatatype.push_back(PredType::STD_I32LE); typesdatatype.push_back(PredType::STD_U64LE); typesdatatype.push_back(PredType::STD_U64LE); typesdatatype.push_back(PredType::STD_U16LE); #endif #ifdef USEADIOS adiostypesdatatype.push_back(ADIOS_DATATYPES::adios_integer); adiostypesdatatype.push_back(ADIOS_DATATYPES::adios_integer); adiostypesdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiostypesdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiostypesdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_short); #endif hierarchy.push_back("File_id"); hierarchy.push_back("Num_of_files"); hierarchy.push_back("Num_of_groups"); hierarchy.push_back("Total_num_of_groups"); hierarchy.push_back("Number_of_substructures_in_halo"); hierarchy.push_back("Parent_halo_ID"); #ifdef USEHDF hierarchydatatype.push_back(PredType::STD_I32LE); hierarchydatatype.push_back(PredType::STD_I32LE); hierarchydatatype.push_back(PredType::STD_U64LE); hierarchydatatype.push_back(PredType::STD_U64LE); hierarchydatatype.push_back(PredType::STD_U32LE); hierarchydatatype.push_back(PredType::STD_I64LE); #endif #ifdef USEADIOS adioshierarchydatatype.push_back(ADIOS_DATATYPES::adios_integer); adioshierarchydatatype.push_back(ADIOS_DATATYPES::adios_integer); adioshierarchydatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adioshierarchydatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adioshierarchydatatype.push_back(ADIOS_DATATYPES::adios_unsigned_integer); adioshierarchydatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); #endif SO.push_back("File_id"); SO.push_back("Num_of_files"); SO.push_back("Num_of_SO_regions"); SO.push_back("Total_num_of_SO_regions"); SO.push_back("Num_of_particles_in_SO_regions"); SO.push_back("Total_num_of_particles_in_SO_regions"); SO.push_back("SO_size"); SO.push_back("Offset"); SO.push_back("Particle_IDs"); #ifdef USEHDF SOdatatype.push_back(PredType::STD_I32LE); SOdatatype.push_back(PredType::STD_I32LE); SOdatatype.push_back(PredType::STD_U64LE); SOdatatype.push_back(PredType::STD_U64LE); SOdatatype.push_back(PredType::STD_U64LE); SOdatatype.push_back(PredType::STD_U64LE); SOdatatype.push_back(PredType::STD_U32LE); SOdatatype.push_back(PredType::STD_U64LE); SOdatatype.push_back(PredType::STD_I64LE); #endif #ifdef USEADIOS adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_integer); adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_integer); adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_integer); adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_long); #endif } }; #endif ///if using MPI API #ifdef USEMPI #include <mpi.h> ///Includes external global variables used for MPI version of code #include "mpivar.h" #endif extern StrucLevelData *psldata; #endif
{ "alphanum_fraction": 0.6640761053, "avg_line_length": 34.7072620659, "ext": "h", "hexsha": "4ffada1de5ec148c5200017196530d8ad80fdbaf", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "f18cb8bf088065f9361fc537d4e5858962499a21", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "broukema/VELOCIraptor-STF", "max_forks_repo_path": "stf/src/allvars.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "f18cb8bf088065f9361fc537d4e5858962499a21", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "broukema/VELOCIraptor-STF", "max_issues_repo_path": "stf/src/allvars.h", "max_line_length": 224, "max_stars_count": null, "max_stars_repo_head_hexsha": "f18cb8bf088065f9361fc537d4e5858962499a21", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "broukema/VELOCIraptor-STF", "max_stars_repo_path": "stf/src/allvars.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 20814, "size": 76946 }
/* * Gsl_vector_2: test gsl_vector * * Copyright (c) 2012 Jérémie Decock * * Required: GSL library (libgsl0-dev) * Usage: gcc gsl_vector_2.c -lgsl -lgslcblas -lm * or: gcc gsl_vector_2.c $(pkg-config --libs gsl) */ #include <stdlib.h> #include <stdio.h> #include <gsl/gsl_vector.h> 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); }
{ "alphanum_fraction": 0.6211453744, "avg_line_length": 20.6363636364, "ext": "c", "hexsha": "b1853e0d3db8b357fc92e28e36cd1188a40e6ef7", "lang": "C", "max_forks_count": 7, "max_forks_repo_forks_event_max_datetime": "2022-01-04T15:59:45.000Z", "max_forks_repo_forks_event_min_datetime": "2017-10-31T09:48:14.000Z", "max_forks_repo_head_hexsha": "4bd4e7f459eee610d5cf19f845299ca942ff4b64", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jeremiedecock/snippets", "max_forks_repo_path": "c/gsl/gsl_vector_2.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "4bd4e7f459eee610d5cf19f845299ca942ff4b64", "max_issues_repo_issues_event_max_datetime": "2020-10-22T02:36:10.000Z", "max_issues_repo_issues_event_min_datetime": "2020-10-22T02:36:10.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "jeremiedecock/snippets", "max_issues_repo_path": "c/gsl/gsl_vector_2.c", "max_line_length": 56, "max_stars_count": 23, "max_stars_repo_head_hexsha": "4bd4e7f459eee610d5cf19f845299ca942ff4b64", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jeremiedecock/snippets", "max_stars_repo_path": "c/gsl/gsl_vector_2.c", "max_stars_repo_stars_event_max_datetime": "2021-12-30T08:20:04.000Z", "max_stars_repo_stars_event_min_datetime": "2015-06-08T13:01:00.000Z", "num_tokens": 223, "size": 681 }
#ifndef GSL_CQP_H #define GSL_CQP_H #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_permutation.h> #include <gsl/gsl_linalg.h> /** * gsl_cqp_data. */ typedef struct { /* objective function: 0.5*(x^t)Qx+(q^t)x */ gsl_matrix * Q; gsl_vector * q; /* constraints: Ax=b; Cx>=d */ gsl_matrix * A; gsl_vector * b; gsl_matrix * C; gsl_vector * d; } gsl_cqp_data; /** * gsl_cqpminimizer_type */ typedef struct { const char *name; size_t size; int (*alloc)( void *state, size_t n, size_t me, size_t mi ); int (*set)( void *state, const gsl_cqp_data *cqp, gsl_vector *x, gsl_vector *y, gsl_vector *z, double *gap, double *residuals_norm, double *data_norm, double *inf_barrier, double *inf_barrier_min ); int (*iterate)( void *state, const gsl_cqp_data * cqp, gsl_vector *x, gsl_vector *y, gsl_vector *z, double *gap, double *residuals_norm, double *inf_barrier, double *inf_barrier_min ); void (*free)( void *state, size_t n ); } gsl_cqpminimizer_type; /** * gsl_cqpminimizer */ typedef struct { const gsl_cqpminimizer_type * type; gsl_cqp_data * cqp; gsl_vector * x; /* Lagrange-multipliers */ gsl_vector * y; /*corresponding to Ax=b */ gsl_vector * z; /*corresponding to CX>=d */ double gap; double residuals_norm; double data_norm; double quantity_of_infeasibility; double quantity_of_infeasibility_min; void *state; } gsl_cqpminimizer; gsl_cqpminimizer* gsl_cqpminimizer_alloc( const gsl_cqpminimizer_type* T, size_t n, size_t me, size_t mi ); int gsl_cqpminimizer_set( gsl_cqpminimizer * minimizer, gsl_cqp_data * cqp ); int gsl_cqpminimizer_iterate( gsl_cqpminimizer *minimizer ); int gsl_cqpminimizer_test_convergence( gsl_cqpminimizer * minimizer, double eps_gap, double eps_residual ); gsl_vector* gsl_cqpminimizer_x( gsl_cqpminimizer * minimizer ); void gsl_cqpminimizer_free( gsl_cqpminimizer *minimizer ); const char* gsl_cqpminimizer_name( const gsl_cqpminimizer * minimizer ); gsl_vector* gsl_cqpminimizer_lm_eq( gsl_cqpminimizer * minimizer ); gsl_vector* gsl_cqpminimizer_lm_ineq( gsl_cqpminimizer * minimizer ); double gsl_cqpminimizer_f( gsl_cqpminimizer * minimizer ); double gsl_cqpminimizer_gap( gsl_cqpminimizer *minimizer ); double gsl_cqpminimizer_residuals_norm( gsl_cqpminimizer *minimizer ); int gsl_cqp_minimizer_test_infeasibility( gsl_cqpminimizer * minimizer, double eps_infeasible ); double gsl_cqpminimizer_minimum( gsl_cqpminimizer * minimizer ); GSL_VAR const gsl_cqpminimizer_type *gsl_cqpminimizer_mg_pdip; #endif
{ "alphanum_fraction": 0.7644927536, "avg_line_length": 30.6666666667, "ext": "h", "hexsha": "33eab37a56b01c0b4e61fc8691f3d759d09c8e7c", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "2a8f82e1492c9efccde9a4935ce3019df1c68cde", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "wmotte/toolkid", "max_forks_repo_path": "src/cqp/gsl_cqp.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "2a8f82e1492c9efccde9a4935ce3019df1c68cde", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "wmotte/toolkid", "max_issues_repo_path": "src/cqp/gsl_cqp.h", "max_line_length": 132, "max_stars_count": null, "max_stars_repo_head_hexsha": "2a8f82e1492c9efccde9a4935ce3019df1c68cde", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "wmotte/toolkid", "max_stars_repo_path": "src/cqp/gsl_cqp.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 837, "size": 2760 }
#pragma once #include "../common.h" #include "../concepts.h" #include <boost/container/flat_set.hpp> #include <boost/outcome/result.hpp> #include <boost/outcome/try.hpp> #include <fmt/format.h> #include <gsl/gsl-lite.hpp> #include <string> #include <string_view> #include <yaml-cpp/yaml.h> namespace angonoka::validation { using boost::container::flat_set; namespace bo = boost::outcome_v2; using result = bo::result<void, std::string>; using namespace fmt::literals; template <typename T> concept Check = std::is_invocable_v<T, const YAML::Node&, gsl::czstring>; template <typename T> concept Attribute = std::is_convertible_v< decltype(std::declval<T>().name), std::string_view> && Check<T>; template <typename T> concept AttrOrStr = String<T> || Attribute<T>; /** YAML scalar. Example: hello: "world" ^ | Scalar scalar() Means that the value has to be a scalar and not a map or a sequence, etc. @return Check function */ constexpr Check auto scalar() { return [](const YAML::Node& node, std::string_view scope) -> result { if (!node || node.IsNull()) return R"("{}" can't be empty.)"_format(scope); if (!node.IsScalar()) return R"("{}" has invalid type.)"_format(scope); return bo::success(); }; } namespace detail { /** Helper class for required and optional YAML fields. @var name Parameter's name @var check Function to apply to the field */ template <Check T> struct functor { gsl::czstring name; T check; constexpr functor(gsl::czstring name, T check) : name{name} , check{check} { } explicit constexpr functor(gsl::czstring name) : functor{name, scalar()} { } }; /** Join YAML path parts. @param a Root path @param b New path @return Concatenation of parts separated by a ".". */ template <String T1, String T2> std::string join(T1&& a, T2&& b) { if (std::empty(a)) return std::forward<T2>(b); return "{}.{}"_format( std::forward<T1>(a), std::forward<T2>(b)); } } // namespace detail /** Requred YAML field. Example: required("hello") Means that the field "hello" is required and it has to be a scalar value. @var name Parameter's name @var check Function to apply to the field */ template <Check T> struct required : detail::functor<T> { using detail::functor<T>::functor; result operator()(const YAML::Node& node, std::string_view scope) const { if (const auto n = node[this->name]) return this->check(n, detail::join(scope, this->name)); return R"("{}" is missing a "{}" attribute.)"_format( scope, this->name); } }; template <Check T> required(gsl::czstring, T) -> required<T>; required(gsl::czstring)->required<decltype(scalar())>; namespace detail { /** Extract the map attribute's name. If an attribute is a string literal, pass the argument as is. @param attr Either an attribute or a string literal @return Attribute name */ constexpr auto attr_name(gsl::czstring attr) { return attr; } constexpr auto attr_name(Attribute auto&& attr) { return attr.name; } /** Extract or construct an attribute check function. If an attrubte is a string literal, construct the required attrubte with the string literal as it's name. @param attr Either an attribute or a string literal @return Check function */ constexpr auto attr_check(gsl::czstring attr) { return required(attr); } constexpr auto attr_check(Attribute auto&& attr) { return attr; } } // namespace detail /** Optional YAML field. Example: optional("hello") Means that the field "hello" is optional and if present, it has to be a scalar value. @var name Parameter's name @var check Function to apply to the field */ template <Check T> struct optional : detail::functor<T> { using detail::functor<T>::functor; result operator()(const YAML::Node& node, std::string_view scope) const { if (const auto n = node[this->name]) return this->check(n, detail::join(scope, this->name)); return bo::success(); } }; template <Check T> optional(gsl::czstring, T) -> optional<T>; optional(gsl::czstring)->optional<decltype(scalar())>; /** YAML array. Validates each value of the array with the provided function. Example: sequence(scalar()) Means that the value has to be a sequence (array) of scalar values. @param check Function to apply to each item @return Check function */ constexpr Check auto sequence(Check auto check) { return [=](const YAML::Node& node, std::string_view scope) -> result { if (!node || !node.IsSequence()) { return R"("{}" is expected to be a sequence.)"_format( scope); } for (gsl::index i{0}; i < std::size(node); ++i) { BOOST_OUTCOME_TRY( check(node[i], "{}[{}]"_format(scope, i))); } return bo::success(); }; } constexpr Check auto sequence() { return sequence(scalar()); } /** YAML map. Matches specified parameters exactly, no extra fields permitted. Example: attributes("first", optional("second")) Means that the value has to be a map with a required field "first", which has to be a scalar and an optional field "second" which also has to be a scalar. @param attrs Sequence of optional or required parameters @return Check function */ constexpr Check auto attributes(AttrOrStr auto... attrs) { return [=](const YAML::Node& node, std::string_view scope = {}) -> result { if (!node || node.IsScalar() || node.IsSequence()) return R"("{}" is expected to be a map.)"_format(scope); flat_set<std::string_view> unique_fields; for (auto&& n : node) { const auto& attr_name = n.first.Scalar(); if (attr_name.empty()) return R"(Empty attribute in "{}".)"_format(scope); if (!unique_fields.emplace(attr_name).second) { return R"(Duplicate attribute "{}" in "{}".)"_format( attr_name, scope); } if (!((attr_name == detail::attr_name(attrs)) || ...)) { return R"(Unexpected attribute "{}" in "{}".)"_format( attr_name, scope); } } result r = bo::success(); ((r = detail::attr_check(attrs)(node, scope)) && ...); return r; }; } /** YAML map. Validates each value of the map with the provided function. Used when the number of map fields may vary. Example: foo: bar1: 1 bar2: 2 bar3: 3 values(scalar()) @param check Function to apply to each value @return Check function */ constexpr Check auto values(Check auto check) { return [=](const YAML::Node& node, std::string_view scope) -> result { if (!node || !node.IsMap()) return R"("{}" is expected to be a map.)"_format(scope); for (auto&& n : node) { BOOST_OUTCOME_TRY(check( n.second, detail::join(scope, n.first.Scalar()))); } return bo::success(); }; } /** Match at least one of the validators. Example: required("example", any_of(scalar(), attributes("foo", "bar"))) Means the value has to either be a singular scalar value or a map with 2 fields "foo" and "bar. example: "hello" or example: foo: 1 bar: 2 @param check Functions to match @return Check function */ constexpr Check auto any_of(Check auto... checks) { return [=](const YAML::Node& node, std::string_view scope) -> result { result r = bo::success(); ((r = checks(node, scope)) || ...); return r; }; } } // namespace angonoka::validation
{ "alphanum_fraction": 0.5800575264, "avg_line_length": 25.0570570571, "ext": "h", "hexsha": "daa03ca1e06c2460e53326e3657a93ad5d029a3d", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "coffee-lord/angonoka", "max_forks_repo_path": "src/config/validation.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_issues_repo_issues_event_max_datetime": "2022-02-12T19:55:52.000Z", "max_issues_repo_issues_event_min_datetime": "2022-02-12T19:52:27.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "coffee-lord/angonoka", "max_issues_repo_path": "src/config/validation.h", "max_line_length": 70, "max_stars_count": 2, "max_stars_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "coffee-lord/angonoka", "max_stars_repo_path": "src/config/validation.h", "max_stars_repo_stars_event_max_datetime": "2022-02-21T21:53:24.000Z", "max_stars_repo_stars_event_min_datetime": "2019-10-23T18:05:25.000Z", "num_tokens": 1963, "size": 8344 }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <float.h> #include <omp.h> #include <math.h> #include "parmt_config.h" #ifdef PARMT_USE_INTEL #include <mkl_cblas.h> #else #include <cblas.h> #endif #include "parmt_mtsearch.h" #include "parmt_utils.h" #include "compearth.h" #include "iscl/array/array.h" #include "iscl/memory/memory.h" #ifndef MAX #define MAX(x,y) (((x) > (y)) ? (x) : (y)) #endif #ifndef MIN #define MIN(x,y) (((x) < (y)) ? (x) : (y)) #endif static int getNpMax(const int iobs, const struct parmtData_struct data, const struct localMT_struct mtloc); /* static int setDataOnG(const int iobs, const int iloc, const int npmax, const struct parmtData_struct data, double *__restrict__ G); */ int parmt_computeL1StationMagnitude64f(const int ldm, const int nmt, const int npts, const int blockSize, const double *__restrict__ Gxx, const double *__restrict__ Gyy, const double *__restrict__ Gzz, const double *__restrict__ Gxy, const double *__restrict__ Gxz, const double *__restrict__ Gyz, const double *__restrict__ mts, const double *__restrict__ d, double *__restrict__ mags); int parmt_locSearchL164f(const MPI_Comm locComm, const int iobs, const int blockSize, const int nlags, const bool lwantLags, const bool lrescale, struct localMT_struct mtloc, struct parmtData_struct *data, const double *__restrict__ CeInv, double *__restrict__ phi, double *__restrict__ var, int *__restrict__ lags) { const char *fcnm = "parmt_locSearchL164f\0"; double *G, *d, *phiLoc, *phiWork, *varLoc, *varWork, xrescaleNum; int *lagLoc, *lagWork, ierr, iloc, jndx, jloc, k, myloc, npmax, nlocProcs, npts; const int master = 0; ierr = 0; myloc =-1; if (mtloc.myid == master) { MPI_Comm_rank(locComm, &myloc); MPI_Comm_size(locComm, &nlocProcs); } MPI_Bcast(&myloc, 1, MPI_INT, master, mtloc.comm); MPI_Bcast(&nlocProcs, 1, MPI_INT, master, mtloc.comm); if (iobs < 0 || iobs >= data->nobs) { printf("%s: Invalid observation number %d\n", fcnm, iobs); return -1; } if (mtloc.ldm <= 6) { printf("%s: Error leading dimension must be at least 6\n", fcnm); return -1; } if (mtloc.mts == NULL || phi == NULL) { if (mtloc.mts == NULL) { fprintf(stderr, "%s: Error mts is NULL\n", __func__); } if (phi == NULL){fprintf(stderr, "%s: Error phi is NULL\n", __func__);} return -1; } npmax = getNpMax(iobs, *data, mtloc); if (npmax < 1) { printf("%s: No data points\n", fcnm); return -1; } // Set space and copy data lagLoc = NULL; lagWork = NULL; varWork = NULL; phiWork = NULL; G = memory_calloc64f(6*npmax); d = memory_calloc64f(npmax); varLoc = array_set64f(npmax, DBL_MAX, &ierr); phiLoc = memory_calloc64f(mtloc.nmt); if (nlocProcs > 1) { if (mtloc.myid == master) { phiWork = memory_calloc64f(data->nlocs*mtloc.nmtAll); varWork = memory_calloc64f(npmax); if (lwantLags) { lagWork = memory_calloc32i(data->nlocs*mtloc.nmtAll); } } else { phiWork = memory_calloc64f(1); varWork = memory_calloc64f(1); lagWork = memory_calloc32i(1); } } else { phiWork = phi; varWork = var; lagWork = lags; } if (lwantLags) { lagLoc = memory_calloc32i(mtloc.nmt); } else { lagLoc = memory_calloc32i(1); } npts = data->data[iobs].npts; cblas_dcopy(npts, data->data[iobs].data, 1, d, 1); for (jloc=0; jloc<data->nlocs; jloc=jloc+nlocProcs) { iloc = jloc + myloc; if (iloc >= data->nlocs){goto NEXT_LOCATION;} k = iobs*data->nlocs + iloc; // Get the Green's functions onto the matrix G ierr = parmt_utils_setDataOnG(iobs, iloc, npmax, *data, G); if (ierr != 0) { printf("%s: Error setting Greens functions\n", fcnm); return -1; } // Tally the objective function ierr = parmt_mtSearchL164f(mtloc.ldm, mtloc.nmt, npts, blockSize, nlags, lwantLags, lrescale, &G[0*npmax], &G[1*npmax], &G[2*npmax], &G[3*npmax], &G[4*npmax], &G[5*npmax], CeInv, mtloc.mts, d, phiLoc, varLoc, lagLoc); if (ierr != 0) { printf("%s: Error calling XC64f search %d %d\n", fcnm, myloc, mtloc.myid); return -1; } // Get the results on the master jndx = 0; if (mtloc.myid == master){jndx = iloc*mtloc.nmtAll;} if (mtloc.commSize == 1) { array_copy64f_work(mtloc.nmt, phiLoc, &phiWork[jndx]); if (lwantLags) { array_copy32i_work(mtloc.nmt, lagLoc, &lagWork[jndx]); } } else { MPI_Gatherv(phiLoc, mtloc.nmt, MPI_DOUBLE, &phiWork[jndx], mtloc.nmtProc, mtloc.offset, MPI_DOUBLE, master, mtloc.comm); if (lwantLags) { MPI_Gatherv(lagLoc, mtloc.nmt, MPI_INT, &lagWork[jndx], mtloc.nmtProc, mtloc.offset, MPI_INT, master, mtloc.comm); } } NEXT_LOCATION:; } // Reduce the variance onto varWork MPI_Reduce(varLoc, varWork, npts, MPI_DOUBLE, MPI_MIN, master, mtloc.comm); // Have the location masters reduce their result onto the master if (mtloc.myid == master) { if (nlocProcs > 1) { MPI_Reduce(phiWork, phi, data->nlocs*mtloc.nmtAll, MPI_DOUBLE, MPI_SUM, master, locComm); MPI_Reduce(varWork, var, npts, MPI_DOUBLE, MPI_MIN, master, locComm); if (lwantLags) { MPI_Reduce(lagWork, lags, data->nlocs*mtloc.nmtAll, MPI_INT, MPI_SUM, master, locComm); } } } cblas_dscal(npts, 1.0/(double) mtloc.nmtAll, varLoc, 1); // Free memory memory_free32i(&lagLoc); memory_free64f(&phiLoc); memory_free64f(&varLoc); memory_free64f(&d); memory_free64f(&G); if (nlocProcs > 1) { memory_free64f(&phiWork); memory_free64f(&varWork); memory_free32i(&lagWork); } phiWork = NULL; lagWork = NULL; // Block until everyone is done if (mtloc.myid == master){MPI_Barrier(locComm);} MPI_Barrier(mtloc.comm); return 0; } int parmt_locSearchXC64f(const MPI_Comm locComm, const int iobs, const int blockSize, const int nlags, const bool lwantLags, struct localMT_struct mtloc, struct parmtData_struct *data, double *__restrict__ phi, int *__restrict__ lags) { const char *fcnm = "parmt_locSearchXC64f\0"; double *G, *d, *phiLoc, *phiWork; int *lagLoc, *lagWork, ierr, iloc, jndx, jloc, k, myloc, npmax, nprocs, npts; const int master = 0; ierr = 0; myloc =-1; if (mtloc.myid == master) { MPI_Comm_rank(locComm, &myloc); MPI_Comm_size(locComm, &nprocs); } MPI_Bcast(&myloc, 1, MPI_INT, master, mtloc.comm); MPI_Bcast(&nprocs, 1, MPI_INT, master, mtloc.comm); if (iobs < 0 || iobs >= data->nobs) { printf("%s: Invalid observation number %d\n", fcnm, iobs); return -1; } if (mtloc.ldm <= 6) { printf("%s: Error leading dimension must be at least 6\n", fcnm); return -1; } if (mtloc.mts == NULL || phi == NULL) { if (mtloc.mts == NULL) { fprintf(stderr, "%s: Error mts is NULL\n", __func__); } if (phi == NULL){fprintf(stderr, "%s: Error phi is NULL\n", __func__);} return -1; } npmax = getNpMax(iobs, *data, mtloc); if (npmax < 1) { printf("%s: No data points\n", fcnm); return -1; } // Set space and copy data G = memory_calloc64f(6*npmax); d = memory_calloc64f(npmax); phiLoc = memory_calloc64f(mtloc.nmt); if (nprocs > 1) { if (mtloc.myid == master) { phiWork = memory_calloc64f(data->nlocs*mtloc.nmtAll); if (lwantLags) { lagWork = memory_calloc32i(data->nlocs*mtloc.nmtAll); } } else { phiWork = memory_calloc64f(1); lagWork = memory_calloc32i(1); } } else { phiWork = phi; lagWork = lags; } if (lwantLags) { lagLoc = memory_calloc32i(mtloc.nmt); } else { lagLoc = memory_calloc32i(1); } npts = data->data[iobs].npts; cblas_dcopy(npts, data->data[iobs].data, 1, d, 1); for (jloc=0; jloc<data->nlocs; jloc=jloc+nprocs) { iloc = jloc + myloc; if (iloc >= data->nlocs){goto NEXT_LOCATION;} k = iobs*data->nlocs + iloc; // Get the Green's functions onto the matrix G ierr = parmt_utils_setDataOnG(iobs, iloc, npmax, *data, G); if (ierr != 0) { printf("%s: Error setting Greens functions\n", fcnm); return -1; } // Tally the objective function ierr = parmt_mtSearchXC64f(mtloc.ldm, mtloc.nmt, npts, blockSize, nlags, lwantLags, &G[0*npmax], &G[1*npmax], &G[2*npmax], &G[3*npmax], &G[4*npmax], &G[5*npmax], mtloc.mts, d, phiLoc, lagLoc); if (ierr != 0) { printf("%s: Error calling XC64f search %d %d\n", fcnm, myloc, mtloc.myid); return -1; } // Get the results on the master jndx = 0; if (mtloc.myid == master){jndx = iloc*mtloc.nmtAll;} MPI_Gatherv(phiLoc, mtloc.nmt, MPI_DOUBLE, &phiWork[jndx], mtloc.nmtProc, mtloc.offset, MPI_DOUBLE, master, mtloc.comm); if (lwantLags) { MPI_Gatherv(lagLoc, mtloc.nmt, MPI_INT, &lagWork[jndx], mtloc.nmtProc, mtloc.offset, MPI_INT, master, mtloc.comm); } NEXT_LOCATION:; MPI_Barrier(mtloc.comm); } // Have the location masters reduce their result onto the master if (mtloc.myid == master && nprocs > 1) { MPI_Reduce(phiWork, phi, data->nlocs*mtloc.nmtAll, MPI_DOUBLE, MPI_SUM, master, locComm); if (lwantLags) { MPI_Reduce(lagWork, lags, data->nlocs*mtloc.nmtAll, MPI_INT, MPI_SUM, master, locComm); } } // Free memory memory_free32i(&lagLoc); memory_free64f(&phiLoc); memory_free64f(&d); memory_free64f(&G); if (nprocs > 1) { memory_free64f(&phiWork); memory_free32i(&lagWork); } phiWork = NULL; lagWork = NULL; return 0; } static int getNpMax(const int iobs, const struct parmtData_struct data, const struct localMT_struct mtloc) { const char *fcnm = "getNpMax\0"; int iloc, k, npmax, npts; const int master = 0; // Get the workspace size npmax = 0; npts = data.data[iobs].header.npts; if (mtloc.myid == master) { for (iloc=0; iloc<data.nlocs; iloc++) { k = iobs*data.nlocs + iloc; npmax = MAX(npmax, data.data[iobs].header.npts); if (data.data[iobs].header.npts != data.sacGxx[k].header.npts || data.data[iobs].header.npts != data.sacGyy[k].header.npts || data.data[iobs].header.npts != data.sacGzz[k].header.npts || data.data[iobs].header.npts != data.sacGxy[k].header.npts || data.data[iobs].header.npts != data.sacGxz[k].header.npts || data.data[iobs].header.npts != data.sacGyz[k].header.npts) { printf("%s: Inconsistent sizes\n", fcnm); npmax = 0; break; } } } MPI_Bcast(&npmax, 1, MPI_INTEGER, master, mtloc.comm); if (npmax < 1) { printf("%s: Error no data points\n", fcnm); return -1; } return npmax; } /* static int setDataOnG(const int iobs, const int iloc, const int npmax, const struct parmtData_struct data, double *__restrict__ G) { const char *fcnm = "setDataOnG\0"; int k; if (iobs < 0 || iobs >= data.nobs) { printf("%s: Error invalid observation\n", fcnm); return -1; } if (iloc < 0 || iloc >= data.nlocs) { printf("%s: Error invalid location\n", fcnm); return -1; } k = iobs*data.nlocs + iloc; if (npmax > data.sacGxx[k].npts || npmax > data.sacGyy[k].npts || npmax > data.sacGzz[k].npts || npmax > data.sacGxy[k].npts || npmax > data.sacGxz[k].npts || npmax > data.sacGyz[k].npts) { printf("%s: npmax is too small\n", fcnm); return -1; } if (data.sacGxx[k].data == NULL || data.sacGyy[k].data == NULL || data.sacGzz[k].data == NULL || data.sacGxy[k].data == NULL || data.sacGxz[k].data == NULL || data.sacGyz[k].data == NULL) { printf("%s: Greens function is null\n", fcnm); return -1; } // Get the Green's functions onto the matrix G array_zeros64f_work(6*npmax, G); cblas_dcopy(data.sacGxx[k].header.npts, data.sacGxx[k].data, 1, &G[0*npmax], 1); cblas_dcopy(data.sacGyy[k].header.npts, data.sacGyy[k].data, 1, &G[1*npmax], 1); cblas_dcopy(data.sacGzz[k].header.npts, data.sacGzz[k].data, 1, &G[2*npmax], 1); cblas_dcopy(data.sacGxy[k].header.npts, data.sacGxy[k].data, 1, &G[3*npmax], 1); cblas_dcopy(data.sacGxz[k].header.npts, data.sacGxz[k].data, 1, &G[4*npmax], 1); cblas_dcopy(data.sacGyz[k].header.npts, data.sacGyz[k].data, 1, &G[5*npmax], 1); return 0; } */
{ "alphanum_fraction": 0.5119817173, "avg_line_length": 33.0064655172, "ext": "c", "hexsha": "1b78ede24bd8e5d2bfbb9566d2b96fdb331b3cf4", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_forks_repo_licenses": [ "Intel" ], "max_forks_repo_name": "bakerb845/parmt", "max_forks_repo_path": "src/locsearch.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Intel" ], "max_issues_repo_name": "bakerb845/parmt", "max_issues_repo_path": "src/locsearch.c", "max_line_length": 79, "max_stars_count": null, "max_stars_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_stars_repo_licenses": [ "Intel" ], "max_stars_repo_name": "bakerb845/parmt", "max_stars_repo_path": "src/locsearch.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4343, "size": 15315 }
/* * Copyright (c) 2016-2021 lymastee, All rights reserved. * Contact: lymastee@hotmail.com * * This file is part of the gslib project. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #pragma once #ifndef vbitset_deeaeda9_1fc9_43e4_9026_c5eeb93c6ebb_h #define vbitset_deeaeda9_1fc9_43e4_9026_c5eeb93c6ebb_h #include <intrin.h> #include <gslib/config.h> #include <gslib/std.h> __gslib_begin__ inline int bit_count(uint n) { uint t = n - ((n >> 1) & 033333333333) - ((n >> 2) & 011111111111); return ((t + (t >> 3)) & 030707070707) % 63; } inline uint bitelim_first_nonzero(uint n) { return n & (n - 1); } inline uint bitmask_first_nonzero(uint n) { return n ^ (n - 1); } inline int bitscan_forward(uint n) { uint p; return _BitScanForward((unsigned long*)&p, n) ? (int)p : -1; } inline int bitscan_reverse(uint n) { uint p; return _BitScanReverse((unsigned long*)&p, n) ? (int)p : -1; } class vbitset { public: typedef vector<uint> container; static const uint knot_size = sizeof(uint) * 8; protected: container _container; int _size; public: vbitset() { _size = 0; } int knot_count() const { return (int)_container.size(); } uint knot_at(int i) const { assert(i < knot_count()); return _container.at(i); } void set_knot(int p, uint k) { if(p >= knot_count()) { assert(!"unexpected."); return; } _container.at(p) = k; } uint& ref_knot_at(int i) { assert(i < knot_count()); return _container.at(i); } int capacity() const { return knot_size * knot_count(); } int size() const { return _size; } int length() const { return _size; } void set(int pos) { reset(pos, true); } void reset(int pos, bool b = false) { int cc = cycle_count(pos); int cidx = cycle_index(pos); ensure_container_capacity(pos, cc, cidx); uint& n = _container.at(cc); uint mask = (1 << cidx); b ? (n |= mask) : (n &= ~mask); } void reset(bool b) { int cc = cycle_count(_size); int cidx = cycle_index(_size); int m = b ? -1 : 0; memset(&_container.front(), m, cc * sizeof(uint)); uint mask = (1 << (cidx + 1)) - 1; uint& n = _container.at(cc); b ? (n |= mask) : (n &= ~mask); } bool test(int pos) { if(pos >= _size) return false; int cc = cycle_count(pos); int cidx = cycle_index(pos); uint n = knot_at(cc); uint mask = (1 << cidx); return (n & mask) != 0; } void resize(int s) { if(s == 0) { _container.clear(); _size = 0; return; } if(s == _size) return; else if(s < _size) { ensure_container_capacity(s - 1); return; } else { int cc = cycle_count(s - 1); _container.resize(cc + 1); _size = s; } } void rotate_left(int bias) { if(!bias) return; if(bias < 0) return rotate_right(-bias); bias %= _size; if(!bias) return; int cc = cycle_count(bias); int cm = cycle_index(bias); rotate_left(cc, cm); } void rotate_right(int bias) { if(!bias) return; if(bias < 0) return rotate_left(-bias); bias %= _size; if(!bias) return; int cc = cycle_count(bias); int cm = cycle_index(bias); rotate_right(cc, cm); } // todo: following void rotate_left(int cc, int cm) { assert(cc >= 0 && cm >= 0); if(!cm) { uint* ptr = new uint[cc]; int crst = (int)_container.size() - cc; memcpy_s(ptr, sizeof(uint) * cc, &_container.front(), _container.capacity()); memcpy_s(&_container.front(), sizeof(uint) * crst, &_container.at(cc), sizeof(uint) * crst); memcpy_s(&_container.front(), sizeof(uint) * cc, ptr, sizeof(uint) * cc); delete [] ptr; } else { } } void rotate_right(int cc, int cm) { assert(cc >= 0 && cm >= 0); } void shift_left(int bias); void shift_right(int bias); void shift_left_1(int bias); void shift_right_1(int bias); public: static int cycle_count(int p) { return p / knot_size; } static int cycle_index(int p) { return p % knot_size; } protected: void ensure_container_capacity(int pos) { if(pos < _size) return; int cc = cycle_count(pos); int cidx = cycle_index(pos); ensure_container_capacity(pos, cc, cidx); } void ensure_container_capacity(int pos, int cc, int cidx) { assert(cc * knot_size + cidx == pos); if(pos < _size) return; int kc = knot_count(); assert(kc <= cc); if(kc == cc) { _container.push_back(0); _size = pos + 1; } else { cc ++; _container.resize(cc); int delta = cc - kc; memset(&_container.at(kc), 0, delta * sizeof(uint)); _size = pos + 1; } } }; __gslib_end__ #endif
{ "alphanum_fraction": 0.54272343, "avg_line_length": 28.9257641921, "ext": "h", "hexsha": "410ddc67f22a6345038063dd7f5a11cde013ce32", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_path": "include/gslib/vbitset.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_path": "include/gslib/vbitset.h", "max_line_length": 105, "max_stars_count": 9, "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_path": "include/gslib/vbitset.h", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "num_tokens": 1657, "size": 6624 }
/* * Created on: Oct. 19, 2019 * Author: Govind */ /* * standard includes */ #include <stdio.h> #include <stdlib.h> /* * includes for GSL components * - use double precision */ #include <gsl/gsl_vector_double.h> #include <gsl/gsl_matrix_double.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> /* * FUNCTIONS */ /* * simple Fibonacci sequence generator function, using recursion * */ size_t fib(size_t k) { if (k==0) { return 0; } else if (k==1) { return 1; } else /* k >= 2 */ { return fib(k-1) + fib(k-2); } } gsl_matrix *embt_mm(const gsl_matrix *U, const gsl_matrix *V, size_t N) { gsl_matrix *W = gsl_matrix_alloc(N,N); double dp; double uk,vk; for (size_t i=0; i != N; ++i) { for (size_t j=0; j != N; ++j) { /* compute element (i,j) of W */ dp = 0; for (size_t k=0; k != N; ++k) { uk = gsl_matrix_get(U,i,k); vk = gsl_matrix_get(V,k,j); dp += uk*vk; } gsl_matrix_set(W,i,j,dp); } } return W; } gsl_vector gsl_print_vector(const gsl_vector V, size_t N) { /* Print the vector*/ for (size_t i = 0; i < N; i++) { printf ("v_%d = %g\n", i, gsl_vector_get (V, i)); } } gsl_matrix embt_print_matrix(const gsl_matrix V, size_t N) { printf("Matrix m\n"); for (size_t i=0;i!=N;i++) { for (size_t j=0;j!=N;j++) { printf("%f ",gsl_matrix_get(V,i,j)); } printf("\n"); } printf("\n"); } int main() { /* * INITIALIZE PARAMETERS */ /* vectors parameters */ size_t N=10; /* index type, vector sizes */ gsl_vector *a = gsl_vector_alloc(N); /* allocate vector from heap of size N */ gsl_vector *b = gsl_vector_alloc(N); /* allocate vector from heap of size N */ gsl_vector *c = gsl_vector_calloc(N); /* allocate vector of size N but initialize entries to zero */ /* random number generator parameters */ const gsl_rng_type *T; gsl_rng *r; /* handle for our random number generator */ /* matrix parameters */ gsl_matrix *A = gsl_matrix_alloc(N,N); gsl_matrix *B = gsl_matrix_alloc(N,N); gsl_matrix *C = gsl_matrix_calloc(N,N); /* * SET UP RANDOM NUMBER GENERATION */ gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc(T); /* * VECTOR OPERATIONS */ /* set the vector elements */ for (size_t i = 0; i != N; ++i) { gsl_vector_set(a, i, fib(i)); /* set element i of vector a to Fibonacci number i */ gsl_vector_set(b, i, gsl_ran_flat(r,-1.0,+1.0)); /* set element of vector b to random number */ } /* c = a + b */ gsl_vector_add(c, a); /* c += a */ gsl_vector_add(c, b); /* c += b */ /* print results */ for (size_t i = 0; i != N; ++i) { printf("i=%d, a(i)=%f, b(i)=%f, c(i)=%f\n", i, gsl_vector_get(a, i), gsl_vector_get(b, i), gsl_vector_get(c, i)); } /* * MATRIX OPERATIONS - your homework!! :) */ /* fill A with first N*N Fibonacci numbers, starting with row 1 (cols 1-10), then row 2, etc. */ for (size_t i=0; i != N; ++i) { for (size_t j = 0; j != N; ++j) { gsl_matrix_set(A, i, j, (double) fib(j+i*N)); } } /* fill B with N*N random numbers, uniformly distributed over the interval (-100, 100) */ for (size_t i=0; i != N; ++i) { for (size_t j = 0; j != N; ++j) { gsl_matrix_set(B, i, j, gsl_ran_flat(r,-100.0,+100.0)); } } /* make C the product of A and B */ C = embt_mm(A,B,N); /* print the results */ embt_print_vector(a,N); embt_print_vector(b,N); embt_print_vector(c,N); embt_print_matrix(A,N); embt_print_matrix(B,N); embt_print_matrix(C,N); /* de-allocate memory */ gsl_vector_free(a); gsl_vector_free(b); gsl_vector_free(c); gsl_matrix_free(A); gsl_matrix_free(B); gsl_matrix_free(C); return EXIT_SUCCESS; }
{ "alphanum_fraction": 0.5928495197, "avg_line_length": 20.4808743169, "ext": "c", "hexsha": "275db3fec01ca520dac1a65ad6c012bc7a97a825", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "febf81fbda55d38a587335057dd561fc486f5103", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "gov466/Embedded-C", "max_forks_repo_path": "C program/DSP/GSL./Matrix_mul.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "febf81fbda55d38a587335057dd561fc486f5103", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "gov466/Embedded-C", "max_issues_repo_path": "C program/DSP/GSL./Matrix_mul.c", "max_line_length": 102, "max_stars_count": 1, "max_stars_repo_head_hexsha": "febf81fbda55d38a587335057dd561fc486f5103", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "gov466/Embedded-C", "max_stars_repo_path": "C program/DSP/GSL./Matrix_mul.c", "max_stars_repo_stars_event_max_datetime": "2021-11-02T15:42:58.000Z", "max_stars_repo_stars_event_min_datetime": "2021-11-02T15:42:58.000Z", "num_tokens": 1267, "size": 3748 }
/* * Gsl_fcmp: test gsl_fcmp (float comparison) * * Copyright (c) 2012 Jérémie Decock * * Required: GSL library (libgsl0-dev) * Usage: gcc gsl_fcmp.c -lgsl -lgslcblas -lm * or: gcc gsl_fcmp.c $(pkg-config --libs gsl) */ #include <gsl/gsl_sys.h> #include <stdio.h> void main(void) { double n1, n2, eps; n1 = 1.0; n2 = 1.1; eps = 0.2; printf("%f ~ %f (+/- %f) : %d\n", n1, n2, eps, gsl_fcmp(n1, n2, eps)); eps = 0.1; printf("%f ~ %f (+/- %f) : %d\n", n1, n2, eps, gsl_fcmp(n1, n2, eps)); eps = 0.05; printf("%f ~ %f (+/- %f) : %d\n", n1, n2, eps, gsl_fcmp(n1, n2, eps)); n1 = 0.01; n2 = 0.0; eps = 0.1; printf("%f ~ %f (+/- %f) : %d\n", n1, n2, eps, gsl_fcmp(n1, n2, eps)); n1 = 0.01; n2 = 0.000001; eps = 0.1; printf("%f ~ %f (+/- %f) : %d\n", n1, n2, eps, gsl_fcmp(n1, n2, eps)); n1 = 1.01; n2 = 1.000001; eps = 0.1; printf("%f ~ %f (+/- %f) : %d\n", n1, n2, eps, gsl_fcmp(n1, n2, eps)); n1 = 0.51; n2 = 0.500001; eps = 0.1; printf("%f ~ %f (+/- %f) : %d\n", n1, n2, eps, gsl_fcmp(n1, n2, eps)); n1 = 0.51; n2 = 0.500001; eps = 0.01; printf("%f ~ %f (+/- %f) : %d\n", n1, n2, eps, gsl_fcmp(n1, n2, eps)); n1 = 0.51; n2 = 0.5; eps = 0.02; printf("%f ~ %f (+/- %f) : %d\n", n1, n2, eps, gsl_fcmp(n1, n2, eps)); }
{ "alphanum_fraction": 0.4594790159, "avg_line_length": 19.7428571429, "ext": "c", "hexsha": "200a08239f337888ca293e85e14807a6df14d5d2", "lang": "C", "max_forks_count": 7, "max_forks_repo_forks_event_max_datetime": "2022-01-04T15:59:45.000Z", "max_forks_repo_forks_event_min_datetime": "2017-10-31T09:48:14.000Z", "max_forks_repo_head_hexsha": "4bd4e7f459eee610d5cf19f845299ca942ff4b64", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jeremiedecock/snippets", "max_forks_repo_path": "c/gsl/gsl_fcmp.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "4bd4e7f459eee610d5cf19f845299ca942ff4b64", "max_issues_repo_issues_event_max_datetime": "2020-10-22T02:36:10.000Z", "max_issues_repo_issues_event_min_datetime": "2020-10-22T02:36:10.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "jeremiedecock/snippets", "max_issues_repo_path": "c/gsl/gsl_fcmp.c", "max_line_length": 74, "max_stars_count": 23, "max_stars_repo_head_hexsha": "4bd4e7f459eee610d5cf19f845299ca942ff4b64", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jeremiedecock/snippets", "max_stars_repo_path": "c/gsl/gsl_fcmp.c", "max_stars_repo_stars_event_max_datetime": "2021-12-30T08:20:04.000Z", "max_stars_repo_stars_event_min_datetime": "2015-06-08T13:01:00.000Z", "num_tokens": 638, "size": 1382 }
/* fit/gsl_fit.h * * Copyright (C) 2000 Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #ifndef __GSL_FIT_H__ #define __GSL_FIT_H__ #include <stdlib.h> #include <gsl/gsl_math.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS int gsl_fit_linear (const double * x, const size_t xstride, const double * y, const size_t ystride, const size_t n, double * c0, double * c1, double * cov00, double * cov01, double * cov11, double * sumsq); int gsl_fit_wlinear (const double * x, const size_t xstride, const double * w, const size_t wstride, const double * y, const size_t ystride, const size_t n, double * c0, double * c1, double * cov00, double * cov01, double * cov11, double * chisq); int gsl_fit_linear_est (const double x, const double c0, const double c1, const double c00, const double c01, const double c11, double *y, double *y_err); int gsl_fit_mul (const double * x, const size_t xstride, const double * y, const size_t ystride, const size_t n, double * c1, double * cov11, double * sumsq); int gsl_fit_wmul (const double * x, const size_t xstride, const double * w, const size_t wstride, const double * y, const size_t ystride, const size_t n, double * c1, double * cov11, double * sumsq); int gsl_fit_mul_est (const double x, const double c1, const double c11, double *y, double *y_err); /* choose better names!! */ int gsl_fit_poly (const double * x, const double * w, const double * y, size_t n, double * c, size_t m, double * chisq); int gsl_fit_fns (const double * A, const double * w, const double * y, size_t n, double * c, size_t m, double * chisq); int gsl_fit_linear_nd (double * m, double * y, double * w); __END_DECLS #endif /* __GSL_FIT_H__ */
{ "alphanum_fraction": 0.5646006784, "avg_line_length": 30.5943396226, "ext": "h", "hexsha": "a906585eb94a1cd5ac47529056cf9f1429008cbf", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_path": "code/em/treba/gsl-1.0/fit/gsl_fit.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_path": "code/em/treba/gsl-1.0/fit/gsl_fit.h", "max_line_length": 73, "max_stars_count": 14, "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_path": "code/em/treba/gsl-1.0/fit/gsl_fit.h", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "num_tokens": 755, "size": 3243 }
/* fit/linear.c * * Copyright (C) 2000 Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_fit.h> /* Fit the data (x_i, y_i) to the linear relationship Y = c0 + c1 x returning, c0, c1 -- coefficients cov00, cov01, cov11 -- variance-covariance matrix of c0 and c1, sumsq -- sum of squares of residuals This fit can be used in the case where the errors for the data are uknown, but assumed equal for all points. The resulting variance-covariance matrix estimates the error in the coefficients from the observed variance of the points around the best fit line. */ int gsl_fit_linear (const double *x, const size_t xstride, const double *y, const size_t ystride, const size_t n, double *c0, double *c1, double *cov_00, double *cov_01, double *cov_11, double *sumsq) { double m_x = 0, m_y = 0, m_dx2 = 0, m_dxdy = 0; size_t i; for (i = 0; i < n; i++) { m_x += (x[i * xstride] - m_x) / (i + 1.0); m_y += (y[i * ystride] - m_y) / (i + 1.0); } for (i = 0; i < n; i++) { const double dx = x[i * xstride] - m_x; const double dy = y[i * ystride] - m_y; m_dx2 += (dx * dx - m_dx2) / (i + 1.0); m_dxdy += (dx * dy - m_dxdy) / (i + 1.0); } /* In terms of y = a + b x */ { double s2 = 0, d2 = 0; double b = m_dxdy / m_dx2; double a = m_y - m_x * b; *c0 = a; *c1 = b; /* Compute chi^2 = \sum (y_i - (a + b * x_i))^2 */ for (i = 0; i < n; i++) { const double dx = x[i * xstride] - m_x; const double dy = y[i * ystride] - m_y; const double d = dy - b * dx; d2 += d * d; } s2 = d2 / (n - 2.0); /* chisq per degree of freedom */ *cov_00 = s2 * (1.0 / n) * (1 + m_x * m_x / m_dx2); *cov_11 = s2 * 1.0 / (n * m_dx2); *cov_01 = s2 * (-m_x) / (n * m_dx2); *sumsq = d2; } return GSL_SUCCESS; } /* Fit the weighted data (x_i, w_i, y_i) to the linear relationship Y = c0 + c1 x returning, c0, c1 -- coefficients s0, s1 -- the standard deviations of c0 and c1, r -- the correlation coefficient between c0 and c1, chisq -- weighted sum of squares of residuals */ int gsl_fit_wlinear (const double *x, const size_t xstride, const double *w, const size_t wstride, const double *y, const size_t ystride, const size_t n, double *c0, double *c1, double *cov_00, double *cov_01, double *cov_11, double *chisq) { /* compute the weighted means and weighted deviations from the means */ /* wm denotes a "weighted mean", wm(f) = (sum_i w_i f_i) / (sum_i w_i) */ double W = 0, wm_x = 0, wm_y = 0, wm_dx2 = 0, wm_dxdy = 0; size_t i; for (i = 0; i < n; i++) { const double wi = w[i * wstride]; if (wi > 0) { W += wi; wm_x += (x[i * xstride] - wm_x) * (wi / W); wm_y += (y[i * ystride] - wm_y) * (wi / W); } } W = 0; /* reset the total weight */ for (i = 0; i < n; i++) { const double wi = w[i * wstride]; if (wi > 0) { const double dx = x[i * xstride] - wm_x; const double dy = y[i * ystride] - wm_y; W += wi; wm_dx2 += (dx * dx - wm_dx2) * (wi / W); wm_dxdy += (dx * dy - wm_dxdy) * (wi / W); } } /* In terms of y = a + b x */ { double d2 = 0; double b = wm_dxdy / wm_dx2; double a = wm_y - wm_x * b; *c0 = a; *c1 = b; *cov_00 = (1 / W) * (1 + wm_x * wm_x / wm_dx2); *cov_11 = 1 / (W * wm_dx2); *cov_01 = -wm_x / (W * wm_dx2); /* Compute chi^2 = \sum w_i (y_i - (a + b * x_i))^2 */ for (i = 0; i < n; i++) { const double wi = w[i * wstride]; if (wi > 0) { const double dx = x[i * xstride] - wm_x; const double dy = y[i * ystride] - wm_y; const double d = dy - b * dx; d2 += wi * d * d; } } *chisq = d2; } return GSL_SUCCESS; } int gsl_fit_linear_est (const double x, const double c0, const double c1, const double c00, const double c01, const double c11, double *y, double *y_err) { *y = c0 + c1 * x; *y_err = sqrt (c00 + x * (2 * c01 + c11 * x)); return GSL_SUCCESS; } int gsl_fit_mul (const double *x, const size_t xstride, const double *y, const size_t ystride, const size_t n, double *c1, double *cov_11, double *sumsq) { double m_x = 0, m_y = 0, m_dx2 = 0, m_dxdy = 0; size_t i; for (i = 0; i < n; i++) { m_x += (x[i * xstride] - m_x) / (i + 1.0); m_y += (y[i * ystride] - m_y) / (i + 1.0); } for (i = 0; i < n; i++) { const double dx = x[i * xstride] - m_x; const double dy = y[i * ystride] - m_y; m_dx2 += (dx * dx - m_dx2) / (i + 1.0); m_dxdy += (dx * dy - m_dxdy) / (i + 1.0); } /* In terms of y = b x */ { double s2 = 0, d2 = 0; double b = (m_x * m_y + m_dxdy) / (m_x * m_x + m_dx2); *c1 = b; /* Compute chi^2 = \sum (y_i - b * x_i)^2 */ for (i = 0; i < n; i++) { const double dx = x[i * xstride] - m_x; const double dy = y[i * ystride] - m_y; const double d = (m_y - b * m_x) + dy - b * dx; d2 += d * d; } s2 = d2 / (n - 1.0); /* chisq per degree of freedom */ *cov_11 = s2 * 1.0 / (n * (m_x * m_x + m_dx2)); *sumsq = d2; } return GSL_SUCCESS; } int gsl_fit_wmul (const double *x, const size_t xstride, const double *w, const size_t wstride, const double *y, const size_t ystride, const size_t n, double *c1, double *cov_11, double *chisq) { /* compute the weighted means and weighted deviations from the means */ /* wm denotes a "weighted mean", wm(f) = (sum_i w_i f_i) / (sum_i w_i) */ double W = 0, wm_x = 0, wm_y = 0, wm_dx2 = 0, wm_dxdy = 0; size_t i; for (i = 0; i < n; i++) { const double wi = w[i * wstride]; if (wi > 0) { W += wi; wm_x += (x[i * xstride] - wm_x) * (wi / W); wm_y += (y[i * ystride] - wm_y) * (wi / W); } } W = 0; /* reset the total weight */ for (i = 0; i < n; i++) { const double wi = w[i * wstride]; if (wi > 0) { const double dx = x[i * xstride] - wm_x; const double dy = y[i * ystride] - wm_y; W += wi; wm_dx2 += (dx * dx - wm_dx2) * (wi / W); wm_dxdy += (dx * dy - wm_dxdy) * (wi / W); } } /* In terms of y = b x */ { double d2 = 0; double b = (wm_x * wm_y + wm_dxdy) / (wm_x * wm_x + wm_dx2); *c1 = b; *cov_11 = 1 / (W * (wm_x * wm_x + wm_dx2)); /* Compute chi^2 = \sum w_i (y_i - b * x_i)^2 */ for (i = 0; i < n; i++) { const double wi = w[i * wstride]; if (wi > 0) { const double dx = x[i * xstride] - wm_x; const double dy = y[i * ystride] - wm_y; const double d = (wm_y - b * wm_x) + (dy - b * dx); d2 += wi * d * d; } } *chisq = d2; } return GSL_SUCCESS; } int gsl_fit_mul_est (const double x, const double c1, const double c11, double *y, double *y_err) { *y = c1 * x; *y_err = sqrt (c11) * fabs (x); return GSL_SUCCESS; }
{ "alphanum_fraction": 0.4975580703, "avg_line_length": 24.1930835735, "ext": "c", "hexsha": "ef5ae5ed055198b360ecfc0889f8646b34705ff7", "lang": "C", "max_forks_count": 40, "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_path": "pkgs/libs/gsl/src/fit/linear.c", "max_issues_count": 12, "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_path": "pkgs/libs/gsl/src/fit/linear.c", "max_line_length": 81, "max_stars_count": 64, "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_path": "pkgs/libs/gsl/src/fit/linear.c", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "num_tokens": 2843, "size": 8395 }
#pragma once #include "iarglist.h" #include "optioninfo.h" #include "configaccess.h" #include "format.h" #include "streamreader.h" #include <gsl/gsl> #include <cmdlime/errors.h> #include <cmdlime/customnames.h> #include <vector> #include <sstream> #include <functional> #include <memory> namespace cmdlime::detail{ template <typename T> class ArgList : public IArgList{ public: ArgList(std::string name, std::string type, std::function<std::vector<T>&()> argListGetter) : info_(std::move(name), {}, std::move(type)) , argListGetter_(std::move(argListGetter)) { } void setDefaultValue(const std::vector<T>& value) { hasValue_ = true; defaultValue_ = value; } OptionInfo& info() override { return info_; } const OptionInfo& info() const override { return info_; } private: bool read(const std::string& data) override { if (!isDefaultValueOverwritten_){ argListGetter_().clear(); isDefaultValueOverwritten_ = true; } auto stream = std::stringstream{data}; argListGetter_().emplace_back(); if (!readFromStream(stream, argListGetter_().back())) return false; hasValue_ = true; return true; } bool hasValue() const override { return hasValue_; } bool isOptional() const override { return defaultValue_.has_value(); } std::string defaultValue() const override { if (!defaultValue_.has_value()) return {}; auto stream = std::stringstream{}; stream << "{"; auto firstVal = true; for (auto& val : defaultValue_.value()){ if (firstVal) stream << val; else stream << ", " << val; firstVal = false; } stream << "}"; return stream.str(); } private: OptionInfo info_; std::function<std::vector<T>&()> argListGetter_; bool hasValue_ = false; std::optional<std::vector<T>> defaultValue_; bool isDefaultValueOverwritten_ = false; }; template <> inline bool ArgList<std::string>::read(const std::string& data) { argListGetter_().push_back(data); hasValue_ = true; return true; } template<typename T, typename TConfig> class ArgListCreator{ using NameProvider = typename Format<ConfigAccess<TConfig>::format()>::nameProvider; public: ArgListCreator(TConfig& cfg, const std::string& varName, const std::string& type, std::function<std::vector<T>&()> argListGetter) : cfg_(cfg) { Expects(!varName.empty()); Expects(!type.empty()); argList_ = std::make_unique<ArgList<T>>(NameProvider::fullName(varName), NameProvider::valueName(type), std::move(argListGetter)); } ArgListCreator<T, TConfig>& operator<<(const std::string& info) { argList_->info().addDescription(info); return *this; } ArgListCreator<T, TConfig>& operator<<(const Name& customName) { argList_->info().resetName(customName.value()); return *this; } ArgListCreator<T, TConfig>& operator<<(const ValueName& valueName) { argList_->info().resetValueName(valueName.value()); return *this; } ArgListCreator<T, TConfig>& operator()(std::vector<T> defaultValue = {}) { defaultValue_ = std::move(defaultValue); argList_->setDefaultValue(defaultValue_); return *this; } operator std::vector<T>() { ConfigAccess<TConfig>{cfg_}.setArgList(std::move(argList_)); return defaultValue_; } private: std::unique_ptr<ArgList<T>> argList_; std::vector<T> defaultValue_; TConfig& cfg_; }; template <typename T, typename TConfig> ArgListCreator<T, TConfig> makeArgListCreator(TConfig& cfg, const std::string& varName, const std::string& type, std::function<std::vector<T>&()> argListGetter) { return ArgListCreator<T, TConfig>{cfg, varName, type, std::move(argListGetter)}; } }
{ "alphanum_fraction": 0.5728952772, "avg_line_length": 26.0892857143, "ext": "h", "hexsha": "3c64f95b80e6c0be7f0a74137aa2c521606b0293", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-05-22T00:36:08.000Z", "max_forks_repo_forks_event_min_datetime": "2021-05-22T00:36:08.000Z", "max_forks_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_forks_repo_licenses": [ "MS-PL" ], "max_forks_repo_name": "GerHobbelt/hypertextcpp", "max_forks_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/arglist.h", "max_issues_count": 6, "max_issues_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_issues_repo_issues_event_max_datetime": "2021-12-21T08:13:28.000Z", "max_issues_repo_issues_event_min_datetime": "2021-05-20T22:04:52.000Z", "max_issues_repo_licenses": [ "MS-PL" ], "max_issues_repo_name": "GerHobbelt/hypertextcpp", "max_issues_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/arglist.h", "max_line_length": 93, "max_stars_count": 77, "max_stars_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_stars_repo_licenses": [ "MS-PL" ], "max_stars_repo_name": "GerHobbelt/hypertextcpp", "max_stars_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/arglist.h", "max_stars_repo_stars_event_max_datetime": "2022-02-13T21:37:54.000Z", "max_stars_repo_stars_event_min_datetime": "2021-05-20T18:05:54.000Z", "num_tokens": 979, "size": 4383 }
#include <bindings.cmacros.h> #include <gsl/gsl_multiroots.h> BC_INLINE3(GSL_MULTIROOT_FN_EVAL,gsl_multiroot_function*,gsl_vector*,gsl_vector*,int) BC_INLINE3(GSL_MULTIROOT_FN_EVAL_F,gsl_multiroot_function_fdf*,gsl_vector*,gsl_vector*,int) BC_INLINE3(GSL_MULTIROOT_FN_EVAL_DF,gsl_multiroot_function_fdf*,gsl_vector*,gsl_matrix*,int) BC_INLINE4(GSL_MULTIROOT_FN_EVAL_F_DF,gsl_multiroot_function_fdf*,gsl_vector*,gsl_vector*,gsl_matrix*,int)
{ "alphanum_fraction": 0.8707482993, "avg_line_length": 55.125, "ext": "c", "hexsha": "f2a08612c0841becab8aea27862a8d69b9abd963", "lang": "C", "max_forks_count": 19, "max_forks_repo_forks_event_max_datetime": "2021-09-10T19:31:38.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-03T20:43:08.000Z", "max_forks_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "flip111/bindings-dsl", "max_forks_repo_path": "bindings-gsl/src/Bindings/Gsl/MultidimensionalRootFinding.c", "max_issues_count": 23, "max_issues_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_issues_repo_issues_event_max_datetime": "2021-04-07T09:49:12.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-04T06:32:10.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "flip111/bindings-dsl", "max_issues_repo_path": "bindings-gsl/src/Bindings/Gsl/MultidimensionalRootFinding.c", "max_line_length": 106, "max_stars_count": 25, "max_stars_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "flip111/bindings-dsl", "max_stars_repo_path": "bindings-gsl/src/Bindings/Gsl/MultidimensionalRootFinding.c", "max_stars_repo_stars_event_max_datetime": "2022-02-06T09:29:03.000Z", "max_stars_repo_stars_event_min_datetime": "2015-04-29T00:31:20.000Z", "num_tokens": 131, "size": 441 }
#include <stdio.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_math.h> #include <gsl/gsl_roots.h> #include <string.h> struct quadratic_params { double a, b, c; }; double quadratic (double x, void *params) { struct quadratic_params *p = (struct quadratic_params *) params; double a = p->a; double b = p->b; double c = p->c; return (a * x + b) * x + c; } double quadratic_deriv (double x, void *params) { struct quadratic_params *p = (struct quadratic_params *) params; double a = p->a; double b = p->b; return 2.0 * a * x + b; } void quadratic_fdf (double x, void *params, double *y, double *dy) { struct quadratic_params *p = (struct quadratic_params *) params; double a = p->a; double b = p->b; double c = p->c; *y = (a * x + b) * x + c; *dy = 2.0 * a * x + b; } int main (int argc, char *argv[]) { int status; int iter = 0, max_iter = 100; const gsl_root_fdfsolver_type *T; gsl_root_fdfsolver *s; double x0, x = 5.0, r_expected = sqrt (5.0); gsl_function_fdf FDF; struct quadratic_params params = {1.0, -2.0, 1.0}; FDF.f = &quadratic; FDF.df = &quadratic_deriv; FDF.fdf = &quadratic_fdf; FDF.params = &params; if (argc < 2) { errno = EINVAL; perror(""); return errno; } char *method = argv[1]; if (0 == strcmp("newton", method)) { T = gsl_root_fdfsolver_newton; } else if (0 == strcmp("secant", method)) { T = gsl_root_fdfsolver_secant; } else if (0 == strcmp("steffenson", method)) { T = gsl_root_fdfsolver_steffenson; } else { errno = EINVAL; perror(""); return errno; } s = gsl_root_fdfsolver_alloc (T); gsl_root_fdfsolver_set (s, &FDF, x); printf ("using %s method\n", gsl_root_fdfsolver_name (s)); printf ("%-5s %10s %10s %10s\n", "iter", "root", "err", "err(est)"); do { iter++; status = gsl_root_fdfsolver_iterate (s); x0 = x; x = gsl_root_fdfsolver_root (s); status = gsl_root_test_delta (x, x0, 0, 1e-3); if (status == GSL_SUCCESS) printf ("Converged:\n"); printf ("%5d %10.7f %+10.7f %10.7f\n", iter, x, x - r_expected, x - x0); } while (status == GSL_CONTINUE && iter < max_iter); gsl_root_fdfsolver_free (s); return status; }
{ "alphanum_fraction": 0.5489878543, "avg_line_length": 22.0535714286, "ext": "c", "hexsha": "6fea89f7cc914e33bf8156c9c4f99c3c29bfe9bc", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "d88c21308b863942497c111d044e359ce220d421", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "mistyfiky/agh-mownit", "max_forks_repo_path": "lab5/zad3.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "d88c21308b863942497c111d044e359ce220d421", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "mistyfiky/agh-mownit", "max_issues_repo_path": "lab5/zad3.c", "max_line_length": 54, "max_stars_count": null, "max_stars_repo_head_hexsha": "d88c21308b863942497c111d044e359ce220d421", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "mistyfiky/agh-mownit", "max_stars_repo_path": "lab5/zad3.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 765, "size": 2470 }
/* specfunc/airy_der.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Author: G. Jungman */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_sf_exp.h> #include <gsl/gsl_sf_airy.h> #include "error.h" #include "chebyshev.h" #include "cheb_eval_mode.c" /*-*-*-*-*-*-*-*-*-*-*-* Private Section *-*-*-*-*-*-*-*-*-*-*-*/ /* based on SLATEC aide.f, bide.f, aid.f, bid.f, r9admp.f */ /* series for aif on the interval -1.00000e+00 to 1.00000e+00 with weighted error 5.22e-18 log weighted error 17.28 significant figures required 16.01 decimal places required 17.73 */ static double aif_data[8] = { 0.10527461226531408809, 0.01183613628152997844, 0.00012328104173225664, 0.00000062261225638140, 0.00000000185298887844, 0.00000000000363328873, 0.00000000000000504622, 0.00000000000000000522 }; static cheb_series aif_cs = { aif_data, 7, -1, 1, 7 }; /* series for aig on the interval -1.00000e+00 to 1.00000e+00 with weighted error 3.14e-19 log weighted error 18.50 significant figures required 17.44 decimal places required 18.98 */ static double aig_data[9] = { 0.021233878150918666852, 0.086315930335214406752, 0.001797594720383231358, 0.000014265499875550693, 0.000000059437995283683, 0.000000000152403366479, 0.000000000000264587660, 0.000000000000000331562, 0.000000000000000000314 }; static cheb_series aig_cs = { aig_data, 8, -1, 1, 8 }; /* series for aip2 on the interval 0.00000e+00 to 1.25000e-01 with weighted error 2.15e-17 log weighted error 16.67 significant figures required 14.27 decimal places required 17.26 */ static double aip2_data[15] = { 0.0065457691989713757, 0.0023833724120774592, -0.0000430700770220586, 0.0000015629125858629, -0.0000000815417186163, 0.0000000054103738057, -0.0000000004284130883, 0.0000000000389497963, -0.0000000000039623161, 0.0000000000004428184, -0.0000000000000536297, 0.0000000000000069650, -0.0000000000000009620, 0.0000000000000001403, -0.0000000000000000215 }; static cheb_series aip2_cs = { aip2_data, 14, -1, 1, 9 }; /* series for aip1 on the interval 1.25000e-01 to 1.00000e+00 with weighted error 2.60e-17 log weighted error 16.58 significant figures required 14.91 decimal places required 17.28 */ static double aip1_data[25] = { 0.0358865097808301538, 0.0114668575627764899, -0.0007592073583861400, 0.0000869517610893841, -0.0000128237294298592, 0.0000022062695681038, -0.0000004222295185921, 0.0000000874686415726, -0.0000000192773588418, 0.0000000044668460054, -0.0000000010790108052, 0.0000000002700029447, -0.0000000000696480108, 0.0000000000184489907, -0.0000000000050027817, 0.0000000000013852243, -0.0000000000003908218, 0.0000000000001121536, -0.0000000000000326862, 0.0000000000000096619, -0.0000000000000028935, 0.0000000000000008770, -0.0000000000000002688, 0.0000000000000000832, -0.0000000000000000260 }; static cheb_series aip1_cs = { aip1_data, 24, -1, 1, 14 }; /* series for bif on the interval -1.00000e+00 to 1.00000e+00 with weighted error 9.05e-18 log weighted error 17.04 significant figures required 15.83 decimal places required 17.49 */ static double bif_data[8] = { 0.1153536790828570243, 0.0205007894049192875, 0.0002135290278902876, 0.0000010783960614677, 0.0000000032094708833, 0.0000000000062930407, 0.0000000000000087403, 0.0000000000000000090 }; static cheb_series bif_cs = { bif_data, 7, -1, 1, 7 }; /* series for big on the interval -1.00000e+00 to 1.00000e+00 with weighted error 5.44e-19 log weighted error 18.26 significant figures required 17.46 decimal places required 18.74 */ static double big_data[9] = { -0.097196440416443537390, 0.149503576843167066571, 0.003113525387121326042, 0.000024708570579821297, 0.000000102949627731379, 0.000000000263970373987, 0.000000000000458279271, 0.000000000000000574283, 0.000000000000000000544 }; static cheb_series big_cs = { big_data, 8, -1, 1, 8 }; /* series for bif2 on the interval 1.00000e+00 to 8.00000e+00 with weighted error 3.82e-19 log weighted error 18.42 significant figures required 17.68 decimal places required 18.92 */ static double bif2_data[10] = { 0.323493987603522033521, 0.086297871535563559139, 0.002994025552655397426, 0.000051430528364661637, 0.000000525840250036811, 0.000000003561751373958, 0.000000000017146864007, 0.000000000000061663520, 0.000000000000000171911, 0.000000000000000000382 }; static cheb_series bif2_cs = { bif2_data, 9, -1, 1, 9 }; /* series for big2 on the interval 1.00000e+00 to 8.00000e+00 with weighted error 3.35e-17 log weighted error 16.48 significant figures required 16.52 decimal places required 16.98 */ static double big2_data[10] = { 1.6062999463621294578, 0.7449088819876088652, 0.0470138738610277380, 0.0012284422062548239, 0.0000173222412256624, 0.0000001521901652368, 0.0000000009113560249, 0.0000000000039547918, 0.0000000000000130017, 0.0000000000000000335 }; static cheb_series big2_cs = { big2_data, 9, -1, 1, 9 }; /* series for bip2 on the interval 0.00000e+00 to 1.25000e-01 with weighted error 2.07e-18 log weighted error 17.69 significant figures required 16.51 decimal places required 18.42 */ static double bip2_data[29] = { -0.13269705443526630495, -0.00568443626045977481, -0.00015643601119611610, -0.00001136737203679562, -0.00000143464350991284, -0.00000018098531185164, 0.00000000926177343611, 0.00000001710005490721, 0.00000000476698163504, -0.00000000035195022023, -0.00000000058890614316, -0.00000000006678499608, 0.00000000006395565102, 0.00000000001554529427, -0.00000000000792397000, -0.00000000000258326243, 0.00000000000121655048, 0.00000000000038707207, -0.00000000000022487045, -0.00000000000004953477, 0.00000000000004563782, 0.00000000000000332998, -0.00000000000000921750, 0.00000000000000094157, 0.00000000000000167154, -0.00000000000000055134, -0.00000000000000022369, 0.00000000000000017487, 0.00000000000000000207 }; static cheb_series bip2_cs = { bip2_data, 28, -1, 1, 14 }; /* series for bip1 on the interval 1.25000e-01 to 3.53553e-01 with weighted error 1.86e-17 log weighted error 16.73 significant figures required 15.67 decimal places required 17.42 */ static double bip1_data[24] = { -0.1729187351079553719, -0.0149358492984694364, -0.0005471104951678566, 0.0001537966292958408, 0.0000154353476192179, -0.0000065434113851906, 0.0000003728082407879, 0.0000002072078388189, -0.0000000658173336470, 0.0000000074926746354, 0.0000000011101336884, -0.0000000007265140553, 0.0000000001782723560, -0.0000000000217346352, -0.0000000000020302035, 0.0000000000019311827, -0.0000000000006044953, 0.0000000000001209450, -0.0000000000000125109, -0.0000000000000019917, 0.0000000000000015154, -0.0000000000000004977, 0.0000000000000001155, -0.0000000000000000186 }; static cheb_series bip1_cs = { bip1_data, 23, -1, 1, 13 }; /* series for an22 on the interval -1.00000e+00 to -1.25000e-01 with weighted error 3.30e-17 log weighted error 16.48 significant figures required 14.95 decimal places required 17.24 */ static double an22_data[33] = { 0.0537418629629794329, -0.0126661435859883193, -0.0011924334106593007, -0.0002032327627275655, -0.0000446468963075164, -0.0000113359036053123, -0.0000031641352378546, -0.0000009446708886149, -0.0000002966562236472, -0.0000000969118892024, -0.0000000326822538653, -0.0000000113144618964, -0.0000000040042691002, -0.0000000014440333684, -0.0000000005292853746, -0.0000000001967763374, -0.0000000000740800096, -0.0000000000282016314, -0.0000000000108440066, -0.0000000000042074801, -0.0000000000016459150, -0.0000000000006486827, -0.0000000000002574095, -0.0000000000001027889, -0.0000000000000412846, -0.0000000000000166711, -0.0000000000000067657, -0.0000000000000027585, -0.0000000000000011296, -0.0000000000000004645, -0.0000000000000001917, -0.0000000000000000794, -0.0000000000000000330 }; static cheb_series an22_cs = { an22_data, 32, -1, 1, 18 }; /* series for an21 on the interval -1.25000e-01 to -1.56250e-02 with weighted error 3.43e-17 log weighted error 16.47 significant figures required 14.48 decimal places required 17.16 */ static double an21_data[24] = { 0.0198313155263169394, -0.0029376249067087533, -0.0001136260695958196, -0.0000100554451087156, -0.0000013048787116563, -0.0000002123881993151, -0.0000000402270833384, -0.0000000084996745953, -0.0000000019514839426, -0.0000000004783865344, -0.0000000001236733992, -0.0000000000334137486, -0.0000000000093702824, -0.0000000000027130128, -0.0000000000008075954, -0.0000000000002463214, -0.0000000000000767656, -0.0000000000000243883, -0.0000000000000078831, -0.0000000000000025882, -0.0000000000000008619, -0.0000000000000002908, -0.0000000000000000993, -0.0000000000000000343 }; static cheb_series an21_cs = { an21_data, 23, -1, 1, 12 }; /* series for an20 on the interval -1.56250e-02 to 0.00000e+00 with weighted error 4.41e-17 log weighted error 16.36 significant figures required 14.16 decimal places required 16.96 */ static double an20_data[16] = { 0.0126732217145738027, -0.0005212847072615621, -0.0000052672111140370, -0.0000001628202185026, -0.0000000090991442687, -0.0000000007438647126, -0.0000000000795494752, -0.0000000000104050944, -0.0000000000015932426, -0.0000000000002770648, -0.0000000000000535343, -0.0000000000000113062, -0.0000000000000025772, -0.0000000000000006278, -0.0000000000000001621, -0.0000000000000000441 }; static cheb_series an20_cs = { an20_data, 15, -1, 1, 8 }; /* series for aph2 on the interval -1.00000e+00 to -1.25000e-01 with weighted error 2.94e-17 log weighted error 16.53 significant figures required 15.58 decimal places required 17.28 */ static double aph2_data[32] = { -0.2057088719781465107, 0.0422196961357771922, 0.0020482560511207275, 0.0002607800735165006, 0.0000474824268004729, 0.0000105102756431612, 0.0000026353534014668, 0.0000007208824863499, 0.0000002103236664473, 0.0000000644975634555, 0.0000000205802377264, 0.0000000067836273921, 0.0000000022974015284, 0.0000000007961306765, 0.0000000002813860610, 0.0000000001011749057, 0.0000000000369306738, 0.0000000000136615066, 0.0000000000051142751, 0.0000000000019351689, 0.0000000000007393607, 0.0000000000002849792, 0.0000000000001107281, 0.0000000000000433412, 0.0000000000000170801, 0.0000000000000067733, 0.0000000000000027017, 0.0000000000000010835, 0.0000000000000004367, 0.0000000000000001769, 0.0000000000000000719, 0.0000000000000000294 }; static cheb_series aph2_cs = { aph2_data, 31, -1, 1, 16 }; /* series for aph1 on the interval -1.25000e-01 to -1.56250e-02 with weighted error 6.38e-17 log weighted error 16.20 significant figures required 14.91 decimal places required 16.87 */ static double aph1_data[22] = { -0.1024172908077571694, 0.0071697275146591248, 0.0001209959363122329, 0.0000073361512841220, 0.0000007535382954272, 0.0000001041478171741, 0.0000000174358728519, 0.0000000033399795033, 0.0000000007073075174, 0.0000000001619187515, 0.0000000000394539982, 0.0000000000101192282, 0.0000000000027092778, 0.0000000000007523806, 0.0000000000002156369, 0.0000000000000635283, 0.0000000000000191757, 0.0000000000000059143, 0.0000000000000018597, 0.0000000000000005950, 0.0000000000000001934, 0.0000000000000000638 }; static cheb_series aph1_cs = { aph1_data, 21, -1, 1, 10 }; /* series for aph0 on the interval -1.56250e-02 to 0.00000e+00 with weighted error 2.29e-17 log weighted error 16.64 significant figures required 15.27 decimal places required 17.23 */ static double aph0_data[15] = { -0.0855849241130933257, 0.0011214378867065261, 0.0000042721029353664, 0.0000000817607381483, 0.0000000033907645000, 0.0000000002253264423, 0.0000000000206284209, 0.0000000000023858763, 0.0000000000003301618, 0.0000000000000527010, 0.0000000000000094555, 0.0000000000000018709, 0.0000000000000004024, 0.0000000000000000930, 0.0000000000000000229 }; static cheb_series aph0_cs = { aph0_data, 14, -1, 1, 7 }; static int airy_deriv_mod_phase(const double x, gsl_mode_t mode, gsl_sf_result * ampl, gsl_sf_result * phi) { const double pi34 = 2.356194490192344928847; gsl_sf_result result_a; gsl_sf_result result_p; double a, p; double sqx; if(x <= -4.0) { double z = 128.0/(x*x*x) + 1.0; cheb_eval_mode_e(&an20_cs, z, mode, &result_a); cheb_eval_mode_e(&aph0_cs, z, mode, &result_p); } else if(x <= -2.0) { double z = (128.0/(x*x*x) + 9.0) / 7.0; cheb_eval_mode_e(&an21_cs, z, mode, &result_a); cheb_eval_mode_e(&aph1_cs, z, mode, &result_p); } else if(x <= -1.0) { double z = (16.0/(x*x*x) + 9.0) / 7.0; cheb_eval_mode_e(&an22_cs, z, mode, &result_a); cheb_eval_mode_e(&aph2_cs, z, mode, &result_p); } else { ampl->val = 0.0; ampl->err = 0.0; phi->val = 0.0; phi->err = 0.0; GSL_ERROR ("x is greater than 1.0", GSL_EDOM); } a = 0.3125 + result_a.val; p = -0.625 + result_p.val; sqx = sqrt(-x); ampl->val = sqrt(a * sqx); ampl->err = fabs(ampl->val) * (GSL_DBL_EPSILON + fabs(result_a.err/result_a.val)); phi->val = pi34 - x * sqx * p; phi->err = fabs(phi->val) * (GSL_DBL_EPSILON + fabs(result_p.err/result_p.val)); return GSL_SUCCESS; } /*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/ int gsl_sf_airy_Ai_deriv_scaled_e(const double x, gsl_mode_t mode, gsl_sf_result * result) { /* CHECK_POINTER(result) */ if(x < -1.0) { gsl_sf_result a; gsl_sf_result p; int status_ap = airy_deriv_mod_phase(x, mode, &a, &p); double c = cos(p.val); result->val = a.val * c; result->err = fabs(result->val * p.err) + fabs(c * a.err); result->err += GSL_DBL_EPSILON * fabs(result->val); return status_ap; } else if(x <= 1.0) { const double x3 = x*x*x; const double x2 = x*x; gsl_sf_result result_c0; gsl_sf_result result_c1; cheb_eval_mode_e(&aif_cs, x3, mode, &result_c0); cheb_eval_mode_e(&aig_cs, x3, mode, &result_c1); result->val = (x2*(0.125 + result_c0.val) - result_c1.val) - 0.25; result->err = fabs(x2*result_c0.val) + result_c1.err; result->err += GSL_DBL_EPSILON * fabs(result->val); if(x > GSL_ROOT3_DBL_EPSILON*GSL_ROOT3_DBL_EPSILON) { /* scale only if x is positive */ double s = exp(2.0*x*sqrt(x)/3.0); result->val *= s; result->err *= s; } return GSL_SUCCESS; } else if(x <= 4.0) { const double sqrtx = sqrt(x); const double z = (16.0/(x*sqrtx) - 9.0)/7.0; const double s = sqrt(sqrtx); gsl_sf_result result_c0; cheb_eval_mode_e(&aip1_cs, z, mode, &result_c0); result->val = -(0.28125 + result_c0.val) * s; result->err = result_c0.err * s; result->err += GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else { const double sqrtx = sqrt(x); const double z = 16.0/(x*sqrtx) - 1.0; const double s = sqrt(sqrtx); gsl_sf_result result_c0; cheb_eval_mode_e(&aip2_cs, z, mode, &result_c0); result->val = -(0.28125 + result_c0.val) * s; result->err = result_c0.err * s; result->err += GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } } int gsl_sf_airy_Ai_deriv_e(const double x, gsl_mode_t mode, gsl_sf_result * result) { /* CHECK_POINTER(result) */ if(x < -1.0) { gsl_sf_result a; gsl_sf_result p; int status_ap = airy_deriv_mod_phase(x, mode, &a, &p); double c = cos(p.val); result->val = a.val * c; result->err = fabs(result->val * p.err) + fabs(c * a.err); result->err += GSL_DBL_EPSILON * fabs(result->val); return status_ap; } else if(x < 1.0) { const double x3 = x*x*x; gsl_sf_result result_c1; gsl_sf_result result_c2; cheb_eval_mode_e(&aif_cs, x3, mode, &result_c1); cheb_eval_mode_e(&aig_cs, x3, mode, &result_c2); result->val = (x*x*(0.125 + result_c1.val) - result_c2.val) - 0.25; result->err = fabs(x*x*result_c1.err) + result_c2.err; result->err += GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else if(x*x*x < 9.0/4.0 * GSL_LOG_DBL_MIN*GSL_LOG_DBL_MIN) { gsl_sf_result result_aps; const double arg = -2.0*x*sqrt(x)/3.0; const int stat_a = gsl_sf_airy_Ai_deriv_scaled_e(x, mode, &result_aps); const int stat_e = gsl_sf_exp_mult_err_e(arg, 1.5*fabs(arg*GSL_DBL_EPSILON), result_aps.val, result_aps.err, result); return GSL_ERROR_SELECT_2(stat_e, stat_a); } else { UNDERFLOW_ERROR(result); } } int gsl_sf_airy_Bi_deriv_scaled_e(const double x, gsl_mode_t mode, gsl_sf_result * result) { const double atr = 8.7506905708484345; /* 16./(sqrt(8)-1) */ const double btr = -2.0938363213560543; /* -(sqrt(8)+1)/(sqrt(8)-1) */ /* CHECK_POINTER(result) */ if(x < -1.0) { gsl_sf_result a; gsl_sf_result p; int status_ap = airy_deriv_mod_phase(x, mode, &a, &p); double s = sin(p.val); result->val = a.val * s; result->err = fabs(result->val * p.err) + fabs(s * a.err); result->err += GSL_DBL_EPSILON * fabs(result->val); return status_ap; } else if(x < 1.0) { const double x3 = x*x*x; const double x2 = x*x; gsl_sf_result result_c1; gsl_sf_result result_c2; cheb_eval_mode_e(&bif_cs, x3, mode, &result_c1); cheb_eval_mode_e(&big_cs, x3, mode, &result_c2); result->val = x2 * (result_c1.val + 0.25) + result_c2.val + 0.5; result->err = x2 * result_c1.err + result_c2.err; result->err += GSL_DBL_EPSILON * fabs(result->val); if(x > GSL_ROOT3_DBL_EPSILON*GSL_ROOT3_DBL_EPSILON) { /* scale only if x is positive */ const double s = exp(-2.0*x*sqrt(x)/3.0); result->val *= s; result->err *= s; } return GSL_SUCCESS; } else if(x < 2.0) { const double z = (2.0*x*x*x - 9.0) / 7.0; const double s = exp(-2.0*x*sqrt(x)/3.0); gsl_sf_result result_c0; gsl_sf_result result_c1; cheb_eval_mode_e(&bif2_cs, z, mode, &result_c0); cheb_eval_mode_e(&big2_cs, z, mode, &result_c1); result->val = s * (x*x * (0.25 + result_c0.val) + 0.5 + result_c1.val); result->err = s * (x*x * result_c0.err + result_c1.err); result->err += GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else if(x < 4.0) { const double sqrtx = sqrt(x); const double z = atr/(x*sqrtx) + btr; const double s = sqrt(sqrtx); gsl_sf_result result_c0; cheb_eval_mode_e(&bip1_cs, z, mode, &result_c0); result->val = s * (0.625 + result_c0.val); result->err = s * result_c0.err; result->err += GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else { const double sqrtx = sqrt(x); const double z = 16.0/(x*sqrtx) - 1.0; const double s = sqrt(sqrtx); gsl_sf_result result_c0; cheb_eval_mode_e(&bip2_cs, z, mode, &result_c0); result->val = s * (0.625 + result_c0.val); result->err = s * result_c0.err; result->err += GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } } int gsl_sf_airy_Bi_deriv_e(const double x, gsl_mode_t mode, gsl_sf_result * result) { /* CHECK_POINTER(result) */ if(x < -1.0) { gsl_sf_result a; gsl_sf_result p; int status_ap = airy_deriv_mod_phase(x, mode, &a, &p); double s = sin(p.val); result->val = a.val * s; result->err = fabs(result->val * p.err) + fabs(s * a.err); result->err += GSL_DBL_EPSILON * fabs(result->val); return status_ap; } else if(x < 1.0) { const double x3 = x*x*x; const double x2 = x*x; gsl_sf_result result_c1; gsl_sf_result result_c2; cheb_eval_mode_e(&bif_cs, x3, mode, &result_c1); cheb_eval_mode_e(&big_cs, x3, mode, &result_c2); result->val = x2 * (result_c1.val + 0.25) + result_c2.val + 0.5; result->err = x2 * result_c1.err + result_c2.err; result->err += GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else if(x < 2.0) { const double z = (2.0*x*x*x - 9.0) / 7.0; gsl_sf_result result_c1; gsl_sf_result result_c2; cheb_eval_mode_e(&bif2_cs, z, mode, &result_c1); cheb_eval_mode_e(&big2_cs, z, mode, &result_c2); result->val = x*x * (result_c1.val + 0.25) + result_c2.val + 0.5; result->err = x*x * result_c1.err + result_c2.err; result->err += GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else if(x < GSL_ROOT3_DBL_MAX*GSL_ROOT3_DBL_MAX) { gsl_sf_result result_bps; const double arg = 2.0*(x*sqrt(x)/3.0); int stat_b = gsl_sf_airy_Bi_deriv_scaled_e(x, mode, &result_bps); int stat_e = gsl_sf_exp_mult_err_e(arg, 1.5*fabs(arg*GSL_DBL_EPSILON), result_bps.val, result_bps.err, result); return GSL_ERROR_SELECT_2(stat_e, stat_b); } else { OVERFLOW_ERROR(result); } } /*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/ #include "eval.h" double gsl_sf_airy_Ai_deriv_scaled(const double x, gsl_mode_t mode) { EVAL_RESULT(gsl_sf_airy_Ai_deriv_scaled_e(x, mode, &result)); } double gsl_sf_airy_Ai_deriv(const double x, gsl_mode_t mode) { EVAL_RESULT(gsl_sf_airy_Ai_deriv_e(x, mode, &result)); } double gsl_sf_airy_Bi_deriv_scaled(const double x, gsl_mode_t mode) { EVAL_RESULT(gsl_sf_airy_Bi_deriv_scaled_e(x, mode, &result)); } double gsl_sf_airy_Bi_deriv(const double x, gsl_mode_t mode) { EVAL_RESULT(gsl_sf_airy_Bi_deriv_e(x, mode, &result)); }
{ "alphanum_fraction": 0.6191499336, "avg_line_length": 28.8590755355, "ext": "c", "hexsha": "45a1c1b7e453c864a2b6af3b2601ccc8ebdc7bc3", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/airy_der.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/airy_der.c", "max_line_length": 86, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/specfunc/airy_der.c", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "num_tokens": 8842, "size": 25598 }
/** * * @file core_dgbelr.c * * PLASMA core_blas kernel * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author Azzam Haidar * @date 2011-05-15 * @generated d Tue Jan 7 11:44:50 2014 * **/ #include <lapacke.h> #include "common.h" #define A(_m, _n) (double *)plasma_geteltaddr(A, ((_m)-1), ((_n)-1), eltsize) #define V(_m) &(V[(_m)-1]) #define TAU(_m) &(TAU[(_m)-1]) /***************************************************************************//** * * @ingroup CORE_double * * CORE_dgbelr is a kernel that will operate on a region (triangle) of data * bounded by st and ed. This kernel eliminate a column by an element-wise * annihiliation, and for each annihiliation, it apply a left update, followed * by an right update on the diagonal 2x2 element, where it create a new nnz, * eliminate it and update V and TAU, then it continue until finishing the the * whole column. When this is done, it take advantage that data are on cache * and will apply the right on the remaining part of this region that has not * been updated by the right yet. * Note that the column to be eliminated is located at st-1. * ******************************************************************************* * * @param[in] uplo * @arg PlasmaLower: * @arg PlasmaUpper: * * @param[in] N * The order of the matrix A. * * @param[in, out] A * A pointer to the descriptor of the matrix A. * * @param[out] V * double array, dimension (N). * The scalar elementary reflectors are written in this * array. So it is used as a workspace for V at each step * of the bulge chasing algorithm. * * @param[out] TAU * double array, dimension (N). * The scalar factors of the elementary reflectors are written * in thisarray. So it is used as a workspace for TAU at each step * of the bulge chasing algorithm. * * @param[in] st * A pointer to the start index where this kernel will operate. * * @param[in] ed * A pointer to the end index where this kernel will operate. * * @param[in] eltsize * PLASMA internal value which refer to the size of the precision. * ******************************************************************************* * * @return * \retval PLASMA_SUCCESS successful exit * \retval <0 if -i, the i-th argument had an illegal value * ******************************************************************************/ /***************************************************************************//** * TYPE 1-BDL Householder * add -1 because of C ******************************************************************************/ int CORE_dgbelr(PLASMA_enum uplo, int N, PLASMA_desc *A, double *V, double *TAU, int st, int ed, int eltsize) { int NB, J1, J2; int len1, len2, t1ed, t2st; int i; static double zzero = 0.0; PLASMA_desc vA=*A; /* Check input arguments */ if (N < 0) { coreblas_error(2, "Illegal value of N"); return -2; } if (ed <= st) { coreblas_error(6, "Illegal value of st and ed (internal)"); return -6; } /* Quick return */ if (N == 0) return PLASMA_SUCCESS; NB = A->mb; if( uplo == PlasmaLower ){ /* ======================== * LOWER CASE * ========================*/ for (i = ed; i >= st+1 ; i--){ /* generate Householder to annihilate a(i+k-1,i) within the band*/ *V(i) = *A(i, (st-1)); *A(i, (st-1)) = zzero; LAPACKE_dlarfg_work( 2, A((i-1),(st-1)), V(i), 1, TAU(i)); /* apply reflector from the left (horizontal row) and from the right for only the diagonal 2x2.*/ J1 = st; J2 = i-2; t1ed = (J2/NB)*NB; t2st = max(t1ed+1,J1); len1 = t1ed-J1+1; len2 = J2-t2st+1; if(len1>0)CORE_dlarfx2(PlasmaLeft, len1 , *V(i), (*TAU(i)), A(i-1, J1 ), ELTLDD(vA, (i-1)), A(i, J1 ), ELTLDD(vA, i) ); if(len2>0)CORE_dlarfx2(PlasmaLeft, len2 , *V(i), (*TAU(i)), A(i-1, t2st), ELTLDD(vA, (i-1)), A(i, t2st), ELTLDD(vA, i) ); CORE_dlarfx2ce(PlasmaLower, V(i), TAU(i), A(i-1,i-1), A(i,i-1), A(i,i)); } /* APPLY RIGHT ON THE REMAINING ELEMENT OF KERNEL 1 */ for (i = ed; i >= st+1 ; i--){ J1 = i+1; J2 = min(ed,N); t1ed = (J2/NB)*NB; t2st = max(t1ed+1,J1); len1 = t1ed-J1+1; len2 = J2-t2st+1; if(len1>0)CORE_dlarfx2(PlasmaRight, len1, (*V(i)), (*TAU(i)), A(J1,i-1), ELTLDD(vA, J1) , A(J1 , i), ELTLDD(vA, J1) ); if(len2>0)CORE_dlarfx2(PlasmaRight, len2, (*V(i)), (*TAU(i)), A(t2st,i-1), ELTLDD(vA, t2st), A(t2st, i), ELTLDD(vA, t2st) ); } } else { /* ======================== * UPPER CASE * ========================*/ for (i = ed; i >= st+1 ; i--){ /* generate Householder to annihilate a(i+k-1,i) within the band*/ *V(i) = *A((st-1), i); *A((st-1), i) = zzero; LAPACKE_dlarfg_work( 2, A((st-1), (i-1)), V(i), 1, TAU(i)); /* apply reflector from the left (horizontal row) and from the right for only the diagonal 2x2.*/ J1 = st; J2 = i-2; t1ed = (J2/NB)*NB; t2st = max(t1ed+1,J1); len1 = t1ed-J1+1; len2 = J2-t2st+1; if(len1>0)CORE_dlarfx2(PlasmaRight, len1, (*V(i)), (*TAU(i)), A(J1,i-1), ELTLDD(vA, J1) , A(J1 , i), ELTLDD(vA, J1) ); if(len2>0)CORE_dlarfx2(PlasmaRight, len2, (*V(i)), (*TAU(i)), A(t2st,i-1), ELTLDD(vA, t2st), A(t2st, i), ELTLDD(vA, t2st) ); CORE_dlarfx2ce(PlasmaUpper, V(i), TAU(i), A((i-1),(i-1)), A((i-1), i), A(i,i)); } /* APPLY LEFT ON THE REMAINING ELEMENT OF KERNEL 1*/ for (i = ed; i >= st+1 ; i--){ J1 = i+1; J2 = min(ed,N); t1ed = (J2/NB)*NB; t2st = max(t1ed+1,J1); len1 = t1ed-J1+1; len2 = J2-t2st+1; if(len1>0)CORE_dlarfx2(PlasmaLeft, len1 , *V(i), (*TAU(i)), A(i-1, J1 ), ELTLDD(vA, (i-1)), A(i, J1 ), ELTLDD(vA, i) ); if(len2>0)CORE_dlarfx2(PlasmaLeft, len2 , *V(i), (*TAU(i)), A(i-1, t2st), ELTLDD(vA, (i-1)), A(i, t2st), ELTLDD(vA, i) ); } } /* end of else for the upper case*/ return PLASMA_SUCCESS; }
{ "alphanum_fraction": 0.4776404825, "avg_line_length": 37.9776536313, "ext": "c", "hexsha": "9a7f107ba33c4c72c6a0a3d3729314a2ca39e878", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_path": "core_blas/core_dgbelr.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_path": "core_blas/core_dgbelr.c", "max_line_length": 136, "max_stars_count": null, "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_path": "core_blas/core_dgbelr.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2136, "size": 6798 }
#ifndef Photometry_h #define Photometry_h /** * @file * $Revision: 1.5 $ * $Date: 2008/07/09 19:40:52 $ * * Unless noted otherwise, the portions of Isis written by the USGS are * public domain. See individual third-party library and package descriptions * for intellectual property information, user agreements, and related * information. * * Although Isis has been used by the USGS, no warranty, expressed or * implied, is made by the USGS as to the accuracy and functioning of such * software and related material nor shall the fact of distribution * constitute any such warranty, and no responsibility is assumed by the * USGS in connection therewith. * * For additional information, launch * $ISISROOT/doc//documents/Disclaimers/Disclaimers.html * in a browser or see the Privacy &amp; Disclaimers page on the Isis website, * http://isis.astrogeology.usgs.gov, and the USGS privacy and disclaimers on * http://www.usgs.gov/privacy.html. */ #include <string> #include <vector> #include <gsl/gsl_errno.h> #include <gsl/gsl_math.h> #include <gsl/gsl_min.h> #include <gsl/gsl_roots.h> namespace Isis { class Pvl; class PhotoModel; class AtmosModel; class NormModel; /** * @author ????-??-?? Unknown * * @internal * @history 2007-08-02 Steven Lambright - Fixed memory leak * @history 2008-03-07 Janet Barrett - Added SetPhotomWl method to allow * the application to set the p_normWavelength variable for * use by MoonAlbedo normalization. * @history 2008-06-18 Steven Koechle - Fixed Documentation Errors * @history 2008-07-09 Steven Lambright - Fixed unit test * @history 2011-08-19 Sharmila Prasad - Implemented brentminimizer using GSL * @history 2011-09-15 Sharmila Prasad - Implemented brent's root solver using GSL */ class Photometry { public: Photometry(Pvl &pvl); Photometry() {}; virtual ~Photometry(); //! Calculate the surface brightness void Compute(double pha, double inc, double ema, double dn, double &albedo, double &mult, double &base); void Compute(double pha, double inc, double ema, double deminc, double demema, double dn, double &albedo, double &mult, double &base); //! Set the wavelength virtual void SetPhotomWl(double wl); //! Double precision version of bracketing algorithm ported from Python. //! Solution bracketing for 1-D minimization routine. static void minbracket(double &xa, double &xb, double &xc, double &fa, double &fb, double &fc, double Func(double par, void *params), void *params); //! Brent's method 1-D minimization routine using GSL's r8Brent minimization Algorithm static int brentminimizer(double x_lower, double x_upper, gsl_function *Func, double & x_minimum, double tolerance); //! GSL's the Brent-Dekker method (Brent's method) combines an interpolation strategy //! with the bisection algorithm to estimate the root of the quadratic function. static int brentsolver(double x_lo, double x_hi, gsl_function *Func, double tolerance, double &root); PhotoModel *GetPhotoModel() const { return p_phtPmodel; } AtmosModel *GetAtmosModel() const { return p_phtAmodel; } NormModel *GetNormModel() const { return p_phtNmodel; } protected: AtmosModel *p_phtAmodel; PhotoModel *p_phtPmodel; NormModel *p_phtNmodel; }; }; #endif
{ "alphanum_fraction": 0.6720221607, "avg_line_length": 35.7425742574, "ext": "h", "hexsha": "2f781d0b521b4bc39c25d207a95bc232c6fd28f2", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-07-12T06:05:03.000Z", "max_forks_repo_forks_event_min_datetime": "2021-07-12T06:05:03.000Z", "max_forks_repo_head_hexsha": "284cc442b773f8369d44379ee29a9b46961d8108", "max_forks_repo_licenses": [ "Unlicense" ], "max_forks_repo_name": "ihumphrey-usgs/ISIS3_old", "max_forks_repo_path": "isis/src/base/objs/Photometry/Photometry.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "284cc442b773f8369d44379ee29a9b46961d8108", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Unlicense" ], "max_issues_repo_name": "ihumphrey-usgs/ISIS3_old", "max_issues_repo_path": "isis/src/base/objs/Photometry/Photometry.h", "max_line_length": 107, "max_stars_count": 1, "max_stars_repo_head_hexsha": "284cc442b773f8369d44379ee29a9b46961d8108", "max_stars_repo_licenses": [ "Unlicense" ], "max_stars_repo_name": "ihumphrey-usgs/ISIS3_old", "max_stars_repo_path": "isis/src/base/objs/Photometry/Photometry.h", "max_stars_repo_stars_event_max_datetime": "2019-10-13T15:31:33.000Z", "max_stars_repo_stars_event_min_datetime": "2019-10-13T15:31:33.000Z", "num_tokens": 919, "size": 3610 }
#ifndef TTT_BOARD_H #define TTT_BOARD_H #include <SDL_rect.h> #include <gsl/util> #include <array> #include <optional> namespace ttt { class Game; enum class CellState { empty, x, o }; class Board final { public: SDL_FPoint pos; SDL_FPoint cellSize; static constexpr int size{3}; CellState preview{CellState::empty}; SDL_Point previewCell{}; Board(const SDL_FPoint &pos, const SDL_FPoint &cellSize, const Game &game) noexcept; void update() noexcept; void render() const noexcept; [[nodiscard]] CellState getCellState(const SDL_Point &pos) const noexcept; void setCellState(const SDL_Point &pos, CellState state) noexcept; void clear() noexcept; [[nodiscard]] std::optional<SDL_Point> getCell(const SDL_Point &point) const noexcept; [[nodiscard]] bool isEmpty() const noexcept; private: const Game &game; std::array<CellState, 9> grid{}; static constexpr float lineWidth{16.0f}; float previewOffset{0.0f}; bool shrinkPreview{false}; const SDL_Rect lineSrc{0, 0, 8, 576}; const SDL_Rect xSrc{8, 0, 48, 48}; const SDL_Rect oSrc{8, 48, 48, 48}; }; inline CellState Board::getCellState(const SDL_Point &pos) const noexcept { return gsl::at(grid, pos.x + pos.y * size); } inline void Board::setCellState(const SDL_Point &pos, CellState state) noexcept { gsl::at(grid, pos.x + pos.y * size) = state; } } #endif
{ "alphanum_fraction": 0.7075812274, "avg_line_length": 20.9848484848, "ext": "h", "hexsha": "6de0dd317a3f7677d6d10e59b0022ff37fa424e5", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "8c70a77e4603dd0ff22ec0621b978ec0685ec3cf", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "itsArtem/TicTacToe", "max_forks_repo_path": "Source/Board.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "8c70a77e4603dd0ff22ec0621b978ec0685ec3cf", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "itsArtem/TicTacToe", "max_issues_repo_path": "Source/Board.h", "max_line_length": 88, "max_stars_count": null, "max_stars_repo_head_hexsha": "8c70a77e4603dd0ff22ec0621b978ec0685ec3cf", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "itsArtem/TicTacToe", "max_stars_repo_path": "Source/Board.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 401, "size": 1385 }
#ifndef TTT_UTIL_FONTCACHE_H #define TTT_UTIL_FONTCACHE_H #include <SDL_ttf.h> #include <gsl/pointers> #include <gsl/util> #include <vector> #include <memory> #include <string_view> namespace ttt::gfx { // A class for caching fonts for reuse. class FontCache final { public: using SizeType = gsl::index; TTF_Font *load(std::string_view path, int size, int index = 0); void unload(SizeType index) noexcept; void erase(SizeType index) noexcept; void clear() noexcept; [[nodiscard]] TTF_Font *at(SizeType index) const noexcept; [[nodiscard]] TTF_Font *operator [](SizeType index) const noexcept; [[nodiscard]] SizeType getSize() const noexcept; [[nodiscard]] SizeType getMaxSize() const noexcept; private: std::vector<std::unique_ptr<TTF_Font, decltype(&TTF_CloseFont)>> fonts; }; inline void FontCache::unload(SizeType index) noexcept { gsl::at(fonts, index).reset(); } inline void FontCache::erase(SizeType index) noexcept { fonts.erase(fonts.cbegin() + index); } inline void FontCache::clear() noexcept { fonts.clear(); } inline TTF_Font *FontCache::at(SizeType index) const noexcept { return gsl::at(fonts, index).get(); } inline TTF_Font *FontCache::operator [](SizeType index) const noexcept { return gsl::at(fonts, index).get(); } inline FontCache::SizeType FontCache::getSize() const noexcept { return fonts.size(); } inline FontCache::SizeType FontCache::getMaxSize() const noexcept { return fonts.max_size(); } } #endif
{ "alphanum_fraction": 0.7286295794, "avg_line_length": 31.3617021277, "ext": "h", "hexsha": "2d407c2decc03885d9d282c22736550b3c32cd81", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "8c70a77e4603dd0ff22ec0621b978ec0685ec3cf", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "itsArtem/TicTacToe", "max_forks_repo_path": "Source/Graphics/FontCache.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "8c70a77e4603dd0ff22ec0621b978ec0685ec3cf", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "itsArtem/TicTacToe", "max_issues_repo_path": "Source/Graphics/FontCache.h", "max_line_length": 111, "max_stars_count": null, "max_stars_repo_head_hexsha": "8c70a77e4603dd0ff22ec0621b978ec0685ec3cf", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "itsArtem/TicTacToe", "max_stars_repo_path": "Source/Graphics/FontCache.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 380, "size": 1474 }
/** * * @file core_claset.c * * PLASMA core_blas kernel * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author Hatem Ltaief * @date 2010-11-15 * @generated c Tue Jan 7 11:44:48 2014 * **/ #include <lapacke.h> #include "common.h" /***************************************************************************//** * * @ingroup CORE_PLASMA_Complex32_t * * CORE_claset - Sets the elements of the matrix A on the diagonal * to beta and on the off-diagonals to alpha * ******************************************************************************* * * @param[in] uplo * Specifies which elements of the matrix are to be set * = PlasmaUpper: Upper part of A is set; * = PlasmaLower: Lower part of A is set; * = PlasmaUpperLower: ALL elements of A are set. * * @param[in] M * The number of rows of the matrix A. M >= 0. * * @param[in] N * The number of columns of the matrix A. N >= 0. * * @param[in] alpha * The constant to which the off-diagonal elements are to be set. * * @param[in] beta * The constant to which the diagonal elements are to be set. * * @param[in,out] A * On entry, the M-by-N tile A. * On exit, A has been set accordingly. * * @param[in] LDA * The leading dimension of the array A. LDA >= max(1,M). * **/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_claset = PCORE_claset #define CORE_claset PCORE_claset #endif void CORE_claset(PLASMA_enum uplo, int M, int N, PLASMA_Complex32_t alpha, PLASMA_Complex32_t beta, PLASMA_Complex32_t *A, int LDA) { LAPACKE_claset_work( LAPACK_COL_MAJOR, lapack_const(uplo), M, N, alpha, beta, A, LDA); }
{ "alphanum_fraction": 0.5685852609, "avg_line_length": 27.7462686567, "ext": "c", "hexsha": "afc9bb42b936c552217303d89d1d79c4eb09c7e0", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_path": "core_blas/core_claset.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_path": "core_blas/core_claset.c", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_path": "core_blas/core_claset.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 507, "size": 1859 }
/* spswap.c * * Copyright (C) 2014 Patrick Alken * Copyright (C) 2016 Alexis Tantet * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_spmatrix.h> #include "avl.c" /* gsl_spmatrix_transpose() Replace the sparse matrix src by its transpose, keeping the matrix in the same storage format Inputs: A - (input/output) sparse matrix to transpose. */ int gsl_spmatrix_transpose(gsl_spmatrix * m) { if (GSL_SPMATRIX_ISTRIPLET(m)) { size_t n; /* swap row/column indices */ for (n = 0; n < m->nz; ++n) { size_t tmp = m->p[n]; m->p[n] = m->i[n]; m->i[n] = tmp; } /* need to rebuild AVL tree, or element searches won't * work correctly with transposed indices */ gsl_spmatrix_tree_rebuild(m); } else { GSL_ERROR("unknown sparse matrix type", GSL_EINVAL); } /* swap dimensions */ if (m->size1 != m->size2) { size_t tmp = m->size1; m->size1 = m->size2; m->size2 = tmp; } return GSL_SUCCESS; } /* gsl_spmatrix_transpose2() Replace the sparse matrix src by its transpose either by swapping its row and column indices if it is in triplet storage, or by switching its major if it is in compressed storage. Inputs: A - (input/output) sparse matrix to transpose. */ int gsl_spmatrix_transpose2(gsl_spmatrix * m) { if (GSL_SPMATRIX_ISTRIPLET(m)) { return gsl_spmatrix_transpose(m); } else if (GSL_SPMATRIX_ISCCS(m)) { m->sptype = GSL_SPMATRIX_CRS; } else if (GSL_SPMATRIX_ISCRS(m)) { m->sptype = GSL_SPMATRIX_CCS; } else { GSL_ERROR("unknown sparse matrix type", GSL_EINVAL); } /* swap dimensions */ if (m->size1 != m->size2) { size_t tmp = m->size1; m->size1 = m->size2; m->size2 = tmp; } return GSL_SUCCESS; } int gsl_spmatrix_transpose_memcpy(gsl_spmatrix *dest, const gsl_spmatrix *src) { const size_t M = src->size1; const size_t N = src->size2; if (M != dest->size2 || N != dest->size1) { GSL_ERROR("dimensions of dest must be transpose of src matrix", GSL_EBADLEN); } else if (dest->sptype != src->sptype) { GSL_ERROR("cannot copy matrices of different storage formats", GSL_EINVAL); } else { int s = GSL_SUCCESS; const size_t nz = src->nz; if (dest->nzmax < src->nz) { s = gsl_spmatrix_realloc(src->nz, dest); if (s) return s; } if (GSL_SPMATRIX_ISTRIPLET(src)) { size_t n; void *ptr; for (n = 0; n < nz; ++n) { dest->i[n] = src->p[n]; dest->p[n] = src->i[n]; dest->data[n] = src->data[n]; /* copy binary tree data */ ptr = avl_insert(dest->tree_data->tree, &dest->data[n]); if (ptr != NULL) { GSL_ERROR("detected duplicate entry", GSL_EINVAL); } } } else if (GSL_SPMATRIX_ISCCS(src)) { size_t *Ai = src->i; size_t *Ap = src->p; double *Ad = src->data; size_t *ATi = dest->i; size_t *ATp = dest->p; double *ATd = dest->data; size_t *w = (size_t *) dest->work; size_t p, j; /* initialize to 0 */ for (p = 0; p < M + 1; ++p) ATp[p] = 0; /* compute row counts of A (= column counts for A^T) */ for (p = 0; p < nz; ++p) ATp[Ai[p]]++; /* compute row pointers for A (= column pointers for A^T) */ gsl_spmatrix_cumsum(M, ATp); /* make copy of row pointers */ for (j = 0; j < M; ++j) w[j] = ATp[j]; for (j = 0; j < N; ++j) { for (p = Ap[j]; p < Ap[j + 1]; ++p) { size_t k = w[Ai[p]]++; ATi[k] = j; ATd[k] = Ad[p]; } } } else if (GSL_SPMATRIX_ISCRS(src)) { size_t *Aj = src->i; size_t *Ap = src->p; double *Ad = src->data; size_t *ATj = dest->i; size_t *ATp = dest->p; double *ATd = dest->data; size_t *w = (size_t *) dest->work; size_t p, i; /* initialize to 0 */ for (p = 0; p < N + 1; ++p) ATp[p] = 0; /* compute column counts of A (= row counts for A^T) */ for (p = 0; p < nz; ++p) ATp[Aj[p]]++; /* compute column pointers for A (= row pointers for A^T) */ gsl_spmatrix_cumsum(N, ATp); /* make copy of column pointers */ for (i = 0; i < N; ++i) w[i] = ATp[i]; for (i = 0; i < M; ++i) { for (p = Ap[i]; p < Ap[i + 1]; ++p) { size_t k = w[Aj[p]]++; ATj[k] = i; ATd[k] = Ad[p]; } } } else { GSL_ERROR("unknown sparse matrix type", GSL_EINVAL); } dest->nz = nz; return s; } } /* gsl_spmatrix_transpose_memcpy() */
{ "alphanum_fraction": 0.5125858124, "avg_line_length": 25.0737704918, "ext": "c", "hexsha": "a54876f6cd87988203523ec58273684f50b9617e", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/spmatrix/spswap.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/spmatrix/spswap.c", "max_line_length": 81, "max_stars_count": 1, "max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_stars_repo_path": "gsl-2.4/spmatrix/spswap.c", "max_stars_repo_stars_event_max_datetime": "2021-01-13T05:01:59.000Z", "max_stars_repo_stars_event_min_datetime": "2021-01-13T05:01:59.000Z", "num_tokens": 1732, "size": 6118 }
/* * Copyright (C) 2021 FISCO BCOS. * SPDX-License-Identifier: Apache-2.0 * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @brief interface for BlockHeader * @file BlockHeader.h * @author: yujiechen * @date: 2021-03-22 */ #pragma once #include "Exceptions.h" #include "ProtocolTypeDef.h" #include <bcos-crypto/interfaces/crypto/CryptoSuite.h> #include <bcos-utilities/DataConvertUtility.h> #include <gsl/span> namespace bcos { namespace protocol { class BlockHeader { public: using Ptr = std::shared_ptr<BlockHeader>; using ConstPtr = std::shared_ptr<const BlockHeader>; using BlockHeadersPtr = std::shared_ptr<std::vector<BlockHeader::Ptr> >; explicit BlockHeader(bcos::crypto::CryptoSuite::Ptr _cryptoSuite) : m_cryptoSuite(_cryptoSuite) {} virtual ~BlockHeader() {} virtual void decode(bytesConstRef _data) = 0; virtual void encode(bytes& _encodeData) const = 0; virtual bcos::crypto::HashType hash() const { return {}; } virtual void populateFromParents(BlockHeadersPtr _parents, BlockNumber _number) { // set parentInfo ParentInfoList parentInfoList; for (auto parentHeader : *_parents) { ParentInfo parentInfo; parentInfo.blockNumber = parentHeader->number(); parentInfo.blockHash = parentHeader->hash(); parentInfoList.emplace_back(parentInfo); } setParentInfo(std::move(parentInfoList)); setNumber(_number); } virtual void clear() = 0; // verifySignatureList verifys the signatureList virtual void verifySignatureList() const { auto signatures = signatureList(); auto sealers = sealerList(); if (signatures.size() < sealers.size()) { BOOST_THROW_EXCEPTION(InvalidBlockHeader() << errinfo_comment( "Invalid blockHeader for the size of sealerList " "is smaller than the size of signatureList")); } for (auto signature : signatures) { auto sealerIndex = signature.index; auto signatureData = signature.signature; if (!m_cryptoSuite->signatureImpl()->verify( std::shared_ptr<const bytes>(&((sealers)[sealerIndex]), [](const bytes*) {}), hash(), bytesConstRef(signatureData.data(), signatureData.size()))) { BOOST_THROW_EXCEPTION( InvalidSignatureList() << errinfo_comment("Invalid signatureList for verify failed, signatureData:" + *toHexString(signatureData))); } } } virtual void populateEmptyBlock( BlockNumber _number, int64_t _sealerId, int64_t _timestamp = utcTime()) { setNumber(_number); setSealer(_sealerId); setTimestamp(_timestamp); } // version returns the version of the blockHeader virtual int32_t version() const = 0; // parentInfo returns the parent information, including (parentBlockNumber, parentHash) virtual gsl::span<const ParentInfo> parentInfo() const = 0; // txsRoot returns the txsRoot of the current block virtual bcos::crypto::HashType txsRoot() const = 0; // receiptsRoot returns the receiptsRoot of the current block virtual bcos::crypto::HashType receiptsRoot() const = 0; // stateRoot returns the stateRoot of the current block virtual bcos::crypto::HashType stateRoot() const = 0; // number returns the number of the current block virtual BlockNumber number() const = 0; virtual u256 gasUsed() const = 0; virtual int64_t timestamp() const = 0; // sealer returns the sealer that generate this block virtual int64_t sealer() const = 0; // sealerList returns the current sealer list virtual gsl::span<const bytes> sealerList() const = 0; virtual bytesConstRef extraData() const = 0; virtual gsl::span<const Signature> signatureList() const = 0; virtual gsl::span<const uint64_t> consensusWeights() const = 0; virtual void setVersion(int32_t _version) = 0; virtual void setParentInfo(gsl::span<const ParentInfo> const& _parentInfo) = 0; virtual void setParentInfo(ParentInfoList&& _parentInfo) = 0; virtual void setTxsRoot(bcos::crypto::HashType _txsRoot) = 0; virtual void setReceiptsRoot(bcos::crypto::HashType _receiptsRoot) = 0; virtual void setStateRoot(bcos::crypto::HashType _stateRoot) = 0; virtual void setNumber(BlockNumber _blockNumber) = 0; virtual void setGasUsed(u256 _gasUsed) = 0; virtual void setTimestamp(int64_t _timestamp) = 0; virtual void setSealer(int64_t _sealerId) = 0; virtual void setSealerList(gsl::span<const bytes> const& _sealerList) = 0; virtual void setSealerList(std::vector<bytes>&& _sealerList) = 0; virtual void setConsensusWeights(gsl::span<const uint64_t> const& _weightList) = 0; virtual void setConsensusWeights(std::vector<uint64_t>&& _weightList) = 0; virtual void setExtraData(bytes const& _extraData) = 0; virtual void setExtraData(bytes&& _extraData) = 0; virtual void setSignatureList(gsl::span<const Signature> const& _signatureList) = 0; virtual void setSignatureList(SignatureList&& _signatureList) = 0; virtual bcos::crypto::CryptoSuite::Ptr cryptoSuite() { return m_cryptoSuite; } protected: bcos::crypto::CryptoSuite::Ptr m_cryptoSuite; }; } // namespace protocol } // namespace bcos
{ "alphanum_fraction": 0.6756085445, "avg_line_length": 40.26, "ext": "h", "hexsha": "af7d77f1df8da912da52e8b13d9ec415571de83f", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "1605c371448b410674559bb1c9e98bab722f036b", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "contropist/FISCO-BCOS", "max_forks_repo_path": "bcos-framework/interfaces/protocol/BlockHeader.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "1605c371448b410674559bb1c9e98bab722f036b", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "contropist/FISCO-BCOS", "max_issues_repo_path": "bcos-framework/interfaces/protocol/BlockHeader.h", "max_line_length": 99, "max_stars_count": null, "max_stars_repo_head_hexsha": "1605c371448b410674559bb1c9e98bab722f036b", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "contropist/FISCO-BCOS", "max_stars_repo_path": "bcos-framework/interfaces/protocol/BlockHeader.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1460, "size": 6039 }
/* histogram/params.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_histogram.h> double gsl_histogram_max (const gsl_histogram * h) { const int n = h->n; return h->range[n]; } double gsl_histogram_min (const gsl_histogram * h) { return h->range[0]; } size_t gsl_histogram_bins (const gsl_histogram * h) { return h->n; }
{ "alphanum_fraction": 0.7259194396, "avg_line_length": 26.5581395349, "ext": "c", "hexsha": "9e2ca120c3dfe6750095d3c3cf8931d0046a6fad", "lang": "C", "max_forks_count": 40, "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_path": "pkgs/libs/gsl/src/histogram/params.c", "max_issues_count": 12, "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_path": "pkgs/libs/gsl/src/histogram/params.c", "max_line_length": 81, "max_stars_count": 64, "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_path": "pkgs/libs/gsl/src/histogram/params.c", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "num_tokens": 302, "size": 1142 }
#include <mpi.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <gsl/gsl_math.h> #include "allvars.h" #include "proto.h" #ifdef MPISENDRECV_CHECKSUM #undef MPI_Sendrecv int MPI_Check_Sendrecv(void *sendbuf, int sendcount, MPI_Datatype sendtype, int dest, int sendtag, void *recvbufreal, int recvcount, MPI_Datatype recvtype, int source, int recvtag, MPI_Comm comm, MPI_Status * status) { int checksumtag = 1000, errtag = 2000; int i, iter = 0, err_flag, err_flag_imported, size_sendtype, size_recvtype; long long sendCheckSum, recvCheckSum, importedCheckSum; unsigned char *p, *buf, *recvbuf; if(dest != source) endrun(3); MPI_Type_size(sendtype, &size_sendtype); MPI_Type_size(recvtype, &size_recvtype); if(dest == ThisTask) { memcpy(recvbufreal, sendbuf, recvcount * size_recvtype); return 0; } if(!(buf = mymalloc(recvcount * size_recvtype + 1024))) endrun(6); for(i = 0, p = buf; i < recvcount * size_recvtype + 1024; i++) *p++ = 255; recvbuf = buf + 512; MPI_Sendrecv(sendbuf, sendcount, sendtype, dest, sendtag, recvbuf, recvcount, recvtype, source, recvtag, comm, status); for(i = 0, p = buf; i < 512; i++, p++) { if(*p != 255) { printf ("MPI-ERROR: Task=%d/%s: Recv occured before recv buffer. message-size=%d from %d, i=%d c=%d\n", ThisTask, getenv("HOST"), recvcount, dest, i, *p); fflush(stdout); endrun(6); } } for(i = 0, p = recvbuf + recvcount * size_recvtype; i < 512; i++, p++) { if(*p != 255) { printf ("MPI-ERROR: Task=%d/%s: Recv occured after recv buffer. message-size=%d from %d, i=%d c=%d\n", ThisTask, getenv("HOST"), recvcount, dest, i, *p); fflush(stdout); endrun(6); } } for(i = 0, p = sendbuf, sendCheckSum = 0; i < sendcount * size_sendtype; i++, p++) sendCheckSum += *p; importedCheckSum = 0; if(dest > ThisTask) { if(sendcount > 0) MPI_Ssend(&sendCheckSum, sizeof(sendCheckSum), MPI_BYTE, dest, checksumtag, MPI_COMM_WORLD); if(recvcount > 0) MPI_Recv(&importedCheckSum, sizeof(importedCheckSum), MPI_BYTE, dest, checksumtag, MPI_COMM_WORLD, status); } else { if(recvcount > 0) MPI_Recv(&importedCheckSum, sizeof(importedCheckSum), MPI_BYTE, dest, checksumtag, MPI_COMM_WORLD, status); if(sendcount > 0) MPI_Ssend(&sendCheckSum, sizeof(sendCheckSum), MPI_BYTE, dest, checksumtag, MPI_COMM_WORLD); } checksumtag++; for(i = 0, p = recvbuf, recvCheckSum = 0; i < recvcount * size_recvtype; i++, p++) recvCheckSum += *p; err_flag = err_flag_imported = 0; if(recvCheckSum != importedCheckSum) { printf ("MPI-ERROR: Receive error on task=%d/%s from task=%d, message size=%d, sendcount=%d checksums= %d %d %d %d. Try to fix it...\n", ThisTask, getenv("HOST"), source, recvcount, sendcount, (int) (recvCheckSum >> 32), (int) recvCheckSum, (int) (importedCheckSum >> 32), (int) importedCheckSum); fflush(stdout); err_flag = 1; } if(dest > ThisTask) { MPI_Ssend(&err_flag, 1, MPI_INT, dest, errtag, MPI_COMM_WORLD); MPI_Recv(&err_flag_imported, 1, MPI_INT, dest, errtag, MPI_COMM_WORLD, status); } else { MPI_Recv(&err_flag_imported, 1, MPI_INT, dest, errtag, MPI_COMM_WORLD, status); MPI_Ssend(&err_flag, 1, MPI_INT, dest, errtag, MPI_COMM_WORLD); } errtag++; if(err_flag > 0 || err_flag_imported > 0) { printf("Task=%d is on %s, wants to send %d and has checksum=%d %d of send data\n", ThisTask, getenv("HOST"), sendcount, (int) (sendCheckSum >> 32), (int) sendCheckSum); fflush(stdout); do { sendtag++; recvtag++; for(i = 0, p = recvbuf; i < recvcount * size_recvtype; i++, p++) *p = 0; if((iter & 1) == 0) { if(dest > ThisTask) { if(sendcount > 0) MPI_Ssend(sendbuf, sendcount, sendtype, dest, sendtag, MPI_COMM_WORLD); if(recvcount > 0) MPI_Recv(recvbuf, recvcount, recvtype, dest, recvtag, MPI_COMM_WORLD, status); } else { if(recvcount > 0) MPI_Recv(recvbuf, recvcount, recvtype, dest, recvtag, MPI_COMM_WORLD, status); if(sendcount > 0) MPI_Ssend(sendbuf, sendcount, sendtype, dest, sendtag, MPI_COMM_WORLD); } } else { if(iter > 5) { printf("we're trying to send each byte now on task=%d (iter=%d)\n", ThisTask, iter); fflush(stdout); if(dest > ThisTask) { for(i = 0, p = sendbuf; i < sendcount * size_sendtype; i++, p++) MPI_Ssend(p, 1, MPI_BYTE, dest, i, MPI_COMM_WORLD); for(i = 0, p = recvbuf; i < recvcount * size_recvtype; i++, p++) MPI_Recv(p, 1, MPI_BYTE, dest, i, MPI_COMM_WORLD, status); } else { for(i = 0, p = recvbuf; i < recvcount * size_recvtype; i++, p++) MPI_Recv(p, 1, MPI_BYTE, dest, i, MPI_COMM_WORLD, status); for(i = 0, p = sendbuf; i < sendcount * size_sendtype; i++, p++) MPI_Ssend(p, 1, MPI_BYTE, dest, i, MPI_COMM_WORLD); } } else { MPI_Sendrecv(sendbuf, sendcount, sendtype, dest, sendtag, recvbuf, recvcount, recvtype, source, recvtag, comm, status); } } importedCheckSum = 0; for(i = 0, p = sendbuf, sendCheckSum = 0; i < sendcount * size_sendtype; i++, p++) sendCheckSum += *p; printf("Task=%d gas send_checksum=%d %d\n", ThisTask, (int) (sendCheckSum >> 32), (int) sendCheckSum); fflush(stdout); if(dest > ThisTask) { if(sendcount > 0) MPI_Ssend(&sendCheckSum, sizeof(sendCheckSum), MPI_BYTE, dest, checksumtag, MPI_COMM_WORLD); if(recvcount > 0) MPI_Recv(&importedCheckSum, sizeof(importedCheckSum), MPI_BYTE, dest, checksumtag, MPI_COMM_WORLD, status); } else { if(recvcount > 0) MPI_Recv(&importedCheckSum, sizeof(importedCheckSum), MPI_BYTE, dest, checksumtag, MPI_COMM_WORLD, status); if(sendcount > 0) MPI_Ssend(&sendCheckSum, sizeof(sendCheckSum), MPI_BYTE, dest, checksumtag, MPI_COMM_WORLD); } for(i = 0, p = recvbuf, recvCheckSum = 0; i < recvcount; i++, p++) recvCheckSum += *p; err_flag = err_flag_imported = 0; if(recvCheckSum != importedCheckSum) { printf ("MPI-ERROR: Again (iter=%d) a receive error on task=%d/%s from task=%d, message size=%d, checksums= %d %d %d %d. Try to fix it...\n", iter, ThisTask, getenv("HOST"), source, recvcount, (int) (recvCheckSum >> 32), (int) recvCheckSum, (int) (importedCheckSum >> 32), (int) importedCheckSum); fflush(stdout); err_flag = 1; } if(dest > ThisTask) { MPI_Ssend(&err_flag, 1, MPI_INT, dest, errtag, MPI_COMM_WORLD); MPI_Recv(&err_flag_imported, 1, MPI_INT, dest, errtag, MPI_COMM_WORLD, status); } else { MPI_Recv(&err_flag_imported, 1, MPI_INT, dest, errtag, MPI_COMM_WORLD, status); MPI_Ssend(&err_flag, 1, MPI_INT, dest, errtag, MPI_COMM_WORLD); } if(err_flag == 0 && err_flag_imported == 0) break; errtag++; checksumtag++; iter++; } while(iter < 10); if(iter >= 10) { char buf[1000]; int length; FILE *fd; sprintf(buf, "send_data_%d.dat", ThisTask); fd = fopen(buf, "w"); length = sendcount * size_sendtype; fwrite(&length, 1, sizeof(int), fd); fwrite(sendbuf, sendcount, size_sendtype, fd); fclose(fd); sprintf(buf, "recv_data_%d.dat", ThisTask); fd = fopen(buf, "w"); length = recvcount * size_recvtype; fwrite(&length, 1, sizeof(int), fd); fwrite(recvbuf, recvcount, size_recvtype, fd); fclose(fd); printf("MPI-ERROR: Even 10 trials proved to be insufficient on task=%d/%s. Stopping\n", ThisTask, getenv("HOST")); fflush(stdout); endrun(10); } } memcpy(recvbufreal, recvbuf, recvcount * size_recvtype); myfree(buf); return 0; } #endif
{ "alphanum_fraction": 0.6243680485, "avg_line_length": 28.0567375887, "ext": "c", "hexsha": "312b98c4172212e65f61967f7aec3b1a1beed0f8", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "egpbos/egp", "max_forks_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/checksummed_sendrecv.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "egpbos/egp", "max_issues_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/checksummed_sendrecv.c", "max_line_length": 137, "max_stars_count": null, "max_stars_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "egpbos/egp", "max_stars_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/checksummed_sendrecv.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2495, "size": 7912 }
//////////////////////////////////////////////////////////// // // Copyright (c) 2018 Sir Ementaler // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // //////////////////////////////////////////////////////////// #ifndef PICTOLEV_TILES_H #define PICTOLEV_TILES_H #include <algorithm> #include <cstddef> #include <iterator> #include <type_traits> #include <vector> #include <gsl/gsl_assert> #include <gsl/gsl_util> #include <gsl/span> #include "grid_size.h" template<class T> using image_fragment = std::vector<gsl::span<T>>; template<class T> auto buffer_to_image(gsl::span<T> buffer, grid_size size) { Expects(gsl::narrow_cast<std::size_t>(buffer.size()) == grid_area(size)); image_fragment<T> image(size.height); std::generate(image.begin(), image.end(), [buffer, width = size.width]() mutable { gsl::span<T> row = buffer.subspan(0, width); buffer = buffer.subspan(width); return row; }); return image; } template<class T> using tile_vector = std::vector<image_fragment<T>>; template<class ForwardIt> auto image_to_tile_list(ForwardIt first, ForwardIt last, std::size_t tile_size) { Expects(std::distance(first, last) % tile_size == 0); Expects(first == last || first->size() % tile_size == 0); using container_type = std::remove_reference_t<typename ForwardIt::reference>; using value_type = std::remove_reference_t<typename container_type::reference>; const grid_size size { first != last ? first->size() / tile_size : 0, std::distance(first, last) / tile_size, }; tile_vector<value_type> tiles(grid_area(size), image_fragment<value_type>(tile_size)); auto out = tiles.begin(); while (first != last) { ForwardIt second = first; std::advance(second, tile_size); for (gsl::index x = 0; x != first->size(); x += tile_size) { std::transform(first, second, out->begin(), [=](const auto& row) { return gsl::span<value_type>(row).subspan(x, tile_size); }); ++out; } first = second; } return tiles; } #endif
{ "alphanum_fraction": 0.6979236437, "avg_line_length": 35.9759036145, "ext": "h", "hexsha": "fef91fb43679177b47e6693114f2b08bcbbb84c4", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "2319122aef4827e0b81294f5177f6f6de08a506c", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "SirEmentaler/PicToLev", "max_forks_repo_path": "PicToLev/include/tiles.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "2319122aef4827e0b81294f5177f6f6de08a506c", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "SirEmentaler/PicToLev", "max_issues_repo_path": "PicToLev/include/tiles.h", "max_line_length": 87, "max_stars_count": null, "max_stars_repo_head_hexsha": "2319122aef4827e0b81294f5177f6f6de08a506c", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "SirEmentaler/PicToLev", "max_stars_repo_path": "PicToLev/include/tiles.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 710, "size": 2986 }
/* Implementation for Gillespie's direct method */ #include <math.h> #include <stdint.h> #include <time.h> #include <stdio.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include "ssa.h" #include "dm.h" const gsl_rng_type *SSARNGT; gsl_rng *SSARNG; INDEX nextreaction(double *propensities, INDEX m) { double r1 = gsl_ran_flat(SSARNG, 0.0, 1.0) * propensities[m - 1]; INDEX i = 0; for(i = 0; i < m; i++) if(r1 <= propensities[i]) return i; return -1; } /* Perform one step of the Gillespie direct method, selecting a reaction to perform and altering molecule counts and time accordingly. */ void ssa_dmstep(INDEX n, INDEX m, double *propensities, INDEX **R, INDEX **P, double *k, COUNT *x, double *t) { propensities[0] = ssa_h(R[0], x, n) * k[0]; INDEX i; for (i = 1; i < m; i++) propensities[i] = ssa_h(R[i], x, n) * k[i] + propensities[i - 1]; if (propensities[m - 1] > 0.0) { *t += gsl_ran_exponential(SSARNG, 1 / propensities[m - 1]); INDEX next = nextreaction(propensities, m); ssa_doreaction(R[next], P[next], x, n); } } void ssa_dm(INDEX **R, INDEX **P, INDEX n, INDEX m, double *k, COUNT *x, double T) { gsl_rng_env_setup(); SSARNGT = gsl_rng_default; SSARNG = gsl_rng_alloc(SSARNGT); gsl_rng_set(SSARNG, time(NULL)); double t = 0.0; double *propensities = malloc(sizeof(double) * m); do { ssa_dmstep(n, m, propensities, R, P, k, x, &t); ssa_printstate(t, x, n); } while(t < T && propensities[m - 1] > 0.0); free(propensities); }
{ "alphanum_fraction": 0.6457369465, "avg_line_length": 22.5820895522, "ext": "c", "hexsha": "abd13f506beb9f0c6bb12454d6760407ea6a9d62", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "f8366e11609bdaa0bb7997dc4177d6e6a5eabeb9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "lgrozinger/ssapy", "max_forks_repo_path": "lib/src/dm.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "f8366e11609bdaa0bb7997dc4177d6e6a5eabeb9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "lgrozinger/ssapy", "max_issues_repo_path": "lib/src/dm.c", "max_line_length": 109, "max_stars_count": null, "max_stars_repo_head_hexsha": "f8366e11609bdaa0bb7997dc4177d6e6a5eabeb9", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "lgrozinger/ssapy", "max_stars_repo_path": "lib/src/dm.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 528, "size": 1513 }
/* movstat/test_minmax.c * * Copyright (C) 2018 Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_test.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_movstat.h> /* compute filtered data by explicitely constructing window and finding min/max */ int slow_minmax(const gsl_movstat_end_t etype, const gsl_vector * x, gsl_vector * y_min, gsl_vector * y_max, const int H, const int J) { const size_t n = x->size; const int K = H + J + 1; double *window = malloc(K * sizeof(double)); size_t i; for (i = 0; i < n; ++i) { size_t wsize = gsl_movstat_fill(etype, x, i, H, J, window); gsl_vector_view v = gsl_vector_view_array(window, wsize); double min, max; gsl_vector_minmax(&v.vector, &min, &max); gsl_vector_set(y_min, i, min); gsl_vector_set(y_max, i, max); } free(window); return GSL_SUCCESS; } static double func_min(const size_t n, double x[], void * params) { gsl_vector_view v = gsl_vector_view_array(x, n); (void) params; return gsl_vector_min(&v.vector); } static double func_max(const size_t n, double x[], void * params) { gsl_vector_view v = gsl_vector_view_array(x, n); (void) params; return gsl_vector_max(&v.vector); } static void test_minmax_x(const double tol, const gsl_vector * x, const int H, const int J, const gsl_movstat_end_t endtype, const char * desc) { const size_t n = x->size; gsl_vector * u_min = gsl_vector_alloc(n); gsl_vector * y_min = gsl_vector_alloc(n); gsl_vector * z_min = gsl_vector_alloc(n); gsl_vector * u_max = gsl_vector_alloc(n); gsl_vector * y_max = gsl_vector_alloc(n); gsl_vector * z_max = gsl_vector_alloc(n); gsl_movstat_workspace * w = gsl_movstat_alloc2(H, J); gsl_movstat_function F1, F2; char buf[2048]; F1.function = func_min; F1.params = NULL; F2.function = func_max; F2.params = NULL; /* compute moving min/max */ gsl_movstat_min(endtype, x, u_min, w); gsl_movstat_max(endtype, x, u_max, w); gsl_movstat_minmax(endtype, x, y_min, y_max, w); /* compute moving min/max with slow brute force method */ slow_minmax(endtype, x, z_min, z_max, H, J); sprintf(buf, "test_minmax: %s min endtype=%d n=%zu H=%d J=%d", desc, endtype, n, H, J); compare_vectors(tol, u_min, z_min, buf); sprintf(buf, "test_minmax: %s max endtype=%d n=%zu H=%d J=%d", desc, endtype, n, H, J); compare_vectors(tol, u_max, z_max, buf); sprintf(buf, "test_minmax: %s minmax(minimum) endtype=%d n=%zu H=%d J=%d", desc, endtype, n, H, J); compare_vectors(tol, y_min, z_min, buf); sprintf(buf, "test_minmax: %s minmax(maximum) endtype=%d n=%zu H=%d J=%d", desc, endtype, n, H, J); compare_vectors(tol, y_max, z_max, buf); /* in-place tests */ gsl_vector_memcpy(u_min, x); gsl_vector_memcpy(u_max, x); gsl_movstat_min(endtype, u_min, u_min, w); gsl_movstat_max(endtype, u_max, u_max, w); sprintf(buf, "test_minmax: %s in-place min endtype=%d n=%zu H=%d J=%d", desc, endtype, n, H, J); compare_vectors(tol, u_min, z_min, buf); sprintf(buf, "test_minmax: %s in-place max endtype=%d n=%zu H=%d J=%d", desc, endtype, n, H, J); compare_vectors(tol, u_max, z_max, buf); /* user-defined function tests */ gsl_movstat_apply(endtype, &F1, x, z_min, w); sprintf(buf, "n=%zu H=%d J=%d endtype=%u min user", n, H, J, endtype); compare_vectors(tol, z_min, y_min, buf); gsl_movstat_apply(endtype, &F2, x, z_max, w); sprintf(buf, "n=%zu H=%d J=%d endtype=%u max user", n, H, J, endtype); compare_vectors(tol, z_max, y_max, buf); gsl_vector_free(u_min); gsl_vector_free(y_min); gsl_vector_free(z_min); gsl_vector_free(u_max); gsl_vector_free(y_max); gsl_vector_free(z_max); gsl_movstat_free(w); } /* test alternating sequence [a,b,a,b,...] input */ static void test_minmax_alt(const double tol, const size_t n, const int H, const int J, const gsl_movstat_end_t endtype) { const double a = 5.0; const double b = -5.0; gsl_vector * x = gsl_vector_alloc(n); size_t i; for (i = 0; i < n; ++i) { if (i % 2 == 0) gsl_vector_set(x, i, a); else gsl_vector_set(x, i, b); } test_minmax_x(tol, x, H, J, endtype, "alternating"); gsl_vector_free(x); } /* test noisy sine wave input */ static void test_minmax_sine(const double tol, const size_t n, const int H, const int J, const gsl_movstat_end_t endtype, gsl_rng * rng_p) { gsl_vector * x = gsl_vector_alloc(n); /* construct noisy sine signal */ test_noisy_sine(0.5, x, rng_p); test_minmax_x(tol, x, H, J, endtype, "noisy_sine"); gsl_vector_free(x); } /* test random input */ static void test_minmax_random(const double tol, const size_t n, const int H, const int J, const gsl_movstat_end_t endtype, gsl_rng * rng_p) { gsl_vector * x = gsl_vector_alloc(n); /* construct random input signal */ random_vector(x, rng_p); test_minmax_x(tol, x, H, J, endtype, "random"); gsl_vector_free(x); } static void test_minmax(gsl_rng * rng_p) { /* alternating input */ test_minmax_alt(GSL_DBL_EPSILON, 1000, 7, 7, GSL_MOVSTAT_END_PADZERO); test_minmax_alt(GSL_DBL_EPSILON, 1000, 5, 2, GSL_MOVSTAT_END_PADZERO); test_minmax_alt(GSL_DBL_EPSILON, 500, 1, 3, GSL_MOVSTAT_END_PADZERO); test_minmax_alt(GSL_DBL_EPSILON, 20, 50, 10, GSL_MOVSTAT_END_PADZERO); test_minmax_alt(GSL_DBL_EPSILON, 20, 10, 50, GSL_MOVSTAT_END_PADZERO); /* noisy sine wave input */ test_minmax_sine(GSL_DBL_EPSILON, 1000, 5, 7, GSL_MOVSTAT_END_PADZERO, rng_p); test_minmax_sine(GSL_DBL_EPSILON, 2000, 0, 2, GSL_MOVSTAT_END_PADZERO, rng_p); test_minmax_sine(GSL_DBL_EPSILON, 500, 3, 0, GSL_MOVSTAT_END_PADZERO, rng_p); test_minmax_sine(GSL_DBL_EPSILON, 20, 50, 50, GSL_MOVSTAT_END_PADZERO, rng_p); test_minmax_sine(GSL_DBL_EPSILON, 20, 10, 50, GSL_MOVSTAT_END_PADZERO, rng_p); test_minmax_sine(GSL_DBL_EPSILON, 20, 50, 10, GSL_MOVSTAT_END_PADZERO, rng_p); test_minmax_sine(GSL_DBL_EPSILON, 500, 5, 7, GSL_MOVSTAT_END_PADVALUE, rng_p); test_minmax_sine(GSL_DBL_EPSILON, 1000, 10, 20, GSL_MOVSTAT_END_PADVALUE, rng_p); test_minmax_sine(GSL_DBL_EPSILON, 1000, 3, 3, GSL_MOVSTAT_END_PADVALUE, rng_p); test_minmax_sine(GSL_DBL_EPSILON, 20, 50, 50, GSL_MOVSTAT_END_PADVALUE, rng_p); test_minmax_sine(GSL_DBL_EPSILON, 20, 10, 50, GSL_MOVSTAT_END_PADVALUE, rng_p); test_minmax_sine(GSL_DBL_EPSILON, 20, 50, 10, GSL_MOVSTAT_END_PADVALUE, rng_p); test_minmax_sine(GSL_DBL_EPSILON, 500, 5, 7, GSL_MOVSTAT_END_TRUNCATE, rng_p); test_minmax_sine(GSL_DBL_EPSILON, 1000, 10, 20, GSL_MOVSTAT_END_TRUNCATE, rng_p); test_minmax_sine(GSL_DBL_EPSILON, 1000, 3, 3, GSL_MOVSTAT_END_TRUNCATE, rng_p); test_minmax_sine(GSL_DBL_EPSILON, 1000, 30, 5, GSL_MOVSTAT_END_TRUNCATE, rng_p); test_minmax_sine(GSL_DBL_EPSILON, 1000, 5, 30, GSL_MOVSTAT_END_TRUNCATE, rng_p); test_minmax_sine(GSL_DBL_EPSILON, 20, 50, 50, GSL_MOVSTAT_END_TRUNCATE, rng_p); test_minmax_sine(GSL_DBL_EPSILON, 20, 10, 50, GSL_MOVSTAT_END_TRUNCATE, rng_p); test_minmax_sine(GSL_DBL_EPSILON, 20, 50, 10, GSL_MOVSTAT_END_TRUNCATE, rng_p); /* random input */ test_minmax_random(GSL_DBL_EPSILON, 1000, 0, 0, GSL_MOVSTAT_END_PADZERO, rng_p); test_minmax_random(GSL_DBL_EPSILON, 1000, 5, 7, GSL_MOVSTAT_END_PADZERO, rng_p); test_minmax_random(GSL_DBL_EPSILON, 2000, 0, 2, GSL_MOVSTAT_END_PADZERO, rng_p); test_minmax_random(GSL_DBL_EPSILON, 500, 3, 0, GSL_MOVSTAT_END_PADZERO, rng_p); test_minmax_random(GSL_DBL_EPSILON, 500, 10, 5, GSL_MOVSTAT_END_PADZERO, rng_p); test_minmax_random(GSL_DBL_EPSILON, 500, 5, 10, GSL_MOVSTAT_END_PADZERO, rng_p); test_minmax_random(GSL_DBL_EPSILON, 20, 50, 50, GSL_MOVSTAT_END_PADZERO, rng_p); test_minmax_random(GSL_DBL_EPSILON, 20, 10, 50, GSL_MOVSTAT_END_PADZERO, rng_p); test_minmax_random(GSL_DBL_EPSILON, 20, 50, 10, GSL_MOVSTAT_END_PADZERO, rng_p); test_minmax_random(GSL_DBL_EPSILON, 1000, 0, 0, GSL_MOVSTAT_END_PADVALUE, rng_p); test_minmax_random(GSL_DBL_EPSILON, 1000, 5, 7, GSL_MOVSTAT_END_PADVALUE, rng_p); test_minmax_random(GSL_DBL_EPSILON, 2000, 0, 2, GSL_MOVSTAT_END_PADVALUE, rng_p); test_minmax_random(GSL_DBL_EPSILON, 500, 3, 0, GSL_MOVSTAT_END_PADVALUE, rng_p); test_minmax_random(GSL_DBL_EPSILON, 500, 10, 5, GSL_MOVSTAT_END_PADVALUE, rng_p); test_minmax_random(GSL_DBL_EPSILON, 500, 5, 10, GSL_MOVSTAT_END_PADVALUE, rng_p); test_minmax_random(GSL_DBL_EPSILON, 20, 50, 50, GSL_MOVSTAT_END_PADVALUE, rng_p); test_minmax_random(GSL_DBL_EPSILON, 20, 10, 50, GSL_MOVSTAT_END_PADVALUE, rng_p); test_minmax_random(GSL_DBL_EPSILON, 20, 50, 10, GSL_MOVSTAT_END_PADVALUE, rng_p); test_minmax_random(GSL_DBL_EPSILON, 1000, 0, 0, GSL_MOVSTAT_END_TRUNCATE, rng_p); test_minmax_random(GSL_DBL_EPSILON, 1000, 5, 7, GSL_MOVSTAT_END_TRUNCATE, rng_p); test_minmax_random(GSL_DBL_EPSILON, 2000, 0, 2, GSL_MOVSTAT_END_TRUNCATE, rng_p); test_minmax_random(GSL_DBL_EPSILON, 500, 3, 0, GSL_MOVSTAT_END_TRUNCATE, rng_p); test_minmax_random(GSL_DBL_EPSILON, 500, 10, 5, GSL_MOVSTAT_END_TRUNCATE, rng_p); test_minmax_random(GSL_DBL_EPSILON, 500, 5, 10, GSL_MOVSTAT_END_TRUNCATE, rng_p); test_minmax_random(GSL_DBL_EPSILON, 20, 50, 50, GSL_MOVSTAT_END_TRUNCATE, rng_p); test_minmax_random(GSL_DBL_EPSILON, 20, 10, 50, GSL_MOVSTAT_END_TRUNCATE, rng_p); test_minmax_random(GSL_DBL_EPSILON, 20, 50, 10, GSL_MOVSTAT_END_TRUNCATE, rng_p); }
{ "alphanum_fraction": 0.7296497287, "avg_line_length": 38.536121673, "ext": "c", "hexsha": "bcc2a2a5fc4f8d77b6dbbf805c54b7110849848a", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_path": "test/lib/gsl-2.6/movstat/test_minmax.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_path": "gsl-2.6/movstat/test_minmax.c", "max_line_length": 104, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/movstat/test_minmax.c", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "num_tokens": 3402, "size": 10135 }
#include <stdio.h> #include <gsl/gsl_cdf.h> int main (void) { double P, Q; double x = 2.0; P = gsl_cdf_ugaussian_P (x); printf ("prob(x < %f) = %f\n", x, P); Q = gsl_cdf_ugaussian_Q (x); printf ("prob(x > %f) = %f\n", x, Q); x = gsl_cdf_ugaussian_Pinv (P); printf ("Pinv(%f) = %f\n", P, x); x = gsl_cdf_ugaussian_Qinv (Q); printf ("Qinv(%f) = %f\n", Q, x); return 0; }
{ "alphanum_fraction": 0.5491183879, "avg_line_length": 16.5416666667, "ext": "c", "hexsha": "968eb96dfaac2ece0583e9b4d98343d1d1162d53", "lang": "C", "max_forks_count": 40, "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/cdf.c", "max_issues_count": 12, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/cdf.c", "max_line_length": 39, "max_stars_count": 64, "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_path": "pkgs/libs/gsl/src/doc/examples/cdf.c", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "num_tokens": 167, "size": 397 }
/* eigen/genv.c * * Copyright (C) 2007 Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <stdlib.h> #include <math.h> #include <config.h> #include <gsl/gsl_eigen.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_math.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_vector_complex.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_errno.h> /* * This module computes the eigenvalues and eigenvectors of a * real generalized eigensystem A x = \lambda B x. Left and right * Schur vectors are optionally computed as well. * * This file contains routines based on original code from LAPACK * which is distributed under the modified BSD license. */ static int genv_get_right_eigenvectors(const gsl_matrix *S, const gsl_matrix *T, gsl_matrix *Z, gsl_matrix_complex *evec, gsl_eigen_genv_workspace *w); static void genv_normalize_eigenvectors(gsl_vector_complex *alpha, gsl_matrix_complex *evec); /* gsl_eigen_genv_alloc() Allocate a workspace for solving the generalized eigenvalue problem. The size of this workspace is O(7n). Inputs: n - size of matrices Return: pointer to workspace */ gsl_eigen_genv_workspace * gsl_eigen_genv_alloc(const size_t n) { gsl_eigen_genv_workspace *w; if (n == 0) { GSL_ERROR_NULL ("matrix dimension must be positive integer", GSL_EINVAL); } w = (gsl_eigen_genv_workspace *) calloc (1, sizeof (gsl_eigen_genv_workspace)); if (w == 0) { GSL_ERROR_NULL ("failed to allocate space for workspace", GSL_ENOMEM); } w->size = n; w->Q = NULL; w->Z = NULL; w->gen_workspace_p = gsl_eigen_gen_alloc(n); if (w->gen_workspace_p == 0) { gsl_eigen_genv_free(w); GSL_ERROR_NULL ("failed to allocate space for gen workspace", GSL_ENOMEM); } /* compute the full Schur forms */ gsl_eigen_gen_params(1, 1, 1, w->gen_workspace_p); w->work1 = gsl_vector_alloc(n); w->work2 = gsl_vector_alloc(n); w->work3 = gsl_vector_alloc(n); w->work4 = gsl_vector_alloc(n); w->work5 = gsl_vector_alloc(n); w->work6 = gsl_vector_alloc(n); if (w->work1 == 0 || w->work2 == 0 || w->work3 == 0 || w->work4 == 0 || w->work5 == 0 || w->work6 == 0) { gsl_eigen_genv_free(w); GSL_ERROR_NULL ("failed to allocate space for additional workspace", GSL_ENOMEM); } return (w); } /* gsl_eigen_genv_alloc() */ /* gsl_eigen_genv_free() Free workspace w */ void gsl_eigen_genv_free(gsl_eigen_genv_workspace *w) { RETURN_IF_NULL (w); if (w->gen_workspace_p) gsl_eigen_gen_free(w->gen_workspace_p); if (w->work1) gsl_vector_free(w->work1); if (w->work2) gsl_vector_free(w->work2); if (w->work3) gsl_vector_free(w->work3); if (w->work4) gsl_vector_free(w->work4); if (w->work5) gsl_vector_free(w->work5); if (w->work6) gsl_vector_free(w->work6); free(w); } /* gsl_eigen_genv_free() */ /* gsl_eigen_genv() Solve the generalized eigenvalue problem A x = \lambda B x for the eigenvalues \lambda and right eigenvectors x. Inputs: A - general real matrix B - general real matrix alpha - (output) where to store eigenvalue numerators beta - (output) where to store eigenvalue denominators evec - (output) where to store eigenvectors w - workspace Return: success or error */ int gsl_eigen_genv (gsl_matrix * A, gsl_matrix * B, gsl_vector_complex * alpha, gsl_vector * beta, gsl_matrix_complex *evec, gsl_eigen_genv_workspace * w) { const size_t N = A->size1; /* check matrix and vector sizes */ if (N != A->size2) { GSL_ERROR ("matrix must be square to compute eigenvalues", GSL_ENOTSQR); } else if ((N != B->size1) || (N != B->size2)) { GSL_ERROR ("B matrix dimensions must match A", GSL_EBADLEN); } else if (alpha->size != N || beta->size != N) { GSL_ERROR ("eigenvalue vector must match matrix size", GSL_EBADLEN); } else if (w->size != N) { GSL_ERROR ("matrix size does not match workspace", GSL_EBADLEN); } else if (evec->size1 != N) { GSL_ERROR ("eigenvector matrix has wrong size", GSL_EBADLEN); } else { int s; gsl_matrix Z; /* * We need a place to store the right Schur vectors, so we will * treat evec as a real matrix and store them in the left * half - the factor of 2 in the tda corresponds to the * complex multiplicity */ Z.size1 = N; Z.size2 = N; Z.tda = 2 * N; Z.data = evec->data; Z.block = 0; Z.owner = 0; s = gsl_eigen_gen_QZ(A, B, alpha, beta, w->Q, &Z, w->gen_workspace_p); if (w->Z) { /* save right Schur vectors */ gsl_matrix_memcpy(w->Z, &Z); } /* only compute eigenvectors if we found all eigenvalues */ if (s == GSL_SUCCESS) { /* compute eigenvectors */ s = genv_get_right_eigenvectors(A, B, &Z, evec, w); if (s == GSL_SUCCESS) genv_normalize_eigenvectors(alpha, evec); } return s; } } /* gsl_eigen_genv() */ /* gsl_eigen_genv_QZ() Solve the generalized eigenvalue problem A x = \lambda B x for the eigenvalues \lambda and right eigenvectors x. Optionally compute left and/or right Schur vectors Q and Z which satisfy: A = Q S Z^t B = Q T Z^t where (S, T) is the generalized Schur form of (A, B) Inputs: A - general real matrix B - general real matrix alpha - (output) where to store eigenvalue numerators beta - (output) where to store eigenvalue denominators evec - (output) where to store eigenvectors Q - (output) if non-null, where to store left Schur vectors Z - (output) if non-null, where to store right Schur vectors w - workspace Return: success or error */ int gsl_eigen_genv_QZ (gsl_matrix * A, gsl_matrix * B, gsl_vector_complex * alpha, gsl_vector * beta, gsl_matrix_complex * evec, gsl_matrix * Q, gsl_matrix * Z, gsl_eigen_genv_workspace * w) { if (Q && (A->size1 != Q->size1 || A->size1 != Q->size2)) { GSL_ERROR("Q matrix has wrong dimensions", GSL_EBADLEN); } else if (Z && (A->size1 != Z->size1 || A->size1 != Z->size2)) { GSL_ERROR("Z matrix has wrong dimensions", GSL_EBADLEN); } else { int s; w->Q = Q; w->Z = Z; s = gsl_eigen_genv(A, B, alpha, beta, evec, w); w->Q = NULL; w->Z = NULL; return s; } } /* gsl_eigen_genv_QZ() */ /******************************************** * INTERNAL ROUTINES * ********************************************/ /* genv_get_right_eigenvectors() Compute right eigenvectors of the Schur form (S, T) and then backtransform them using the right Schur vectors to get right eigenvectors of the original system. Inputs: S - upper quasi-triangular Schur form of A T - upper triangular Schur form of B Z - right Schur vectors evec - (output) where to store eigenvectors w - workspace Return: success or error Notes: 1) based on LAPACK routine DTGEVC 2) eigenvectors are stored in the order that their eigenvalues appear in the Schur form */ static int genv_get_right_eigenvectors(const gsl_matrix *S, const gsl_matrix *T, gsl_matrix *Z, gsl_matrix_complex *evec, gsl_eigen_genv_workspace *w) { const size_t N = w->size; const double small = GSL_DBL_MIN * N / GSL_DBL_EPSILON; const double big = 1.0 / small; const double bignum = 1.0 / (GSL_DBL_MIN * N); size_t i, j, k, end; int is; double anorm, bnorm; double temp, temp2, temp2r, temp2i; double ascale, bscale; double salfar, sbeta; double acoef, bcoefr, bcoefi, acoefa, bcoefa; double creala, cimaga, crealb, cimagb, cre2a, cim2a, cre2b, cim2b; double dmin, xmax; double scale; size_t nw, na; int lsa, lsb; int complex_pair; gsl_complex z_zero, z_one; double bdiag[2] = { 0.0, 0.0 }; double sum[4]; int il2by2; size_t jr, jc, ja; double xscale; gsl_vector_complex_view ecol; gsl_vector_view re, im, re2, im2; GSL_SET_COMPLEX(&z_zero, 0.0, 0.0); GSL_SET_COMPLEX(&z_one, 1.0, 0.0); /* * Compute the 1-norm of each column of (S, T) excluding elements * belonging to the diagonal blocks to check for possible overflow * in the triangular solver */ anorm = fabs(gsl_matrix_get(S, 0, 0)); if (N > 1) anorm += fabs(gsl_matrix_get(S, 1, 0)); bnorm = fabs(gsl_matrix_get(T, 0, 0)); gsl_vector_set(w->work1, 0, 0.0); gsl_vector_set(w->work2, 0, 0.0); for (j = 1; j < N; ++j) { temp = temp2 = 0.0; if (gsl_matrix_get(S, j, j - 1) == 0.0) end = j; else end = j - 1; for (i = 0; i < end; ++i) { temp += fabs(gsl_matrix_get(S, i, j)); temp2 += fabs(gsl_matrix_get(T, i, j)); } gsl_vector_set(w->work1, j, temp); gsl_vector_set(w->work2, j, temp2); for (i = end; i < GSL_MIN(j + 2, N); ++i) { temp += fabs(gsl_matrix_get(S, i, j)); temp2 += fabs(gsl_matrix_get(T, i, j)); } anorm = GSL_MAX(anorm, temp); bnorm = GSL_MAX(bnorm, temp2); } ascale = 1.0 / GSL_MAX(anorm, GSL_DBL_MIN); bscale = 1.0 / GSL_MAX(bnorm, GSL_DBL_MIN); complex_pair = 0; for (k = 0; k < N; ++k) { size_t je = N - 1 - k; if (complex_pair) { complex_pair = 0; continue; } nw = 1; if (je > 0) { if (gsl_matrix_get(S, je, je - 1) != 0.0) { complex_pair = 1; nw = 2; } } if (!complex_pair) { if (fabs(gsl_matrix_get(S, je, je)) <= GSL_DBL_MIN && fabs(gsl_matrix_get(T, je, je)) <= GSL_DBL_MIN) { /* singular matrix pencil - unit eigenvector */ for (i = 0; i < N; ++i) gsl_matrix_complex_set(evec, i, je, z_zero); gsl_matrix_complex_set(evec, je, je, z_one); continue; } /* clear vector */ for (i = 0; i < N; ++i) gsl_vector_set(w->work3, i, 0.0); } else { /* clear vectors */ for (i = 0; i < N; ++i) { gsl_vector_set(w->work3, i, 0.0); gsl_vector_set(w->work4, i, 0.0); } } if (!complex_pair) { /* real eigenvalue */ temp = 1.0 / GSL_MAX(GSL_DBL_MIN, GSL_MAX(fabs(gsl_matrix_get(S, je, je)) * ascale, fabs(gsl_matrix_get(T, je, je)) * bscale)); salfar = (temp * gsl_matrix_get(S, je, je)) * ascale; sbeta = (temp * gsl_matrix_get(T, je, je)) * bscale; acoef = sbeta * ascale; bcoefr = salfar * bscale; bcoefi = 0.0; /* scale to avoid underflow */ scale = 1.0; lsa = fabs(sbeta) >= GSL_DBL_MIN && fabs(acoef) < small; lsb = fabs(salfar) >= GSL_DBL_MIN && fabs(bcoefr) < small; if (lsa) scale = (small / fabs(sbeta)) * GSL_MIN(anorm, big); if (lsb) scale = GSL_MAX(scale, (small / fabs(salfar)) * GSL_MIN(bnorm, big)); if (lsa || lsb) { scale = GSL_MIN(scale, 1.0 / (GSL_DBL_MIN * GSL_MAX(1.0, GSL_MAX(fabs(acoef), fabs(bcoefr))))); if (lsa) acoef = ascale * (scale * sbeta); else acoef *= scale; if (lsb) bcoefr = bscale * (scale * salfar); else bcoefr *= scale; } acoefa = fabs(acoef); bcoefa = fabs(bcoefr); /* first component is 1 */ gsl_vector_set(w->work3, je, 1.0); xmax = 1.0; /* compute contribution from column je of A and B to sum */ for (i = 0; i < je; ++i) { gsl_vector_set(w->work3, i, bcoefr*gsl_matrix_get(T, i, je) - acoef * gsl_matrix_get(S, i, je)); } } else { gsl_matrix_const_view vs = gsl_matrix_const_submatrix(S, je - 1, je - 1, 2, 2); gsl_matrix_const_view vt = gsl_matrix_const_submatrix(T, je - 1, je - 1, 2, 2); /* complex eigenvalue */ gsl_schur_gen_eigvals(&vs.matrix, &vt.matrix, &bcoefr, &temp2, &bcoefi, &acoef, &temp); if (bcoefi == 0.0) { GSL_ERROR("gsl_schur_gen_eigvals failed on complex block", GSL_FAILURE); } /* scale to avoid over/underflow */ acoefa = fabs(acoef); bcoefa = fabs(bcoefr) + fabs(bcoefi); scale = 1.0; if (acoefa*GSL_DBL_EPSILON < GSL_DBL_MIN && acoefa >= GSL_DBL_MIN) scale = (GSL_DBL_MIN / GSL_DBL_EPSILON) / acoefa; if (bcoefa*GSL_DBL_EPSILON < GSL_DBL_MIN && bcoefa >= GSL_DBL_MIN) scale = GSL_MAX(scale, (GSL_DBL_MIN/GSL_DBL_EPSILON) / bcoefa); if (GSL_DBL_MIN*acoefa > ascale) scale = ascale / (GSL_DBL_MIN * acoefa); if (GSL_DBL_MIN*bcoefa > bscale) scale = GSL_MIN(scale, bscale / (GSL_DBL_MIN*bcoefa)); if (scale != 1.0) { acoef *= scale; acoefa = fabs(acoef); bcoefr *= scale; bcoefi *= scale; bcoefa = fabs(bcoefr) + fabs(bcoefi); } /* compute first two components of eigenvector */ temp = acoef * gsl_matrix_get(S, je, je - 1); temp2r = acoef * gsl_matrix_get(S, je, je) - bcoefr * gsl_matrix_get(T, je, je); temp2i = -bcoefi * gsl_matrix_get(T, je, je); if (fabs(temp) >= fabs(temp2r) + fabs(temp2i)) { gsl_vector_set(w->work3, je, 1.0); gsl_vector_set(w->work4, je, 0.0); gsl_vector_set(w->work3, je - 1, -temp2r / temp); gsl_vector_set(w->work4, je - 1, -temp2i / temp); } else { gsl_vector_set(w->work3, je - 1, 1.0); gsl_vector_set(w->work4, je - 1, 0.0); temp = acoef * gsl_matrix_get(S, je - 1, je); gsl_vector_set(w->work3, je, (bcoefr*gsl_matrix_get(T, je - 1, je - 1) - acoef*gsl_matrix_get(S, je - 1, je - 1)) / temp); gsl_vector_set(w->work4, je, bcoefi*gsl_matrix_get(T, je - 1, je - 1) / temp); } xmax = GSL_MAX(fabs(gsl_vector_get(w->work3, je)) + fabs(gsl_vector_get(w->work4, je)), fabs(gsl_vector_get(w->work3, je - 1)) + fabs(gsl_vector_get(w->work4, je - 1))); /* compute contribution from column je and je - 1 */ creala = acoef * gsl_vector_get(w->work3, je - 1); cimaga = acoef * gsl_vector_get(w->work4, je - 1); crealb = bcoefr * gsl_vector_get(w->work3, je - 1) - bcoefi * gsl_vector_get(w->work4, je - 1); cimagb = bcoefi * gsl_vector_get(w->work3, je - 1) + bcoefr * gsl_vector_get(w->work4, je - 1); cre2a = acoef * gsl_vector_get(w->work3, je); cim2a = acoef * gsl_vector_get(w->work4, je); cre2b = bcoefr * gsl_vector_get(w->work3, je) - bcoefi * gsl_vector_get(w->work4, je); cim2b = bcoefi * gsl_vector_get(w->work3, je) + bcoefr * gsl_vector_get(w->work4, je); for (i = 0; i < je - 1; ++i) { gsl_vector_set(w->work3, i, -creala * gsl_matrix_get(S, i, je - 1) + crealb * gsl_matrix_get(T, i, je - 1) - cre2a * gsl_matrix_get(S, i, je) + cre2b * gsl_matrix_get(T, i, je)); gsl_vector_set(w->work4, i, -cimaga * gsl_matrix_get(S, i, je - 1) + cimagb * gsl_matrix_get(T, i, je - 1) - cim2a * gsl_matrix_get(S, i, je) + cim2b * gsl_matrix_get(T, i, je)); } } dmin = GSL_MAX(GSL_DBL_MIN, GSL_MAX(GSL_DBL_EPSILON*acoefa*anorm, GSL_DBL_EPSILON*bcoefa*bnorm)); /* triangular solve of (a A - b B) x = 0 */ il2by2 = 0; for (is = (int) je - (int) nw; is >= 0; --is) { j = (size_t) is; if (!il2by2 && j > 0) { if (gsl_matrix_get(S, j, j - 1) != 0.0) { il2by2 = 1; continue; } } bdiag[0] = gsl_matrix_get(T, j, j); if (il2by2) { na = 2; bdiag[1] = gsl_matrix_get(T, j + 1, j + 1); } else na = 1; if (nw == 1) { gsl_matrix_const_view sv = gsl_matrix_const_submatrix(S, j, j, na, na); gsl_vector_view xv, bv; bv = gsl_vector_subvector(w->work3, j, na); /* * the loop below expects the solution in the first column * of sum, so set stride to 2 */ xv = gsl_vector_view_array_with_stride(sum, 2, na); gsl_schur_solve_equation(acoef, &sv.matrix, bcoefr, bdiag[0], bdiag[1], &bv.vector, &xv.vector, &scale, &temp, dmin); } else { double bdat[4]; gsl_matrix_const_view sv = gsl_matrix_const_submatrix(S, j, j, na, na); gsl_vector_complex_view xv = gsl_vector_complex_view_array(sum, na); gsl_vector_complex_view bv = gsl_vector_complex_view_array(bdat, na); gsl_complex z; bdat[0] = gsl_vector_get(w->work3, j); bdat[1] = gsl_vector_get(w->work4, j); if (na == 2) { bdat[2] = gsl_vector_get(w->work3, j + 1); bdat[3] = gsl_vector_get(w->work4, j + 1); } GSL_SET_COMPLEX(&z, bcoefr, bcoefi); gsl_schur_solve_equation_z(acoef, &sv.matrix, &z, bdiag[0], bdiag[1], &bv.vector, &xv.vector, &scale, &temp, dmin); } if (scale < 1.0) { for (jr = 0; jr <= je; ++jr) { gsl_vector_set(w->work3, jr, scale * gsl_vector_get(w->work3, jr)); if (nw == 2) { gsl_vector_set(w->work4, jr, scale * gsl_vector_get(w->work4, jr)); } } } xmax = GSL_MAX(scale * xmax, temp); for (jr = 0; jr < na; ++jr) { gsl_vector_set(w->work3, j + jr, sum[jr*na]); if (nw == 2) gsl_vector_set(w->work4, j + jr, sum[jr*na + 1]); } if (j > 0) { xscale = 1.0 / GSL_MAX(1.0, xmax); temp = acoefa * gsl_vector_get(w->work1, j) + bcoefa * gsl_vector_get(w->work2, j); if (il2by2) { temp = GSL_MAX(temp, acoefa * gsl_vector_get(w->work1, j + 1) + bcoefa * gsl_vector_get(w->work2, j + 1)); } temp = GSL_MAX(temp, GSL_MAX(acoefa, bcoefa)); if (temp > bignum * xscale) { for (jr = 0; jr <= je; ++jr) { gsl_vector_set(w->work3, jr, xscale * gsl_vector_get(w->work3, jr)); if (nw == 2) { gsl_vector_set(w->work4, jr, xscale * gsl_vector_get(w->work4, jr)); } } xmax *= xscale; } for (ja = 0; ja < na; ++ja) { if (complex_pair) { creala = acoef * gsl_vector_get(w->work3, j + ja); cimaga = acoef * gsl_vector_get(w->work4, j + ja); crealb = bcoefr * gsl_vector_get(w->work3, j + ja) - bcoefi * gsl_vector_get(w->work4, j + ja); cimagb = bcoefi * gsl_vector_get(w->work3, j + ja) + bcoefr * gsl_vector_get(w->work4, j + ja); for (jr = 0; jr <= j - 1; ++jr) { gsl_vector_set(w->work3, jr, gsl_vector_get(w->work3, jr) - creala * gsl_matrix_get(S, jr, j + ja) + crealb * gsl_matrix_get(T, jr, j + ja)); gsl_vector_set(w->work4, jr, gsl_vector_get(w->work4, jr) - cimaga * gsl_matrix_get(S, jr, j + ja) + cimagb * gsl_matrix_get(T, jr, j + ja)); } } else { creala = acoef * gsl_vector_get(w->work3, j + ja); crealb = bcoefr * gsl_vector_get(w->work3, j + ja); for (jr = 0; jr <= j - 1; ++jr) { gsl_vector_set(w->work3, jr, gsl_vector_get(w->work3, jr) - creala * gsl_matrix_get(S, jr, j + ja) + crealb * gsl_matrix_get(T, jr, j + ja)); } } /* if (!complex_pair) */ } /* for (ja = 0; ja < na; ++ja) */ } /* if (j > 0) */ il2by2 = 0; } /* for (i = 0; i < je - nw; ++i) */ for (jr = 0; jr < N; ++jr) { gsl_vector_set(w->work5, jr, gsl_vector_get(w->work3, 0) * gsl_matrix_get(Z, jr, 0)); if (nw == 2) { gsl_vector_set(w->work6, jr, gsl_vector_get(w->work4, 0) * gsl_matrix_get(Z, jr, 0)); } } for (jc = 1; jc <= je; ++jc) { for (jr = 0; jr < N; ++jr) { gsl_vector_set(w->work5, jr, gsl_vector_get(w->work5, jr) + gsl_vector_get(w->work3, jc) * gsl_matrix_get(Z, jr, jc)); if (nw == 2) { gsl_vector_set(w->work6, jr, gsl_vector_get(w->work6, jr) + gsl_vector_get(w->work4, jc) * gsl_matrix_get(Z, jr, jc)); } } } /* store the eigenvector */ if (complex_pair) { ecol = gsl_matrix_complex_column(evec, je - 1); re = gsl_vector_complex_real(&ecol.vector); im = gsl_vector_complex_imag(&ecol.vector); ecol = gsl_matrix_complex_column(evec, je); re2 = gsl_vector_complex_real(&ecol.vector); im2 = gsl_vector_complex_imag(&ecol.vector); } else { ecol = gsl_matrix_complex_column(evec, je); re = gsl_vector_complex_real(&ecol.vector); im = gsl_vector_complex_imag(&ecol.vector); } for (jr = 0; jr < N; ++jr) { gsl_vector_set(&re.vector, jr, gsl_vector_get(w->work5, jr)); if (complex_pair) { gsl_vector_set(&im.vector, jr, gsl_vector_get(w->work6, jr)); gsl_vector_set(&re2.vector, jr, gsl_vector_get(w->work5, jr)); gsl_vector_set(&im2.vector, jr, -gsl_vector_get(w->work6, jr)); } else { gsl_vector_set(&im.vector, jr, 0.0); } } /* scale eigenvector */ xmax = 0.0; if (complex_pair) { for (j = 0; j < N; ++j) { xmax = GSL_MAX(xmax, fabs(gsl_vector_get(&re.vector, j)) + fabs(gsl_vector_get(&im.vector, j))); } } else { for (j = 0; j < N; ++j) { xmax = GSL_MAX(xmax, fabs(gsl_vector_get(&re.vector, j))); } } if (xmax > GSL_DBL_MIN) { xscale = 1.0 / xmax; for (j = 0; j < N; ++j) { gsl_vector_set(&re.vector, j, gsl_vector_get(&re.vector, j) * xscale); if (complex_pair) { gsl_vector_set(&im.vector, j, gsl_vector_get(&im.vector, j) * xscale); gsl_vector_set(&re2.vector, j, gsl_vector_get(&re2.vector, j) * xscale); gsl_vector_set(&im2.vector, j, gsl_vector_get(&im2.vector, j) * xscale); } } } } /* for (k = 0; k < N; ++k) */ return GSL_SUCCESS; } /* genv_get_right_eigenvectors() */ /* genv_normalize_eigenvectors() Normalize eigenvectors so that their Euclidean norm is 1 Inputs: alpha - eigenvalue numerators evec - eigenvectors */ static void genv_normalize_eigenvectors(gsl_vector_complex *alpha, gsl_matrix_complex *evec) { const size_t N = evec->size1; size_t i; /* looping */ gsl_complex ai; gsl_vector_complex_view vi; gsl_vector_view re, im; double scale; /* scaling factor */ for (i = 0; i < N; ++i) { ai = gsl_vector_complex_get(alpha, i); vi = gsl_matrix_complex_column(evec, i); re = gsl_vector_complex_real(&vi.vector); if (GSL_IMAG(ai) == 0.0) { scale = 1.0 / gsl_blas_dnrm2(&re.vector); gsl_blas_dscal(scale, &re.vector); } else if (GSL_IMAG(ai) > 0.0) { im = gsl_vector_complex_imag(&vi.vector); scale = 1.0 / gsl_hypot(gsl_blas_dnrm2(&re.vector), gsl_blas_dnrm2(&im.vector)); gsl_blas_zdscal(scale, &vi.vector); vi = gsl_matrix_complex_column(evec, i + 1); gsl_blas_zdscal(scale, &vi.vector); } } } /* genv_normalize_eigenvectors() */
{ "alphanum_fraction": 0.4838877881, "avg_line_length": 31.06587473, "ext": "c", "hexsha": "a309e41e531ffed361c60d19d13ca9dfda40ee42", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/eigen/genv.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/eigen/genv.c", "max_line_length": 87, "max_stars_count": 14, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/eigen/genv.c", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "num_tokens": 7714, "size": 28767 }
#include <cblas.h> #include <stdio.h> /* compilar: gcc fonte.c -o exec -lblas */ int main( void ) { int lda = 3; float A[] = { 1, 0, -1, 2, 3, 1 }; int ldb = 2; float B[] = { 5, 1, 6, -1, 7, 2 }; int ldc = 2; float C[] = { 0.00, 0.00, 0.00, 0.00 }; /* Compute C = A B */ cblas_sgemm( CblasRowMajor, CblasNoTrans, CblasNoTrans, 2, 2, 3, 1.0, A, lda, B, ldb, 0.0, C, ldc ); printf( "[ %g, %g\n", C[ 0 ], C[ 1 ] ); printf( " %g, %g ]\n", C[ 2 ], C[ 3 ] ); return( 0 ); }
{ "alphanum_fraction": 0.420212766, "avg_line_length": 18.8, "ext": "c", "hexsha": "aca2bdb28bace7bca6bab91ab1a26b603e63bab5", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "eb4fcb9c19ca4fc2cba2a392928957efe4bd5198", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "lellisls/PAD", "max_forks_repo_path": "at02-cache/exemplos/sgemm.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "eb4fcb9c19ca4fc2cba2a392928957efe4bd5198", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "lellisls/PAD", "max_issues_repo_path": "at02-cache/exemplos/sgemm.c", "max_line_length": 102, "max_stars_count": null, "max_stars_repo_head_hexsha": "eb4fcb9c19ca4fc2cba2a392928957efe4bd5198", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "lellisls/PAD", "max_stars_repo_path": "at02-cache/exemplos/sgemm.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 246, "size": 564 }
#include<stdio.h> #include<math.h> #include"recur.c" #include <gsl/gsl_integration.h> #include"gsl_integration.c" #define NMAX 100 #include"timer.h" #include"timer.c" #include"adjust.c" /* The integral is evaluated for n=0 to n=100 using both a derived recursion formula * and the GSL general integrator. The values of both are stored in their own * respective arrays. The values and their absolute error are printed in order to * compare the accuracy of the two methods. Then, both functions are timed to * determine which one is faster at generating the results. Finally, the timings of * the two functions are divided to provide a ratio describing the difference in * efficiency of the two methods. */ int main (void) { double vals1[NMAX + 1], vals2[NMAX + 1], time1a, time1b, time2a, time2b, tmin = 1., tmax = 2.; // Initializing all the "double" variables for use in the program// int nmin = 0, nmax = NMAX, count1 = 1000, count2 = 800; integral_recur (nmin, nmax, vals1); // Recursion formula stores I(0) to I(100) in the array vals1// integral_gen (nmin, nmax, vals2); // GSL integration algorithm stores I(0) to I(100) in the array vals2// printf (" --n-- --Recur-- --GSL Integrator-- --Absolute Error*10^9--\n"); int k; for (k = 0; k < 101; k++) { printf (" %6d %15.15f %15.15f %15.15f \n", k, vals1[k], vals2[k], fabs (1.e9 * (vals1[k] - vals2[k]))); } // Prints the values for each term in the sequence as generated by both of the algorithms // int p; printf ("\n--Timing for recurrence function--\nTime per call (usec) Total Time (sec) Count\n"); do { timer_start (); // The timer is started. for (p = 0; p < count1; p++) // The function is called "count1" times. { integral_recur (nmin, nmax, vals1); // The recursion formula stores each of the sequence values in the array vals1// } time1a = timer_stop (); // The timer is stopped. time1b = time1a / count1; // The time per function call is calculated as the total time divided by the number of function calls. printf (" %10.2f usec %10.6f sec %10d\n", time1b * 1.e6, time1a, count1); count1 = adjust_rep_count (count1, time1a, tmin, tmax); // The number of function calls "count1" is adjusted. } while ((time1a > tmax) || (time1a < tmin)); // This is repeated until the total time is within the desired range. printf ("Time per recur function call = %f usec \n", time1b * 1.e6); printf ("\n--Timing for GSL integration function--\nTime per call (usec) Total Time (sec) Count\n"); do { timer_start (); // The timer is started. for (p = 0; p < count2; p++) // The function is called "count2" times. { integral_gen (nmin, nmax, vals2); // The GSL integration formula stores each of the sequence values in the array vals1// } time2a = timer_stop (); // The timer is stopped. time2b = time2a / count2; // The time per function call is calculated as the total time divided by the number of function calls. printf (" %10.2f usec %10.6f sec %10d\n", time2b * 1.e6, time2a, count2); count2 = adjust_rep_count (count2, time2a, tmin, tmax); // The number of function calls "count2" is adjusted. } while ((time2a > tmax) || (time2a < tmin)); // This is repeated until the total time is within the desired range. printf ("Time per GSL function call = %f usec \n", time2b * 1.e6); printf ("Ratio of times Tgsl / Trecur = %f\n", time2b / time1b); // The ratio of times per function call of each function is printed// return 0; }
{ "alphanum_fraction": 0.6185271923, "avg_line_length": 50.5657894737, "ext": "c", "hexsha": "39d021332daed9bc2a06702998b9d541748d2435", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "00507c760b4820c73736a7987beb6ba21fb892d1", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "fbergabo/hw07", "max_forks_repo_path": "main.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "00507c760b4820c73736a7987beb6ba21fb892d1", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "fbergabo/hw07", "max_issues_repo_path": "main.c", "max_line_length": 171, "max_stars_count": null, "max_stars_repo_head_hexsha": "00507c760b4820c73736a7987beb6ba21fb892d1", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "fbergabo/hw07", "max_stars_repo_path": "main.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1083, "size": 3843 }
/** * * @generated d Tue Jan 7 11:45:26 2014 * **/ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <cblas.h> #include <lapacke.h> #include <plasma.h> #include <core_blas.h> #include "auxiliary.h" /*------------------------------------------------------------------- * Check the orthogonality of Q */ int d_check_orthogonality(int M, int N, int LDQ, double *Q) { double alpha, beta; double normQ; int info_ortho; int i; int minMN = min(M, N); double eps; double *work = (double *)malloc(minMN*sizeof(double)); eps = LAPACKE_dlamch_work('e'); alpha = 1.0; beta = -1.0; /* Build the idendity matrix USE DLASET?*/ double *Id = (double *) malloc(minMN*minMN*sizeof(double)); memset((void*)Id, 0, minMN*minMN*sizeof(double)); for (i = 0; i < minMN; i++) Id[i*minMN+i] = (double)1.0; /* Perform Id - Q'Q */ if (M >= N) cblas_dsyrk(CblasColMajor, CblasUpper, CblasTrans, N, M, alpha, Q, LDQ, beta, Id, N); else cblas_dsyrk(CblasColMajor, CblasUpper, CblasNoTrans, M, N, alpha, Q, LDQ, beta, Id, M); normQ = LAPACKE_dlansy_work(LAPACK_COL_MAJOR, 'i', 'u', minMN, Id, minMN, work); printf("============\n"); printf("Checking the orthogonality of Q \n"); printf("||Id-Q'*Q||_oo / (N*eps) = %e \n",normQ/(minMN*eps)); if ( isnan(normQ / (minMN * eps)) || (normQ / (minMN * eps) > 10.0) ) { printf("-- Orthogonality is suspicious ! \n"); info_ortho=1; } else { printf("-- Orthogonality is CORRECT ! \n"); info_ortho=0; } free(work); free(Id); return info_ortho; } /*------------------------------------------------------------ * Check the factorization QR */ int d_check_QRfactorization(int M, int N, double *A1, double *A2, int LDA, double *Q) { double Anorm, Rnorm; double alpha, beta; int info_factorization; int i,j; double eps; eps = LAPACKE_dlamch_work('e'); double *Ql = (double *)malloc(M*N*sizeof(double)); double *Residual = (double *)malloc(M*N*sizeof(double)); double *work = (double *)malloc(max(M,N)*sizeof(double)); alpha=1.0; beta=0.0; if (M >= N) { /* Extract the R */ double *R = (double *)malloc(N*N*sizeof(double)); memset((void*)R, 0, N*N*sizeof(double)); LAPACKE_dlacpy_work(LAPACK_COL_MAJOR,'u', M, N, A2, LDA, R, N); /* Perform Ql=Q*R */ memset((void*)Ql, 0, M*N*sizeof(double)); cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, M, N, N, (alpha), Q, LDA, R, N, (beta), Ql, M); free(R); } else { /* Extract the L */ double *L = (double *)malloc(M*M*sizeof(double)); memset((void*)L, 0, M*M*sizeof(double)); LAPACKE_dlacpy_work(LAPACK_COL_MAJOR,'l', M, N, A2, LDA, L, M); /* Perform Ql=LQ */ memset((void*)Ql, 0, M*N*sizeof(double)); cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, M, N, M, (alpha), L, M, Q, LDA, (beta), Ql, M); free(L); } /* Compute the Residual */ for (i = 0; i < M; i++) for (j = 0 ; j < N; j++) Residual[j*M+i] = A1[j*LDA+i]-Ql[j*M+i]; Rnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'i', M, N, Residual, M, work); Anorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'i', M, N, A2, LDA, work); if (M >= N) { printf("============\n"); printf("Checking the QR Factorization \n"); printf("-- ||A-QR||_oo/(||A||_oo.N.eps) = %e \n",Rnorm/(Anorm*N*eps)); } else { printf("============\n"); printf("Checking the LQ Factorization \n"); printf("-- ||A-LQ||_oo/(||A||_oo.N.eps) = %e \n",Rnorm/(Anorm*N*eps)); } if (isnan(Rnorm / (Anorm * N *eps)) || (Rnorm / (Anorm * N * eps) > 10.0) ) { printf("-- Factorization is suspicious ! \n"); info_factorization = 1; } else { printf("-- Factorization is CORRECT ! \n"); info_factorization = 0; } free(work); free(Ql); free(Residual); return info_factorization; } /*------------------------------------------------------------------------ * Check the factorization of the matrix A2 */ int d_check_LLTfactorization(int N, double *A1, double *A2, int LDA, int uplo) { double Anorm, Rnorm; double alpha; int info_factorization; int i,j; double eps; eps = LAPACKE_dlamch_work('e'); double *Residual = (double *)malloc(N*N*sizeof(double)); double *L1 = (double *)malloc(N*N*sizeof(double)); double *L2 = (double *)malloc(N*N*sizeof(double)); double *work = (double *)malloc(N*sizeof(double)); memset((void*)L1, 0, N*N*sizeof(double)); memset((void*)L2, 0, N*N*sizeof(double)); alpha= 1.0; LAPACKE_dlacpy_work(LAPACK_COL_MAJOR,' ', N, N, A1, LDA, Residual, N); /* Dealing with L'L or U'U */ if (uplo == PlasmaUpper){ LAPACKE_dlacpy_work(LAPACK_COL_MAJOR,'u', N, N, A2, LDA, L1, N); LAPACKE_dlacpy_work(LAPACK_COL_MAJOR,'u', N, N, A2, LDA, L2, N); cblas_dtrmm(CblasColMajor, CblasLeft, CblasUpper, CblasTrans, CblasNonUnit, N, N, (alpha), L1, N, L2, N); } else{ LAPACKE_dlacpy_work(LAPACK_COL_MAJOR,'l', N, N, A2, LDA, L1, N); LAPACKE_dlacpy_work(LAPACK_COL_MAJOR,'l', N, N, A2, LDA, L2, N); cblas_dtrmm(CblasColMajor, CblasRight, CblasLower, CblasTrans, CblasNonUnit, N, N, (alpha), L1, N, L2, N); } /* Compute the Residual || A -L'L|| */ for (i = 0; i < N; i++) for (j = 0; j < N; j++) Residual[j*N+i] = L2[j*N+i] - Residual[j*N+i]; Rnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'i', N, N, Residual, N, work); Anorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'i', N, N, A1, LDA, work); printf("============\n"); printf("Checking the Cholesky Factorization \n"); printf("-- ||L'L-A||_oo/(||A||_oo.N.eps) = %e \n",Rnorm/(Anorm*N*eps)); if ( isnan(Rnorm/(Anorm*N*eps)) || (Rnorm/(Anorm*N*eps) > 10.0) ){ printf("-- Factorization is suspicious ! \n"); info_factorization = 1; } else{ printf("-- Factorization is CORRECT ! \n"); info_factorization = 0; } free(Residual); free(L1); free(L2); free(work); return info_factorization; } /*-------------------------------------------------------------- * Check the gemm */ double d_check_gemm(PLASMA_enum transA, PLASMA_enum transB, int M, int N, int K, double alpha, double *A, int LDA, double *B, int LDB, double beta, double *Cplasma, double *Cref, int LDC, double *Cinitnorm, double *Cplasmanorm, double *Clapacknorm ) { double beta_const = -1.0; double Rnorm; double *work = (double *)malloc(max(K,max(M, N))* sizeof(double)); *Cinitnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'i', M, N, Cref, LDC, work); *Cplasmanorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'i', M, N, Cplasma, LDC, work); cblas_dgemm(CblasColMajor, (CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB, M, N, K, (alpha), A, LDA, B, LDB, (beta), Cref, LDC); *Clapacknorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'i', M, N, Cref, LDC, work); cblas_daxpy(LDC * N, (beta_const), Cplasma, 1, Cref, 1); Rnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'i', M, N, Cref, LDC, work); free(work); return Rnorm; } /*-------------------------------------------------------------- * Check the trsm */ double d_check_trsm(PLASMA_enum side, PLASMA_enum uplo, PLASMA_enum trans, PLASMA_enum diag, int M, int NRHS, double alpha, double *A, int LDA, double *Bplasma, double *Bref, int LDB, double *Binitnorm, double *Bplasmanorm, double *Blapacknorm ) { double beta_const = -1.0; double Rnorm; double *work = (double *)malloc(max(M, NRHS)* sizeof(double)); /*double eps = LAPACKE_dlamch_work('e');*/ *Binitnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'i', M, NRHS, Bref, LDB, work); *Bplasmanorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'm', M, NRHS, Bplasma, LDB, work); cblas_dtrsm(CblasColMajor, (CBLAS_SIDE)side, (CBLAS_UPLO)uplo, (CBLAS_TRANSPOSE)trans, (CBLAS_DIAG)diag, M, NRHS, (alpha), A, LDA, Bref, LDB); *Blapacknorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'm', M, NRHS, Bref, LDB, work); cblas_daxpy(LDB * NRHS, (beta_const), Bplasma, 1, Bref, 1); Rnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'm', M, NRHS, Bref, LDB, work); Rnorm = Rnorm / *Blapacknorm; /* max(M,NRHS) * eps);*/ free(work); return Rnorm; } /*-------------------------------------------------------------- * Check the solution */ double d_check_solution(int M, int N, int NRHS, double *A, int LDA, double *B, double *X, int LDB, double *anorm, double *bnorm, double *xnorm ) { /* int info_solution; */ double Rnorm = -1.00; double zone = 1.0; double mzone = -1.0; double *work = (double *)malloc(max(M, N)* sizeof(double)); *anorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'i', M, N, A, LDA, work); *xnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'i', M, NRHS, X, LDB, work); *bnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'i', N, NRHS, B, LDB, work); cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, M, NRHS, N, (zone), A, LDA, X, LDB, (mzone), B, LDB); Rnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'i', N, NRHS, B, LDB, work); free(work); return Rnorm; }
{ "alphanum_fraction": 0.5562763876, "avg_line_length": 32.5872483221, "ext": "c", "hexsha": "d876b72ad494500510399d6ecf8357313efe0f91", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_path": "timing/dauxiliary.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_path": "timing/dauxiliary.c", "max_line_length": 114, "max_stars_count": null, "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_path": "timing/dauxiliary.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3153, "size": 9711 }
/* fft/benchmark.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stddef.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #include <float.h> #include <time.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_fft_complex.h> #include <gsl/gsl_errno.h> #include "complex_internal.h" #include "bitreverse.h" #include "urand.c" void my_error_handler (const char *reason, const char *file, int line, int err); int main (int argc, char *argv[]) { double *data, *fft_data; gsl_fft_complex_wavetable * cw; unsigned int i, logn; int result; int status; clock_t start, end; int resolution = CLOCKS_PER_SEC; unsigned int n = 1; gsl_set_error_handler (&my_error_handler); if (argc == 2) { n = strtol (argv[1], NULL, 0); } else { printf ("test n\n"); exit (EXIT_FAILURE); } cw = gsl_fft_complex_wavetable_alloc (n); cwork = gsl_fft_complex_wavetable_workspace_alloc (n); status = gsl_fft_complex_init (n, cw, cwork); status = gsl_fft_complex_generate (n, cw, cwork); data = (double *) malloc (n * 2 * sizeof (double)); fft_data = (double *) malloc (n * 2 * sizeof (double)); for (i = 0; i < n; i++) { REAL(data,1,i) = urand (); IMAG(data,1,i) = urand (); } /* compute the fft */ memcpy (fft_data, data, n * 2 * sizeof (double)); start = clock (); i = 0; do { status = gsl_fft_complex_forward (fft_data, 1, n, cw, cwork); i++; end = clock (); } while (end < start + resolution && status == 0); if (status == 0) { printf ("n = %d gsl_fft_complex_forward %f seconds\n", n, (end - start) / ((double) i) / ((double) CLOCKS_PER_SEC)); } else { printf ("MR fft failed\n"); } /* compute the fft with radix2 */ memcpy (fft_data, data, n * 2 * sizeof (double)); result = fft_binary_logn(n) ; if (result == -1) { exit(EXIT_SUCCESS) ; } else { logn = result ; } start = clock (); i = 0; do { status = gsl_fft_complex_radix2_forward (fft_data, 1, n); i++; end = clock (); } while (end < start + resolution && status == 0); if (status == 0) { printf ("n = %d gsl_fft_complex_radix2_forward %f seconds\n", n, (end - start) / ((double) i) / ((double) CLOCKS_PER_SEC)); } else { printf ("fft_radix2: not a power of 2\n"); } start = clock (); i = 0; do { status = fft_complex_bitreverse_order (fft_data, 1, n, logn); i++; end = clock (); } while (end < start + resolution && status == 0); printf ("n = %d gsl_fft_complex_bitreverse_order %f seconds\n", n, (end - start) / ((double) i) / ((double) CLOCKS_PER_SEC)); return 0; } void my_error_handler (const char *reason, const char *file, int line, int err) { printf ("error: %s in %s at %d (gsl_errno=%d)\n", reason, file, line, err); }
{ "alphanum_fraction": 0.6169519152, "avg_line_length": 23.5961538462, "ext": "c", "hexsha": "54379b38c6a27d2a769437d13158d1130036ca79", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/fft/benchmark.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/fft/benchmark.c", "max_line_length": 129, "max_stars_count": 1, "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/fft/benchmark.c", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "num_tokens": 1078, "size": 3681 }
#ifndef _INC_REGRESSION_ #define _INC_REGRESSION_ /** * contains the functions needed to handle the linear regression * this entails, creating hvectors (for given x vectors in the parameter space) * estimatingBeta, this needs the inverse covariance matrix and the training data * creating hmatrix, a done once kind of job, slap together hvectors for each of the design points */ #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_sf.h> /** * \brief creates a vector of regression coefficients at x_location * * create a h_vector evaluated at given x_location., * this currently only creates a set of linear basis fns, you could add another loop which * would add squares etc * * on calling h_vector should be initliased to a vector of length nregression_fns which * in the default case nregression_fns = nparams + 1 * * the value of options->nregression_fns is going to be very important for this * * this pointer is set to one of the fns in this file by optstruct.c:setup_regression */ void (*makeHVector)(gsl_vector *h_vector, gsl_vector *x_location, int nparams); //void makeHVector(gsl_vector *h_vector, gsl_vector *x_location, int nparams); void makeHMatrix(gsl_matrix *h_matrix, gsl_matrix *xmodel, int nmodel_points, int nparams, int nregresion_fns); void makeHMatrix_fnptr(gsl_matrix *h_matrix, gsl_matrix *xmodel, int nmodel_points, int nparams, int nregression_fns, void (*makeHVector_ptr)(gsl_vector *h_vector, gsl_vector *x_location, int nparams)); void estimateBeta(gsl_vector *beta_vector, gsl_matrix *h_matrix, gsl_matrix* cinverse, gsl_vector *trainingvector, int nmodel_points, int nregression_fns); void makeHVector_linear( gsl_vector *h_vector, gsl_vector *x_location, int nparams); void makeHVector_quadratic( gsl_vector *h_vector, gsl_vector *x_location, int nparams); void makeHVector_trivial(gsl_vector *h_vector, gsl_vector *x_location, int nparams); void makeHVector_cubic( gsl_vector *h_vector, gsl_vector *x_location, int nparams); #endif
{ "alphanum_fraction": 0.7788920726, "avg_line_length": 42.7346938776, "ext": "h", "hexsha": "e8f8f13481153d0ac7ec1b8a84d251c28c85e69a", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-01-30T16:43:33.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-30T16:43:33.000Z", "max_forks_repo_head_hexsha": "7d926ad04a791c7694defd88db41c13f7ee4e6aa", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "MADAI/MADAIEmulator", "max_forks_repo_path": "src/libEmu/regression.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "7d926ad04a791c7694defd88db41c13f7ee4e6aa", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "MADAI/MADAIEmulator", "max_issues_repo_path": "src/libEmu/regression.h", "max_line_length": 155, "max_stars_count": 2, "max_stars_repo_head_hexsha": "1c11f69c535acef8159ef0e780cca343785ea004", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jackdawjackdaw/emulator", "max_stars_repo_path": "src/libEmu/regression.h", "max_stars_repo_stars_event_max_datetime": "2017-06-02T00:34:49.000Z", "max_stars_repo_stars_event_min_datetime": "2015-04-02T17:37:42.000Z", "num_tokens": 544, "size": 2094 }
/*========================================================================= Copyright (c) Yue Sheng, University of Manchester and David Worth, STFC All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /** \file vvQuan3D.c \brief This is a VolView plugin to calculate several characteristics from a labelled image. The following characteristics are calculated: \li Volume by voxel counts \li Equivalent sphere diameter by voxel counts \li Bounding box diagonal \li Principal Component Analysis \li Ellipsoid fitting by PCA \li Equivalent circle diameter by PCA \li Isosurface by marching cube \li Surface area \li Surface volume \li Equivalent sphere diameter from surface volume \li Sphercity \li Normalised surface area to volume ratio (Radius*Sa/Vol) */ #include "vvHelper.h" #include "vtkVVPluginAPI.h" #include <dlfcn.h> #include <limits.h> #include <math.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <gsl/gsl_eigen.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> /** Struct used when calculating the number of voxels with each voxel value */ typedef struct { /** The voxel value */ int value; /** The number of voxels with this value */ int count; } vvQuan3DVoxelCount; /** Comparison function for sorting the image data. \param a Integer value \param b Integer value \return 1 if \c a>b; -1 if \c a<b; 0 if \c a==b. */ int cmpfun(void *a, void *b) { return ( *(int*)a - *(int*)b ); } /** \brief Calculate sphere diameter from the sphere volume. Use the formula \f$ 2*(3v/(4\pi))^{\frac{1}{3}} \f$ where \f$ v \f$ is the sphere volume. \param volume The sphere volume \return Diameter of the sphere */ double vol2dia(double volume) { return 2.0 * pow((3.0*volume)/(4.0*3.14159265),(1.0/3.0)); } /** \brief Find the (i,j,k) coordinates for each voxel id and also calculate maximum, minimum and mean coordinates. The positions pointer must be allocated by the calling function as follows \code positions = malloc(3*sizeof(int)*voxelCount); \endcode \param voxelSubArray Array of voxel ids \param voxelCount Number of voxels in voxelSubArray <b>NB This is not the length of the array</b> \param dim The dimsnesions of the image \param positions Pointer to matrix which will hold the (i,j,k) coordinates \param min The minimum coordinate in each dimension \param max The maximum coordinate in each dimension \param mean The mean of the coordinates in each dimension */ void getCoords(int *voxelSubArray, int voxelCount, int dim[], gsl_matrix *positions, int min[], int max[], int mean[]) { int i; int voxelId; int icoord, jcoord, kcoord, rem; min[0] = min[1] = min[2] = INT_MAX; max[0] = max[1] = max[2] = INT_MIN; mean[0] = mean[1] = mean[2] = 0; /* Loop over the voxels and calulate i,j,k coords for each one */ for (i = 0; i < voxelCount; i++) { voxelId = voxelSubArray[i]; kcoord = floor(voxelId / (dim[0]*dim[1])); rem = voxelId % (dim[0]*dim[1]); jcoord = floor(rem / dim[0]); icoord = rem % dim[0]; //printf("voxel %d (%d,%d,%d)\n",voxelId,icoord,jcoord,kcoord); gsl_matrix_set(positions,i,0,icoord); gsl_matrix_set(positions,i,1,jcoord); gsl_matrix_set(positions,i,2,kcoord); if (icoord > max[0]) max[0] = icoord; if (jcoord > max[1]) max[1] = jcoord; if (kcoord > max[2]) max[2] = kcoord; if (icoord < min[0]) min[0] = icoord; if (jcoord < min[1]) min[1] = jcoord; if (kcoord < min[2]) min[2] = kcoord; mean[0] += icoord; mean[1] += jcoord; mean[2] += kcoord; } mean[0] /= voxelCount; mean[1] /= voxelCount; mean[2] /= voxelCount; } /** \brief Calculate the data from the image \author David Worth, STFC \date May 2012 \todo This only works for unsigned short image type. Make it do other integer datatypes. \param inf Pointer to object that holds data for this plugin. The voxel size can be obtained from it. \param pds Pointer to object that carries information on data set to be processed. Includes actual buffer of voxel data, number of voxels along each dimension, voxel spacing and voxel type. */ static int ProcessData(void *inf, vtkVVProcessDataStruct *pds) { /* Information about the plugin and the image */ vtkVVPluginInfo *info = (vtkVVPluginInfo *)inf; /* Number of voxels in each direction of image */ int *dim = info->InputVolumeDimensions; /* Size of datatype in the image */ unsigned int rsize = info->InputVolumeScalarSize; /* Voxel size - can be set by user in VolView */ double voxelSize = atof(info->GetGUIProperty(info, 0, VVP_GUI_VALUE)); /* Minimum and maximum raw values from image. */ double imgMin = info->InputVolumeScalarRange[0], imgMax = info->InputVolumeScalarRange[1]; /* Array of voxel counts for each value. Array index is the value. */ int maxVoxelVals = (int)ceil(imgMax)-(int)floor(imgMin)+1; int *voxelCounts = malloc(sizeof(int)*maxVoxelVals); /* Array of arrays - each sub-array holding the ids of voxels with that value */ int* *voxelArray = malloc(sizeof(int*)*maxVoxelVals); /* Pointer to sub array used when creating voxelArray */ int *voxelSubArray = NULL; /* Index array used to write into voxelSubArray */ int *indexVoxelSubArray = malloc(sizeof(int)*maxVoxelVals); /* Number of the non-background voxels */ int sumVoxels = 0; /* Number of different voxel values */ int totalParticles = 0; /* Array of (i,j,k) coordinates for voxels with a particular value */ gsl_matrix *positions = NULL; /* Stats for voxel data for each value */ int max[3], min[3], mean[3], boundingBoxSize[3]; double boundingBoxDiam; /* Multiplication factors based on physical voxel size */ double areaFactor = pow(voxelSize,2), volumeFactor = pow(voxelSize,3); /* Output data */ int voxelLabel, voxelCount; double voxelCountVolume, voxelCountDia; /* Data used when covariance matrix is calculated */ double* *matrix = NULL; double *row = NULL; double* *covMatrix = NULL; /* Data for eigenanalysis of covariance matrix */ gsl_matrix *gslCovMatrix = NULL; gsl_vector *eval = NULL; gsl_matrix *evecs = NULL; gsl_eigen_symmv_workspace *workspace = NULL; gsl_vector vector; int result; void *gslcblas_handle, *gsl_handle; /* Buffer for output to user */ char buffer[1000]; int i, j = 0; /* The raw image data */ unsigned short *ptr = (unsigned short *)pds->inData; /* Check the data type */ switch (info->InputVolumeScalarType) { case VTK_CHAR: case VTK_UNSIGNED_CHAR: case VTK_FLOAT: case VTK_DOUBLE: { sprintf(buffer, "Image datatype must be integer or boolean. This \ algorithm cannot continue"); info->SetProperty(info, VVP_ERROR, buffer); return -1; break; } } printf("Image has type %d size %d\n", info->InputVolumeScalarType,rsize); printf("The dimensions of the image are: %d, %d, %d \n", dim[0], dim[1], dim[2]); sprintf(buffer, "The dimensions of the image are: %d, %d, %d \n", dim[0], dim[1], dim[2]); printf("There are %d components\n",info->InputVolumeNumberOfComponents); printf("The minimum value in the image is %d\n", (int)imgMin); printf("and the maximum value is %d\n", (int)imgMax); /* Sort the image values */ /*qsort(ptr, (size_t)(dim[0]*dim[1]*dim[2]), (size_t)info->InputVolumeScalarSize, (__compar_fn_t)cmpfun);*/ /* * Create array of voxel counts for each voxel value except the min value * which we take to be the background */ for (i = 0; i < maxVoxelVals; i++) voxelCounts[i]=0; for (i = 0; i < dim[0]*dim[1]*dim[2]; i++) { if (ptr[i] != imgMin) { /* Not the minimum value */ if (ptr[i] > imgMax) printf("%d %d\n",i,ptr[i]); /* Something wrong */ /* Not seen this value before so it's a new particle */ if (voxelCounts[ptr[i]] == 0) totalParticles++; voxelCounts[ptr[i]]++; sumVoxels++; } } /* Create the array of arrays with voxel ids for each voxel value */ for (i = 0; i < maxVoxelVals; i++) { if (voxelCounts[i] > 0) { /*printf("Non zero voxel count for i = %d - count is %d\n",i,voxelCounts[i]);*/ voxelArray[i] = malloc(voxelCounts[i]*sizeof(int)); } else voxelArray[i] = NULL; indexVoxelSubArray[i] = 0; } /* Now populate that array with values */ for (i = 0; i < dim[0]*dim[1]*dim[2]; i++) { if (ptr[i] != imgMin) { //printf("add entry to voxel array %d - entry id %d\n",ptr[i],i); voxelSubArray = voxelArray[ptr[i]]; voxelSubArray[ indexVoxelSubArray[ptr[i]] ] = i; indexVoxelSubArray[ptr[i]]++; } } printf("Porosity is %f\n",(double)sumVoxels/(double)(dim[0]*dim[1]*dim[2])); sprintf(buffer+strlen(buffer), "Porosity is %f\n", (double)sumVoxels/(double)(dim[0]*dim[1]*dim[2])); printf("Number of particles is %d\n",totalParticles); /* Load the GSL BLAS and GSL itself. RTLD_GLOBAL means we can use the * function names from GSL rather than having to get function pointers with * dlsym. */ gslcblas_handle = dlopen("/usr/lib/libgslcblas.so", RTLD_LAZY|RTLD_GLOBAL); if (!gslcblas_handle) { printf("Error opening libgslcblas.so - %s\n",dlerror()); } gsl_handle = dlopen("/usr/lib/libgsl.so", RTLD_LAZY|RTLD_GLOBAL); if (!gsl_handle) { printf("Error opening libgsl.so - %s\n",dlerror()); } /* Allocate the GSL matrices and vectors for eigenanalysis */ gslCovMatrix = gsl_matrix_alloc(3,3); eval = gsl_vector_alloc(3); evecs = gsl_matrix_alloc(3,3); workspace = gsl_eigen_symmv_alloc(3); /* Loop over the particles */ for (i = 0; i < 1/*totalParticles*/; i++) { /* Find the next particle with a non-zero voxel count */ while ((j < maxVoxelVals) && (voxelCounts[j] == 0)) j++; /* Do some simple stuff */ voxelLabel = j; voxelCount = voxelCounts[j]; voxelCountVolume = voxelCount * volumeFactor; voxelCountDia = voxelSize*vol2dia(voxelCount); printf("%d, %d, %f, %f",voxelLabel,voxelCount,voxelCountVolume, voxelCountDia); /* Find the (i,j,k) coordinates in the image of the voxels */ positions = gsl_matrix_alloc(voxelCount,3); voxelSubArray = voxelArray[voxelLabel]; getCoords(voxelSubArray, voxelCount, dim, positions, min, max, mean); /*printf(" (%d, %d, %d)",min[0],min[1],min[2]); printf(" (%d, %d, %d)",max[0],max[1],max[2]); printf(" (%d, %d, %d)",mean[0],mean[1],mean[2]);*/ boundingBoxSize[0] = max[0]-min[0]+1; boundingBoxSize[1] = max[1]-min[1]+1; boundingBoxSize[2] = max[2]-min[2]+1; boundingBoxDiam = sqrt(boundingBoxSize[0]*boundingBoxSize[0] + boundingBoxSize[1]*boundingBoxSize[1] + boundingBoxSize[2]*boundingBoxSize[2])*voxelSize; printf(" (%d, %d, %d)",boundingBoxSize[0],boundingBoxSize[1], boundingBoxSize[2]); printf(" %f", boundingBoxDiam); /* Calculate positions-mean */ matrix = malloc(voxelCount*sizeof(double*)); for (j = 0; j < voxelCount; j++) { row = malloc(3*sizeof(double)); row[0] = gsl_matrix_get(positions,j,0)-mean[0]; row[1] = gsl_matrix_get(positions,j,1)-mean[1]; row[2] = gsl_matrix_get(positions,j,2)-mean[2]; matrix[j] = row; } covMatrix = CovMat(matrix, voxelCount, 3); for (j = 0; j < voxelCount; j++) { free(matrix[j]); } free(matrix); /*printf("\nCovariance matrix\n"); for (j = 0; j < 3; j++) { printf("%f %f %f\n", covMatrix[j][0], covMatrix[j][1], covMatrix[j][2]); }*/ /* To do the eigenanalysis use GNU Scientific library so create matrix * in that format */ for (j = 0; j < 3; j++) { gsl_matrix_set(gslCovMatrix,0,j,covMatrix[0][j]); gsl_matrix_set(gslCovMatrix,1,j,covMatrix[1][j]); gsl_matrix_set(gslCovMatrix,2,j,covMatrix[2][j]); } /* Calculate eigenvalues and vectors */ result = gsl_eigen_symmv(gslCovMatrix, eval, evecs, workspace); printf("\nEigenvalues\n"); gsl_vector_fprintf(stdout, eval, "%g"); printf("\nEigenvectors\n"); vector = gsl_matrix_const_column(evecs,0).vector; gsl_vector_fprintf(stdout, &vector, "%g"); printf("\n"); vector = gsl_matrix_const_column(evecs,1).vector; gsl_vector_fprintf(stdout, &vector, "%g"); printf("\n"); vector = gsl_matrix_const_column(evecs,2).vector; gsl_vector_fprintf(stdout, &vector, "%g"); for (j = 0; j < 3; j++) { free(covMatrix[j]); } free(covMatrix); gsl_matrix_free(positions); printf("\n"); /* Move on to next particle */ j++; } dlclose(gsl_handle); dlclose(gslcblas_handle); info->SetProperty(info, VVP_REPORT_TEXT, buffer); free(voxelCounts); for (i = 0; i < maxVoxelVals; i++) { if (voxelArray[i] != NULL) free(voxelArray[i]); } gsl_matrix_free(gslCovMatrix); gsl_vector_free(eval); gsl_matrix_free(evecs); gsl_eigen_symmv_free(workspace); free(voxelArray); free(indexVoxelSubArray); return 0; } /** \brief Update the VolView GUI to display user parameters. Sets one GUI parameter - the physical size of the voxels in the image. \param inf Pointer to object that should be modified to set up GUI elements for this plugin. It also contains details of the input and output images. */ static int UpdateGUI(void *inf) { int i; vtkVVPluginInfo *info = (vtkVVPluginInfo *)inf; info->SetGUIProperty(info, 0, VVP_GUI_LABEL, "Voxel Size"); info->SetGUIProperty(info, 0, VVP_GUI_TYPE, VVP_GUI_SCALE); info->SetGUIProperty(info, 0, VVP_GUI_DEFAULT , "1"); info->SetGUIProperty(info, 0, VVP_GUI_HELP, "The physical size of a voxel in the image"); /* what range should we show for possible output values */ vvPluginSetGUIScaleRange(0); info->OutputVolumeScalarType = info->InputVolumeScalarType; info->OutputVolumeNumberOfComponents = info->InputVolumeNumberOfComponents; for (i = 0; i < 3; i++) { info->OutputVolumeDimensions[i] = info->InputVolumeDimensions[i]; info->OutputVolumeSpacing[i] = info->InputVolumeSpacing[i]; info->OutputVolumeOrigin[i] = info->InputVolumeOrigin[i]; } return 1; } /** \brief Initialise this plugin. Sets the name and group for this plugin in the plugin list shown to the VolView user and gives some documentation. Also defines properties so VolView can judge the memory requirements and potential for undoing this plugin. \param info Pointer to object that should be modified to give details about this plugin. */ void VV_PLUGIN_EXPORT vvQuan3DCInit(vtkVVPluginInfo *info) { /* always check the version */ vvPluginVersionCheck(); /* setup information that never changes */ info->ProcessData = ProcessData; info->UpdateGUI = UpdateGUI; info->SetProperty(info, VVP_NAME, "Quantify 3D in C"); info->SetProperty(info, VVP_GROUP, "Quantification"); info->SetProperty(info, VVP_TERSE_DOCUMENTATION, "Quantify several characteristics from a labelled image"); info->SetProperty(info, VVP_FULL_DOCUMENTATION, "Quantify the following characteristics from a labelled image: Volume by \ voxel counts, Equivalent sphere diameter by voxel counts, Bounding box \ diagonal, Principal Component Analysis, Ellipsoid fitting by PCA, Equivalent \ circle diameter by PCA, Isosurface by marching cube, Surface area, Surface \ volume, Equivalent sphere diameter from surface volume, Sphercity, Normalised \ surface area to volume ratio"); info->SetProperty(info, VVP_SUPPORTS_IN_PLACE_PROCESSING, "1"); info->SetProperty(info, VVP_SUPPORTS_PROCESSING_PIECES, "1"); info->SetProperty(info, VVP_REQUIRED_Z_OVERLAP, "0"); info->SetProperty(info, VVP_NUMBER_OF_GUI_ITEMS, "1"); info->SetProperty(info, VVP_REQUIRES_SERIES_INPUT, "0"); info->SetProperty(info, VVP_SUPPORTS_PROCESSING_SERIES_BY_VOLUMES, "0"); info->SetProperty(info, VVP_PRODUCES_OUTPUT_SERIES, "0"); info->SetProperty(info, VVP_PRODUCES_PLOTTING_OUTPUT, "0"); }
{ "alphanum_fraction": 0.6585173502, "avg_line_length": 35.0723404255, "ext": "c", "hexsha": "a47ebc69fbdadedd023bbfa99cfcd606ebe74305", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "cb53ff9abf865c48b1cf240932f6aa0f647b6a4f", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "vais-ral/CCPi-Quantification", "max_forks_repo_path": "MXIF/Quan3D/vvQuan3D.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "cb53ff9abf865c48b1cf240932f6aa0f647b6a4f", "max_issues_repo_issues_event_max_datetime": "2019-02-14T16:17:03.000Z", "max_issues_repo_issues_event_min_datetime": "2019-01-30T12:42:14.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "vais-ral/CCPi-Quantification", "max_issues_repo_path": "MXIF/Quan3D/vvQuan3D.c", "max_line_length": 85, "max_stars_count": null, "max_stars_repo_head_hexsha": "cb53ff9abf865c48b1cf240932f6aa0f647b6a4f", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "vais-ral/CCPi-Quantification", "max_stars_repo_path": "MXIF/Quan3D/vvQuan3D.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4657, "size": 16484 }
#include <erl_nif.h> #include <stdio.h> #include <string.h> #include <math.h> #include <cblas.h> /* --------------------------------------------------------------------| ------------------------------ | | LAPACKE | | ------------------------------ | --------------------------------------------------------------------| */ void dgetrf_(int* M, int *N, double* A, int* lda, int* IPIV, int* INFO); void dgetri_(int* N, double* A, int* lda, int* IPIV, double* WORK, int* lwork, int* INFO); /* --------------------------------------------------------------------| ------------------------------ | | INIT FC | | ------------------------------ | --------------------------------------------------------------------| */ ERL_NIF_TERM atom_nok; ERL_NIF_TERM atom_true; ERL_NIF_TERM atom_false; ERL_NIF_TERM atom_matrix; ErlNifResourceType *MULT_YIELDING_ARG = NULL; int load(ErlNifEnv* env, void** priv_data, ERL_NIF_TERM load_info){ atom_nok = enif_make_atom(env, "nok\0"); atom_true = enif_make_atom(env, "true\0"); atom_false = enif_make_atom(env, "false\0"); atom_matrix = enif_make_atom(env, "matrix\0"); return 0; } int upgrade(ErlNifEnv* caller_env, void** priv_data, void** old_priv_data, ERL_NIF_TERM load_info){ return 0; } //Gives easier access to an ErlangBinary containing a matrix. typedef struct{ int n_rows; int n_cols; //Content of the matrix, in row major format. double* content; //Erlang binary containing the matrix. ErlNifBinary bin; } Matrix; //Access asked coordinates of matrix double* matrix_at(int col, int row, Matrix m){ return &m.content[row*m.n_cols + col]; } //Allocates memory space of for matrix of dimensions n_rows, n_cols. //The matrix_content can be modified, until a call to array_to_erl. //Matrix content is stored in row major format. Matrix matrix_alloc(int n_rows, int n_cols){ ErlNifBinary bin; enif_alloc_binary(sizeof(double)*n_rows*n_cols, &bin); Matrix matrix; matrix.n_cols = n_cols; matrix.n_rows = n_rows; matrix.bin = bin; matrix.content = (double*) bin.data; return matrix; } //Creates a duplicate of a matrix. //This duplicate can be modified until uploaded. Matrix matrix_dup(Matrix m){ Matrix d = matrix_alloc(m.n_rows, m.n_cols); memcpy(d.content, m.content, d.bin.size); return d; } //Free an allocated matrix that was not sent back to Erlang. void matrix_free(Matrix m){ enif_release_binary(&m.bin); } //Constructs a matrix erlang term. //No modifications can be made afterwards to the matrix. ERL_NIF_TERM matrix_to_erl(ErlNifEnv* env, Matrix m){ ERL_NIF_TERM term = enif_make_binary(env, &m.bin); return enif_make_tuple4(env, atom_matrix, enif_make_int(env,m.n_rows), enif_make_int(env,m.n_cols), term); } int enif_is_matrix(ErlNifEnv* env, ERL_NIF_TERM term){ int arity; const ERL_NIF_TERM* content; if(!enif_is_tuple(env, term)) return 0; enif_get_tuple(env, term, &arity, &content); if(arity != 4) return 0; if(content[0] != atom_matrix || !enif_is_number(env, content[1]) || !enif_is_number(env, content[2]) || !enif_is_binary(env, content[3])) return 0; return 1; } //Reads an erlang term as a matrix. //As such, no modifications can be made to the red matrix. //Returns true if it was possible to read a matrix, false otherwise int enif_get_matrix(ErlNifEnv* env, ERL_NIF_TERM term, Matrix *dest){ int arity; const ERL_NIF_TERM* content; if(!enif_is_tuple(env, term)) return 0; enif_get_tuple(env, term, &arity, &content); if(arity != 4) return 0; if(content[0] != atom_matrix || !enif_get_int(env, content[1], &dest->n_rows) || !enif_get_int(env, content[2], &dest->n_cols) || !enif_inspect_binary(env, content[3], &dest->bin)) { return 0; } dest->content = (double*) (dest->bin.data); return 1; } //Used to translate at once a number of ERL_NIF_TERM. //Data types are inferred via content of format string: // n: number (int or double) translated to double. // m: matrix // i: int int enif_get(ErlNifEnv* env, const ERL_NIF_TERM* erl_terms, const char* format, ...){ va_list valist; va_start(valist, format); int valid = 1; while(valid && *format != '\0'){ switch(*format++){ case 'n': //Read a number as a double. ; double *d = va_arg(valist, double*); int i; if(!enif_get_double(env, *erl_terms, d)) if(enif_get_int(env, *erl_terms, &i)) *d = (double) i; else valid = 0; break; case 'm': //Reads a matrix. valid = enif_get_matrix(env, *erl_terms, va_arg(valist, Matrix*)); break; case 'i': //Reads an int. valid = enif_get_int(env, *erl_terms, va_arg(valist, int*)); break; default: //Unknown type... give an error. valid = 0; break; } erl_terms ++; } va_end(valist); return valid; } //----------------------------------------------------------------------------------------------------| // ------------------------------------------ | // | NIFS | | // ------------------------------------------ | //----------------------------------------------------------------------------------------------------| //@arg 0: List of Lists of numbers. //@return: Matrix of dimension ERL_NIF_TERM nif_matrix(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){ unsigned n_rows, line_length, dest = 0, n_cols = -1; ERL_NIF_TERM list = argv[0], row, elem; Matrix m; //Reading incoming matrix. if(!enif_get_list_length(env, list, &n_rows) && n_rows > 0) return enif_make_badarg(env); for(int i = 0; enif_get_list_cell(env, list, &row, &list); i++){ if(!enif_get_list_length(env, row, &line_length)) return enif_make_badarg(env); if(n_cols == -1){ //Allocate binary, make matrix accessor. n_cols = line_length; m = matrix_alloc(n_rows,n_cols); } if(n_cols != line_length) return enif_make_badarg(env); for(int j = 0; enif_get_list_cell(env, row, &elem, &row); j++){ if(!enif_get_double(env, elem, &m.content[dest])){ int i; if(enif_get_int(env, elem, &i)){ m.content[dest] = (double) i; } else{ return enif_make_badarg(env); } } dest++; } } return matrix_to_erl(env, m); } #define PRECISION 10 //Used for debug purpose. void debug_write(char info[]){ FILE* fp = fopen("debug.txt", "a"); fprintf(fp, info); fprintf(fp, "\n"); fclose(fp); } void debug_write_matrix(Matrix m){ char *content = enif_alloc(sizeof(char)*((2*m.n_cols-1)*m.n_rows*PRECISION + m.n_rows*2 + 3)); content[0] = '['; content[1] = '\0'; char converted[PRECISION]; for(int i=0; i<m.n_rows; i++){ strcat(content, "["); for(int j = 0; j<m.n_cols; j++){ snprintf(converted, PRECISION-1, "%.5lf", m.content[i*m.n_cols+j]); strcat(content, converted); if(j != m.n_cols-1) strcat(content, " "); } strcat(content, "]"); } strcat(content, "]"); debug_write(content); enif_free(content); } //@arg 0: matrix. //@arg 1: int, coord m: row //@arg 2: int, coord n: col //@return: double, at cord Matrix(m,n). ERL_NIF_TERM nif_get(ErlNifEnv * env, int argc, const ERL_NIF_TERM argv[]){ int m,n; Matrix matrix; if(!enif_get(env, argv, "iim", &m, &n, &matrix)) return enif_make_badarg(env); m--, n--; if(m < 0 || m >= matrix.n_rows || n < 0 || n >= matrix.n_cols) return enif_make_badarg(env); int index = m*matrix.n_cols+n; return enif_make_double(env, matrix.content[index]); } ERL_NIF_TERM nif_at(ErlNifEnv * env, int argc, const ERL_NIF_TERM argv[]){ int n; Matrix matrix; if(!enif_get(env, argv, "mi", &matrix, &n)) return enif_make_badarg(env); n--; if( n < 0 || n >= matrix.n_cols * matrix.n_rows) return enif_make_badarg(env); return enif_make_double(env, matrix.content[n]); } //Matrix to flattened list of ints ERL_NIF_TERM nif_mtfli(ErlNifEnv * env, int argc, const ERL_NIF_TERM argv[]){ Matrix M; if(!enif_get(env, argv, "m", &M)){ return enif_make_badarg(env); } int n_elems = M.n_cols * M.n_rows; ERL_NIF_TERM *arr = enif_alloc(sizeof(ERL_NIF_TERM)*n_elems); for(int i = 0; i<n_elems; i++){ arr[i] = enif_make_int(env, (int)M.content[i]); } ERL_NIF_TERM result = enif_make_list_from_array(env, arr, n_elems); enif_free(arr); return result; } //Matrix to flattened list of ints ERL_NIF_TERM nif_mtfl(ErlNifEnv * env, int argc, const ERL_NIF_TERM argv[]){ Matrix M; if(!enif_get(env, argv, "m", &M)){ return enif_make_badarg(env); } int n_elems = M.n_cols * M.n_rows; ERL_NIF_TERM *arr = enif_alloc(sizeof(ERL_NIF_TERM)*n_elems); for(int i = 0; i<n_elems; i++){ arr[i] = enif_make_double(env, M.content[i]); } ERL_NIF_TERM result = enif_make_list_from_array(env, arr, n_elems); enif_free(arr); return result; } //Equal all doubles //Compares whether all doubles are approximately the same. int equal_ad(double* a, double* b, int size){ for(int i = 0; i<size; i++){ if(fabs(a[i] - b[i])> 1e-6) return 0; } return 1; } //@arg 0: Array. //@arg 1: Array. //@return: true if arrays share content, false if they have different content || size.. ERL_NIF_TERM nif_equals(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){ Matrix a,b; if(!enif_get(env, argv, "mm", &a, &b)) return atom_false; //Compare number of columns and rows if((a.n_cols != b.n_cols || a.n_rows != b.n_rows)) return atom_false; //Compare content of arrays if(!equal_ad(a.content, b.content, a.n_cols*a.n_rows)) return atom_false; return atom_true; } //@arg 0: int. //@arg 1: Array. //@return: returns an array, containing requested row. ERL_NIF_TERM nif_row(ErlNifEnv * env, int argc, const ERL_NIF_TERM argv[]){ int row_req; Matrix matrix; if(!enif_get(env, argv, "im", &row_req, &matrix)) return enif_make_badarg(env); row_req--; if(row_req<0 || row_req >= matrix.n_rows) return enif_make_badarg(env); Matrix row = matrix_alloc(1, matrix.n_cols); memcpy(row.content, matrix.content + (row_req * matrix.n_cols), matrix.n_cols*sizeof(double)); return matrix_to_erl(env, row); } //@arg 0: int. //@arg 1: Array. //@return: returns an array, containing requested col. ERL_NIF_TERM nif_col(ErlNifEnv * env, int argc, const ERL_NIF_TERM argv[]){ int col_req; Matrix matrix; if(!enif_get(env, argv, "im", &col_req, &matrix)) return enif_make_badarg(env); col_req--; if(col_req<0 || col_req >= matrix.n_cols) return enif_make_badarg(env); Matrix col = matrix_alloc(matrix.n_rows, 1); for(int i = 0; i < matrix.n_rows; i++){ col.content[i] = matrix.content[i * matrix.n_rows + col_req]; } return matrix_to_erl(env, col); } //@arg 0: int. //@arg 1: int. //@return: empty Matrix of requested dimension.. ERL_NIF_TERM nif_zeros(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){ int m,n; if(!enif_get(env, argv, "ii", &m, &n)) return enif_make_badarg(env); Matrix a = matrix_alloc(m,n); memset(a.content, 0, sizeof(double)*m*n); return matrix_to_erl(env, a); } //@arg 0: int. //@arg 1: int. //@return: empty matrix of dimension [arg 0, arg 1].. ERL_NIF_TERM nif_eye(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){ int m; if(!enif_get_int(env, argv[0], &m)) return enif_make_badarg(env); if(m <= 0) return enif_make_badarg(env); Matrix a = matrix_alloc(m,m); memset(a.content, 0, sizeof(double)*m*m); for(int i = 0; i<m; i++){ a.content[i*m+i] = 1.0; } return matrix_to_erl(env, a); } //Either element-wise multiplication, or multiplication of a matrix by a number. ERL_NIF_TERM nif_mult(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){ Matrix a,b; double c; if(enif_get(env, argv, "mn", &a, &c)){ Matrix d = matrix_alloc(a.n_rows, a.n_cols); for(int i = 0; i<a.n_cols*a.n_rows; i++){ d.content[i] = a.content[i] * c; } return matrix_to_erl(env, d); } else if(enif_get(env, argv, "mm", &a, &b) && a.n_rows*a.n_cols == b.n_rows*b.n_cols){ Matrix d = matrix_alloc(a.n_rows, a.n_cols); for(int i = 0; i < a.n_rows*a.n_cols; i++){ d.content[i] = a.content[i] * b.content[i]; } return matrix_to_erl(env, d); } return enif_make_badarg(env); } //Either element-wise addition, or addition of a matrix by a number. ERL_NIF_TERM nif_add(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){ Matrix a,b; double c; if(enif_get(env, argv, "mn", &a, &c)){ Matrix d = matrix_alloc(a.n_rows, a.n_cols); for(int i = 0; i<a.n_cols*a.n_rows; i++){ d.content[i] = a.content[i] + c; } return matrix_to_erl(env, d); } else if(enif_get(env, argv, "mm", &a, &b) && a.n_rows*a.n_cols == b.n_rows*b.n_cols){ Matrix d = matrix_alloc(a.n_rows, a.n_cols); for(int i = 0; i < a.n_rows*a.n_cols; i++){ d.content[i] = a.content[i] + b.content[i]; } return matrix_to_erl(env, d); } return enif_make_badarg(env); } //Either element-wise subtraction, or subtraction of a matrix by a number. ERL_NIF_TERM nif_sub(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){ Matrix a,b; double c; if(enif_get(env, argv, "mn", &a, &c)){ Matrix d = matrix_alloc(a.n_rows, a.n_cols); for(int i = 0; i<a.n_cols*a.n_rows; i++){ d.content[i] = a.content[i] - c; } return matrix_to_erl(env, d); } else if(enif_get(env, argv, "mm", &a, &b) && a.n_rows*a.n_cols == b.n_rows*b.n_cols){ Matrix d = matrix_alloc(a.n_rows, a.n_cols); for(int i = 0; i < a.n_rows*a.n_cols; i++){ d.content[i] = a.content[i] - b.content[i]; } return matrix_to_erl(env, d); } return enif_make_badarg(env); } //Either element-wise division, or division of a matrix by a number. ERL_NIF_TERM nif_divide(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){ Matrix a,b; double c; if(enif_get(env, argv, "mn", &a, &c)){ if(c!=0.0){ Matrix d = matrix_alloc(a.n_rows, a.n_cols); for(int i = 0; i<a.n_cols*a.n_rows; i++){ d.content[i] = a.content[i] / c; } return matrix_to_erl(env, d); } } else if(enif_get(env, argv, "mm", &a, &b) && a.n_rows*a.n_cols == b.n_rows*b.n_cols){ Matrix d = matrix_alloc(a.n_rows, a.n_cols); for(int i = 0; i < a.n_rows*a.n_cols; i++){ if(b.content[i] == 0.0){ return enif_make_badarg(env); } else{ d.content[i] = a.content[i] / b.content[i]; } } return matrix_to_erl(env, d); } return enif_make_badarg(env); } //Transpose of a matrix. Matrix tr(Matrix a){ Matrix result = matrix_alloc(a.n_cols ,a.n_rows); for(int j = 0; j < a.n_rows; j++){ for(int i = 0; i < a.n_cols; i++){ result.content[i*result.n_cols+j] = a.content[j*a.n_cols+i]; } } return result; } ERL_NIF_TERM nif_transpose(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){ Matrix a; if(!enif_get_matrix(env, argv[0], &a)) return enif_make_badarg(env); return matrix_to_erl(env, tr(a)); } //arg0: Matrix. ERL_NIF_TERM nif_inv(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){ Matrix a; if(!enif_get_matrix(env, argv[0], &a)) return enif_make_badarg(env); Matrix inv = matrix_dup(a); int N = a.n_rows; int *IPIV = enif_alloc(sizeof(int)*N); int LWORK = N*N; double* WORK = enif_alloc(sizeof(int)*N*N); int INFO1, INFO2; dgetrf_(&N,&N,inv.content,&N,IPIV,&INFO1); dgetri_(&N,inv.content,&N,IPIV,WORK,&LWORK,&INFO2); enif_free(IPIV); enif_free(WORK); ERL_NIF_TERM result; if(INFO1 > 0 || INFO2 > 0){ result = enif_raise_exception(env, enif_make_atom(env, "nif_inv: could not invert singular matrix.")); matrix_free(inv); } else if(INFO1 < 0 || INFO2 < 0){ result = enif_raise_exception(env, enif_make_atom(env, "nif_inv: LAPACK error.")); matrix_free(inv); } else result = matrix_to_erl(env, inv); return result; } //----------------------------------------------------------------------------------------------------| // ------------------------------------------ | // | CBLAS | | // ------------------------------------------ | //----------------------------------------------------------------------------------------------------| //Some CBLAS wrappers. //Calculates the norm of input vector/matrix, aka the square root of the sum of its composants. ERL_NIF_TERM nif_dnrm2(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){ Matrix x; if(!enif_get(env, argv, "m", &x)){ return enif_make_badarg(env); } double result = cblas_dnrm2(x.n_cols*x.n_rows, x.content, 1); return enif_make_double(env, result); } //Performs blas_ddot //Input: two vectors / matrices ERL_NIF_TERM nif_ddot(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){ Matrix x,y; if(!enif_get(env, argv, "mm", &x, &y)){ return enif_make_badarg(env); } int n = fmin(x.n_rows*x.n_cols, y.n_rows*y.n_cols); if(n <= 0){ return enif_make_badarg(env); } double result = cblas_ddot(n, x.content, 1, y.content, 1); return enif_make_double(env, result); } //Performs blas_daxpy //Input: a number, vectors X and Y //Output: a vector of same dimension then Y, containing alpha X + Y //------------------------------------------------------------------------ ERL_NIF_TERM nif_daxpy(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){ Matrix x,y; int n; double alpha; if(!enif_get(env, argv, "inmm", &n, &alpha, &x, &y)){ return enif_make_badarg(env); } if(fmin(x.n_rows, x.n_cols) * fmin(y.n_rows, y.n_cols) != 1){ //We are not using vectors... return enif_make_badarg(env); } Matrix ny = matrix_dup(y); cblas_daxpy(n, alpha, x.content, 1, ny.content, 1); return matrix_to_erl(env, ny); } // Arguments: alpha, A, x, beta, y // Performs alpha*A*x + beta*y. // alpha, beta are numbers // A, x, y are matrices (x and y being vectors) // x and y are expected to have a length of A.n_cols ERL_NIF_TERM nif_dgemv(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){ Matrix A,x,y; double alpha, beta; if(!enif_get(env, argv, "nmmnm", &alpha, &A, &x, &beta, &y)){ enif_make_badarg(env); } //Check dimensions compatibility int vec_length = fmin(fmax(x.n_cols, x.n_rows), fmax(y.n_cols, y.n_rows)); if(vec_length < A.n_cols || fmin(x.n_cols, x.n_rows) != 1 || fmin(y.n_cols, y.n_rows) != 1){ enif_make_badarg(env); } Matrix ny = matrix_dup(y); cblas_dgemv(CblasRowMajor, CblasNoTrans, A.n_rows, A.n_cols, alpha, A.content, A.n_rows, x.content, 1, beta, ny.content, 1); return matrix_to_erl(env, ny); } //Arguments: double alpha, matrix A, matrix B, double beta, matrix C ERL_NIF_TERM nif_dgemm(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){ Matrix A, B; double alpha = 1.0; double beta = 0.0; if(!enif_get(env, argv, "mm", &A, &B) || A.n_cols != B.n_rows){ return enif_make_badarg(env); } Matrix C = matrix_alloc(A.n_rows, B.n_cols); cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, A.n_rows, B.n_cols, A.n_cols, alpha, A.content, A.n_cols, B.content, B.n_rows, 1.0, C.content, C.n_cols); return matrix_to_erl(env, C); } ErlNifFunc nif_funcs[] = { {"matrix", 1, nif_matrix}, {"get", 3, nif_get}, {"at", 2, nif_at}, {"mtfli", 1, nif_mtfli}, {"mtfl", 1, nif_mtfl}, {"equals", 2, nif_equals}, {"row", 2, nif_row}, {"col", 2, nif_col}, {"zeros", 2, nif_zeros}, {"eye", 1, nif_eye}, {"mult", 2, nif_mult}, {"add", 2, nif_add}, {"sub", 2, nif_sub}, {"divide", 2, nif_divide}, {"transpose", 1, nif_transpose}, {"inv", 1, nif_inv}, //--- BLAS---------- {"nrm2", 1, nif_dnrm2}, {"vec_dot", 2, nif_ddot}, {"dot", 2, nif_dgemm} }; ERL_NIF_INIT(numerl, nif_funcs, load, NULL, upgrade, NULL)
{ "alphanum_fraction": 0.5474756622, "avg_line_length": 28.3868894602, "ext": "c", "hexsha": "d0d9cb3f4edeb8b25f91f5f65e559506c3295ed2", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2022-01-20T04:29:43.000Z", "max_forks_repo_forks_event_min_datetime": "2022-01-08T19:51:31.000Z", "max_forks_repo_head_hexsha": "c0ca907ef54b05eb2e466a1de971361f10965086", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "tanguyl/numerl", "max_forks_repo_path": "c_src/numerl.c", "max_issues_count": 7, "max_issues_repo_head_hexsha": "c0ca907ef54b05eb2e466a1de971361f10965086", "max_issues_repo_issues_event_max_datetime": "2022-02-14T12:26:23.000Z", "max_issues_repo_issues_event_min_datetime": "2022-01-09T15:55:06.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "tanguyl/numerl", "max_issues_repo_path": "c_src/numerl.c", "max_line_length": 129, "max_stars_count": 23, "max_stars_repo_head_hexsha": "c0ca907ef54b05eb2e466a1de971361f10965086", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "tanguyl/numerl", "max_stars_repo_path": "c_src/numerl.c", "max_stars_repo_stars_event_max_datetime": "2022-01-20T04:16:14.000Z", "max_stars_repo_stars_event_min_datetime": "2021-12-18T02:51:31.000Z", "num_tokens": 6168, "size": 22085 }
#include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <math.h> #include <string.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_odeiv.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_integration.h> #include "ccl.h" #include "ccl_params.h" // // Macros for replacing relative paths #define EXPAND_STR(s) STRING(s) #define STRING(s) #s const ccl_configuration default_config = {ccl_boltzmann_class, ccl_halofit, ccl_nobaryons, ccl_tinker10, ccl_duffy2008, ccl_emu_strict}; const ccl_gsl_params default_gsl_params = {GSL_EPSREL, // EPSREL GSL_N_ITERATION, // N_ITERATION GSL_INTEGRATION_GAUSS_KRONROD_POINTS,// INTEGRATION_GAUSS_KRONROD_POINTS GSL_EPSREL, // INTEGRATION_EPSREL GSL_INTEGRATION_GAUSS_KRONROD_POINTS,// INTEGRATION_LIMBER_GAUSS_KRONROD_POINTS GSL_EPSREL, // INTEGRATION_LIMBER_EPSREL GSL_EPSREL_DIST, // INTEGRATION_DISTANCE_EPSREL GSL_EPSREL_DNDZ, // INTEGRATION_DNDZ_EPSREL GSL_EPSREL_SIGMAR, // INTEGRATION_SIGMAR_EPSREL GSL_EPSREL_NU, // INTEGRATION_NU_EPSREL GSL_EPSABS_NU, // INTEGRATION_NU_EPSABS GSL_EPSREL, // ROOT_EPSREL GSL_N_ITERATION, // ROOT_N_ITERATION GSL_EPSREL_GROWTH // ODE_GROWTH_EPSREL }; /* ------- ROUTINE: ccl_cosmology_read_config ------ INPUTS: none, but will look for ini file in include/ dir TASK: fill out global variables of splines with user defined input. The variables are defined in ccl_params.h. The following are the relevant global variables: */ ccl_spline_params * ccl_splines=NULL; // Global variable ccl_gsl_params * ccl_gsl=NULL; // Global variable void ccl_cosmology_read_config(void) { int CONFIG_LINE_BUFFER_SIZE=100; int MAX_CONFIG_VAR_LEN=100; FILE *fconfig; char buf[CONFIG_LINE_BUFFER_SIZE]; char var_name[MAX_CONFIG_VAR_LEN]; char* rtn; double var_dbl; // Get parameter .ini filename from environment variable or default location const char* param_file; const char* param_file_env = getenv("CCL_PARAM_FILE"); if (param_file_env != NULL) { param_file = param_file_env; } else { // Use default ini file param_file = EXPAND_STR(__CCL_DATA_DIR__) "/ccl_params.ini"; } if ((fconfig=fopen(param_file, "r")) == NULL) { ccl_raise_exception(CCL_ERROR_MISSING_CONFIG_FILE, "ccl_core.c: Failed to open config file: %s", param_file); return; } if(ccl_splines == NULL) { ccl_splines = malloc(sizeof(ccl_spline_params)); } if(ccl_gsl == NULL) { ccl_gsl = malloc(sizeof(ccl_gsl_params)); memcpy(ccl_gsl, &default_gsl_params, sizeof(ccl_gsl_params)); } /* Exit gracefully if we couldn't allocate memory */ if(ccl_splines==NULL || ccl_gsl==NULL) { ccl_raise_exception(CCL_ERROR_MEMORY, "ccl_core.c: Failed to allocate memory for config file data."); return; } #define MATCH(s, action) if (0 == strcmp(var_name, s)) { action ; continue;} do{} while(0) int lineno = 0; while(! feof(fconfig)) { rtn = fgets(buf, CONFIG_LINE_BUFFER_SIZE, fconfig); lineno ++; if (buf[0]==';' || buf[0]=='[' || buf[0]=='\n') { continue; } else { sscanf(buf, "%99[^=]=%le\n",var_name, &var_dbl); // Spline parameters MATCH("A_SPLINE_NA", ccl_splines->A_SPLINE_NA=(int) var_dbl); MATCH("A_SPLINE_NLOG", ccl_splines->A_SPLINE_NLOG=(int) var_dbl); MATCH("A_SPLINE_MINLOG", ccl_splines->A_SPLINE_MINLOG=var_dbl); MATCH("A_SPLINE_MIN", ccl_splines->A_SPLINE_MIN=var_dbl); MATCH("A_SPLINE_MINLOG_PK", ccl_splines->A_SPLINE_MINLOG_PK=var_dbl); MATCH("A_SPLINE_MIN_PK", ccl_splines->A_SPLINE_MIN_PK=var_dbl); MATCH("A_SPLINE_MAX", ccl_splines->A_SPLINE_MAX=var_dbl); MATCH("LOGM_SPLINE_DELTA", ccl_splines->LOGM_SPLINE_DELTA=var_dbl); MATCH("LOGM_SPLINE_NM", ccl_splines->LOGM_SPLINE_NM=(int) var_dbl); MATCH("LOGM_SPLINE_MIN", ccl_splines->LOGM_SPLINE_MIN=var_dbl); MATCH("LOGM_SPLINE_MAX", ccl_splines->LOGM_SPLINE_MAX=var_dbl); MATCH("A_SPLINE_NA_PK", ccl_splines->A_SPLINE_NA_PK=(int) var_dbl); MATCH("A_SPLINE_NLOG_PK", ccl_splines->A_SPLINE_NLOG_PK=(int) var_dbl); MATCH("K_MAX_SPLINE", ccl_splines->K_MAX_SPLINE=var_dbl); MATCH("K_MAX", ccl_splines->K_MAX=var_dbl); MATCH("K_MIN", ccl_splines->K_MIN=var_dbl); MATCH("N_K", ccl_splines->N_K=(int) var_dbl); // 3dcorr parameters MATCH("N_K_3DCOR", ccl_splines->N_K_3DCOR=(int) var_dbl); // GSL parameters MATCH("GSL_EPSREL", ccl_gsl->EPSREL=var_dbl); MATCH("GSL_N_ITERATION", ccl_gsl->N_ITERATION=(size_t) var_dbl); MATCH("GSL_INTEGRATION_GAUSS_KRONROD_POINTS", ccl_gsl->INTEGRATION_GAUSS_KRONROD_POINTS=(int) var_dbl); MATCH("GSL_INTEGRATION_EPSREL", ccl_gsl->INTEGRATION_EPSREL=var_dbl); MATCH("GSL_INTEGRATION_DISTANCE_EPSREL", ccl_gsl->INTEGRATION_DISTANCE_EPSREL=var_dbl); MATCH("GSL_INTEGRATION_DNDZ_EPSREL", ccl_gsl->INTEGRATION_DNDZ_EPSREL=var_dbl); MATCH("GSL_INTEGRATION_SIGMAR_EPSREL", ccl_gsl->INTEGRATION_SIGMAR_EPSREL=var_dbl); MATCH("GSL_INTEGRATION_NU_EPSREL", ccl_gsl->INTEGRATION_NU_EPSREL=var_dbl); MATCH("GSL_INTEGRATION_NU_EPSABS", ccl_gsl->INTEGRATION_NU_EPSABS=var_dbl); MATCH("GSL_INTEGRATION_LIMBER_GAUSS_KRONROD_POINTS", ccl_gsl->INTEGRATION_LIMBER_GAUSS_KRONROD_POINTS=(int) var_dbl); MATCH("GSL_INTEGRATION_LIMBER_EPSREL", ccl_gsl->INTEGRATION_LIMBER_EPSREL=var_dbl); MATCH("GSL_ROOT_EPSREL", ccl_gsl->ROOT_EPSREL=var_dbl); MATCH("GSL_ROOT_N_ITERATION", ccl_gsl->ROOT_N_ITERATION=(int) var_dbl); MATCH("GSL_ODE_GROWTH_EPSREL", ccl_gsl->ODE_GROWTH_EPSREL=var_dbl); ccl_raise_exception(CCL_ERROR_MISSING_CONFIG_FILE, "ccl_core.c: Failed to parse config file at line %d: %s", lineno, buf); } } #undef MATCH fclose(fconfig); } /* ------- ROUTINE: ccl_cosmology_create ------ INPUTS: ccl_parameters params ccl_configuration config TASK: creates the ccl_cosmology struct and passes some values to it DEFINITIONS: chi: comoving distance [Mpc] growth: growth function (density) fgrowth: logarithmic derivative of the growth (density) (dlnD/da?) E: E(a)=H(a)/H0 accelerator: interpolation accelerator for functions of a accelerator_achi: interpolation accelerator for functions of chi growth0: growth at z=0, defined to be 1 sigma: ? p_lin: linear matter power spectrum at z=0? p_lnl: nonlinear matter power spectrum at z=0? computed_distances, computed_growth, computed_power, computed_sigma: store status of the computations */ ccl_cosmology * ccl_cosmology_create(ccl_parameters params, ccl_configuration config) { ccl_cosmology * cosmo = malloc(sizeof(ccl_cosmology)); cosmo->params = params; cosmo->config = config; cosmo->data.chi = NULL; cosmo->data.growth = NULL; cosmo->data.fgrowth = NULL; cosmo->data.E = NULL; cosmo->data.accelerator=NULL; cosmo->data.accelerator_achi=NULL; cosmo->data.accelerator_m=NULL; cosmo->data.accelerator_d=NULL; cosmo->data.accelerator_k=NULL; cosmo->data.growth0 = 1.; cosmo->data.achi=NULL; cosmo->data.logsigma = NULL; cosmo->data.dlnsigma_dlogm = NULL; // hmf parameter for interpolation cosmo->data.alphahmf = NULL; cosmo->data.betahmf = NULL; cosmo->data.gammahmf = NULL; cosmo->data.phihmf = NULL; cosmo->data.etahmf = NULL; cosmo->data.p_lin = NULL; cosmo->data.p_nl = NULL; //cosmo->data.nu_pspace_int = NULL; cosmo->computed_distances = false; cosmo->computed_growth = false; cosmo->computed_power = false; cosmo->computed_sigma = false; cosmo->computed_hmfparams = false; cosmo->status = 0; ccl_cosmology_set_status_message(cosmo, ""); return cosmo; } /* ------ ROUTINE: ccl_parameters_fill_initial ------- INPUT: ccl_parameters: params TASK: fill parameters not set by ccl_parameters_create with some initial values DEFINITIONS: Omega_g = (Omega_g*h^2)/h^2 is the radiation parameter; "g" is for photons, as in CLASS T_CMB: CMB temperature in Kelvin Omega_l: Lambda A_s: amplitude of the primordial PS, enforced here to initially set to NaN sigma8: variance in 8 Mpc/h spheres for normalization of matter PS, enforced here to initially set to NaN z_star: recombination redshift */ void ccl_parameters_fill_initial(ccl_parameters * params, int *status) { // Fixed radiation parameters // Omega_g * h**2 is known from T_CMB params->T_CMB = TCMB; // kg / m^3 double rho_g = 4. * STBOLTZ / pow(CLIGHT, 3) * pow(params->T_CMB, 4); // kg / m^3 double rho_crit = RHO_CRITICAL * SOLAR_MASS/pow(MPC_TO_METER, 3) * pow(params->h, 2); params->Omega_g = rho_g/rho_crit; // Get the N_nu_rel from Neff and N_nu_mass params->N_nu_rel = params->Neff - params->N_nu_mass * pow(TNCDM, 4) / pow(4./11.,4./3.); // Temperature of the relativistic neutrinos in K double T_nu= (params->T_CMB) * pow(4./11.,1./3.); // in kg / m^3 double rho_nu_rel = params->N_nu_rel* 7.0/8.0 * 4. * STBOLTZ / pow(CLIGHT, 3) * pow(T_nu, 4); params-> Omega_n_rel = rho_nu_rel/rho_crit; // If non-relativistic neutrinos are present, calculate the phase_space integral. if((params->N_nu_mass)>0) { // Pass NULL for the accelerator here because we don't have our cosmology object defined yet. params->Omega_n_mass = ccl_Omeganuh2(1.0, params->N_nu_mass, params->mnu, params->T_CMB, NULL, status) / ((params->h)*(params->h)); ccl_check_status_nocosmo(status); } else{ params->Omega_n_mass = 0.; } params->Omega_m = params->Omega_b + params-> Omega_c; params->Omega_l = 1.0 - params->Omega_m - params->Omega_g - params->Omega_n_rel -params->Omega_n_mass- params->Omega_k; // Initially undetermined parameters - set to nan to trigger // problems if they are mistakenly used. if (isfinite(params->A_s)) {params->sigma8 = NAN;} if (isfinite(params->sigma8)) {params->A_s = NAN;} params->z_star = NAN; if(fabs(params->Omega_k)<1E-6) params->k_sign=0; else if(params->Omega_k>0) params->k_sign=-1; else params->k_sign=1; params->sqrtk=sqrt(fabs(params->Omega_k))*params->h/CLIGHT_HMPC; } /* ------ ROUTINE: ccl_parameters_create ------- INPUT: numbers for the basic cosmological parameters needed by CCL TASK: fill params with some initial values provided by the user DEFINITIONS: Omega_c: cold dark matter Omega_b: baryons Omega_m: matter Omega_k: curvature little omega_x means Omega_x*h^2 Neff : Effective number of neutrino speces mnu : Pointer to either sum of neutrino masses or list of three masses. mnu_type : how the neutrino mass(es) should be treated w0: Dark energy eq of state parameter wa: Dark energy eq of state parameter, time variation H0: Hubble's constant in km/s/Mpc. h: Hubble's constant divided by (100 km/s/Mpc). A_s: amplitude of the primordial PS n_s: index of the primordial PS */ ccl_parameters ccl_parameters_create( double Omega_c, double Omega_b, double Omega_k, double Neff, double* mnu, ccl_mnu_convention mnu_type, double w0, double wa, double h, double norm_pk, double n_s, double bcm_log10Mc, double bcm_etab, double bcm_ks, int nz_mgrowth, double *zarr_mgrowth, double *dfarr_mgrowth, int *status) { #ifndef USE_GSL_ERROR gsl_set_error_handler_off (); #endif ccl_parameters params; // Initialize params params.mnu = NULL; params.z_mgrowth=NULL; params.df_mgrowth=NULL; params.sigma8 = NAN; params.A_s = NAN; params.Omega_c = Omega_c; params.Omega_b = Omega_b; params.Omega_k = Omega_k; params.Neff = Neff; // Set the sum of neutrino masses params.sum_nu_masses = *mnu; double mnusum = *mnu; double *mnu_in = NULL; /* Check whether ccl_splines and ccl_gsl exist. If either is not set yet, load parameters from the config file. */ if(ccl_splines==NULL || ccl_gsl==NULL) { ccl_cosmology_read_config(); } // Decide how to split sum of neutrino masses between 3 neutrinos. We use // a Newton's rule numerical solution (thanks M. Jarvis). if (mnu_type==ccl_mnu_sum){ // Normal hierarchy mnu_in = malloc(3*sizeof(double)); // Check if the sum is zero if (*mnu<1e-15){ mnu_in[0] = 0.; mnu_in[1] = 0.; mnu_in[2] = 0.; } else{ mnu_in[0] = 0.; // This is a starting guess. double sum_check; // Check that sum is consistent mnu_in[1] = sqrt(DELTAM12_sq); mnu_in[2] = sqrt(DELTAM13_sq_pos); sum_check = mnu_in[0] + mnu_in[1] + mnu_in[2]; if (ccl_mnu_sum < sum_check){ *status = CCL_ERROR_MNU_UNPHYSICAL; } double dsdm1; // This is the Newton's method while (fabs(*mnu - sum_check) > 1e-15){ dsdm1 = 1. + mnu_in[0] / mnu_in[1] + mnu_in[0] / mnu_in[2]; mnu_in[0] = mnu_in[0] - (sum_check - *mnu) / dsdm1; mnu_in[1] = sqrt(mnu_in[0]*mnu_in[0] + DELTAM12_sq); mnu_in[2] = sqrt(mnu_in[0]*mnu_in[0] + DELTAM13_sq_pos); sum_check = mnu_in[0] + mnu_in[1] + mnu_in[2]; } } } else if (mnu_type==ccl_mnu_sum_inverted){ // Inverted hierarchy mnu_in = malloc(3*sizeof(double)); // Check if the sum is zero if (*mnu<1e-15){ mnu_in[0] = 0.; mnu_in[1] = 0.; mnu_in[2] = 0.; } else{ mnu_in[0] = 0.; // This is a starting guess. double sum_check; // Check that sum is consistent mnu_in[1] = sqrt(-1.* DELTAM13_sq_neg - DELTAM12_sq); mnu_in[2] = sqrt(-1.* DELTAM13_sq_neg); sum_check = mnu_in[0] + mnu_in[1] + mnu_in[2]; if (ccl_mnu_sum < sum_check){ *status = CCL_ERROR_MNU_UNPHYSICAL; } double dsdm1; // This is the Newton's method while (fabs(*mnu- sum_check) > 1e-15){ dsdm1 = 1. + (mnu_in[0] / mnu_in[1]) + (mnu_in[0] / mnu_in[2]); mnu_in[0] = mnu_in[0] - (sum_check - *mnu) / dsdm1; mnu_in[1] = sqrt(mnu_in[0]*mnu_in[0] + DELTAM12_sq); mnu_in[2] = sqrt(mnu_in[0]*mnu_in[0] + DELTAM13_sq_neg); sum_check = mnu_in[0] + mnu_in[1] + mnu_in[2]; } } } else if (mnu_type==ccl_mnu_sum_equal){ // Split the sum of masses equally mnu_in = malloc(3*sizeof(double)); mnu_in[0] = params.sum_nu_masses / 3.; mnu_in[1] = params.sum_nu_masses / 3.; mnu_in[2] = params.sum_nu_masses / 3.; } else if (mnu_type == ccl_mnu_list){ // A list of neutrino masses was already passed in params.sum_nu_masses = mnu[0] + mnu[1] + mnu[2]; mnu_in = malloc(3*sizeof(double)); for(int i=0; i<3; i++) mnu_in[i] = mnu[i]; } else { *status = CCL_ERROR_NOT_IMPLEMENTED; } // Check for errors in the neutrino set up (e.g. unphysical mnu) ccl_check_status_nocosmo(status); // Check which of the neutrino species are non-relativistic today int N_nu_mass = 0; for(int i = 0; i<3; i=i+1){ if (mnu_in[i] > 0.00017){ // Limit taken from Lesgourges et al. 2012 N_nu_mass = N_nu_mass + 1; } } params.N_nu_mass = N_nu_mass; // Fill the array of massive neutrinos if (N_nu_mass>0){ params.mnu = malloc(params.N_nu_mass*sizeof(double)); int relativistic[3] = {0, 0, 0}; for (int i = 0; i < N_nu_mass; i = i + 1){ for (int j = 0; j<3; j = j +1){ if ((mnu_in[j]>0.00017) && (relativistic[j]==0)){ relativistic[j]=1; params.mnu[i] = mnu_in[j]; break; } } // end loop over neutrinos } // end loop over massive neutrinos } else{ params.mnu = malloc(sizeof(double)); params.mnu[0] = 0.; } // Free mnu_in if (mnu_in != NULL) free(mnu_in); // Dark Energy params.w0 = w0; params.wa = wa; // Hubble parameters params.h = h; params.H0 = h*100; // Primordial power spectra if(norm_pk<1E-5) params.A_s=norm_pk; else params.sigma8=norm_pk; params.n_s = n_s; //Baryonic params if(bcm_log10Mc<0) params.bcm_log10Mc=log10(1.2e14); else params.bcm_log10Mc=bcm_log10Mc; if(bcm_etab<0) params.bcm_etab=0.5; else params.bcm_etab=bcm_etab; if(bcm_ks<0) params.bcm_ks=55.0; else params.bcm_ks=bcm_ks; // Set remaining standard and easily derived parameters ccl_parameters_fill_initial(&params, status); //Trigger modified growth function if nz>0 if(nz_mgrowth>0) { params.has_mgrowth=true; params.nz_mgrowth=nz_mgrowth; params.z_mgrowth=malloc(params.nz_mgrowth*sizeof(double)); params.df_mgrowth=malloc(params.nz_mgrowth*sizeof(double)); memcpy(params.z_mgrowth,zarr_mgrowth,params.nz_mgrowth*sizeof(double)); memcpy(params.df_mgrowth,dfarr_mgrowth,params.nz_mgrowth*sizeof(double)); } else { params.has_mgrowth=false; params.nz_mgrowth=0; params.z_mgrowth=NULL; params.df_mgrowth=NULL; } return params; } /* ------- ROUTINE: ccl_parameters_create_flat_lcdm -------- INPUT: some cosmological parameters needed to create a flat LCDM model TASK: call ccl_parameters_create to produce an LCDM model */ ccl_parameters ccl_parameters_create_flat_lcdm(double Omega_c, double Omega_b, double h, double norm_pk, double n_s, int *status) { double Omega_k = 0.0; double Neff = 3.046; double w0 = -1.0; double wa = 0.0; double *mnu; double mnuval = 0.; // a pointer to the variable is not kept past the lifetime of this function mnu = &mnuval; ccl_mnu_convention mnu_type = ccl_mnu_sum; ccl_parameters params = ccl_parameters_create(Omega_c, Omega_b, Omega_k, Neff, mnu, mnu_type, w0, wa, h, norm_pk, n_s, -1, -1, -1, -1, NULL, NULL, status); return params; } /** * Write a cosmology parameters object to a file in yaml format. * @param cosmo Cosmological parameters * @param f FILE* pointer opened for reading * @return void */ void ccl_parameters_write_yaml(ccl_parameters * params, const char * filename, int *status) { FILE * f = fopen(filename, "w"); if (!f){ *status = CCL_ERROR_FILE_WRITE; return; } #define WRITE_DOUBLE(name) fprintf(f, #name ": %le\n",params->name) #define WRITE_INT(name) fprintf(f, #name ": %d\n",params->name) // Densities: CDM, baryons, total matter, curvature WRITE_DOUBLE(Omega_c); WRITE_DOUBLE(Omega_b); WRITE_DOUBLE(Omega_m); WRITE_DOUBLE(Omega_k); WRITE_INT(k_sign); // Dark Energy WRITE_DOUBLE(w0); WRITE_DOUBLE(wa); // Hubble parameters WRITE_DOUBLE(H0); WRITE_DOUBLE(h); // Neutrino properties WRITE_DOUBLE(Neff); WRITE_INT(N_nu_mass); WRITE_DOUBLE(N_nu_rel); if (params->N_nu_mass>0){ fprintf(f, "mnu: ["); for (int i=0; i<params->N_nu_mass; i++){ fprintf(f, "%le, ", params->mnu[i]); } fprintf(f, "]\n"); } WRITE_DOUBLE(sum_nu_masses); WRITE_DOUBLE(Omega_n_mass); WRITE_DOUBLE(Omega_n_rel); // Primordial power spectra WRITE_DOUBLE(A_s); WRITE_DOUBLE(n_s); // Radiation parameters WRITE_DOUBLE(Omega_g); WRITE_DOUBLE(T_CMB); // BCM baryonic model parameters WRITE_DOUBLE(bcm_log10Mc); WRITE_DOUBLE(bcm_etab); WRITE_DOUBLE(bcm_ks); // Derived parameters WRITE_DOUBLE(sigma8); WRITE_DOUBLE(Omega_l); WRITE_DOUBLE(z_star); WRITE_INT(has_mgrowth); WRITE_INT(nz_mgrowth); if (params->has_mgrowth){ fprintf(f, "z_mgrowth: ["); for (int i=0; i<params->nz_mgrowth; i++){ fprintf(f, "%le, ", params->z_mgrowth[i]); } fprintf(f, "]\n"); fprintf(f, "df_mgrowth: ["); for (int i=0; i<params->nz_mgrowth; i++){ fprintf(f, "%le, ", params->df_mgrowth[i]); } fprintf(f, "]\n"); } #undef WRITE_DOUBLE #undef WRITE_INT fclose(f); } /** * Write a cosmology parameters object to a file in yaml format. * @param cosmo Cosmological parameters * @param f FILE* pointer opened for reading * @return void */ ccl_parameters ccl_parameters_read_yaml(const char * filename, int *status) { FILE * f = fopen(filename, "r"); if (!f){ *status = CCL_ERROR_FILE_READ; ccl_parameters bad_params; ccl_raise_exception(CCL_ERROR_FILE_READ, "ccl_core.c: Failed to read parameters from file."); return bad_params; } #define READ_DOUBLE(name) double name; *status |= (0==fscanf(f, #name ": %le\n",&name)); #define READ_INT(name) int name; *status |= (0==fscanf(f, #name ": %d\n",&name)) // Densities: CDM, baryons, total matter, curvature READ_DOUBLE(Omega_c); READ_DOUBLE(Omega_b); READ_DOUBLE(Omega_m); READ_DOUBLE(Omega_k); READ_INT(k_sign); // Dark Energy READ_DOUBLE(w0); READ_DOUBLE(wa); // Hubble parameters READ_DOUBLE(H0); READ_DOUBLE(h); // Neutrino properties READ_DOUBLE(Neff); READ_INT(N_nu_mass); READ_DOUBLE(N_nu_rel); double mnu[3] = {0.0, 0.0, 0.0}; if (N_nu_mass>0){ *status |= (0==fscanf(f, "mnu: [")); for (int i=0; i<N_nu_mass; i++){ *status |= (0==fscanf(f, "%le, ", mnu+i)); } *status |= (0==fscanf(f, "]\n")); } READ_DOUBLE(sum_nu_masses); READ_DOUBLE(Omega_n_mass); READ_DOUBLE(Omega_n_rel); // Primordial power spectra READ_DOUBLE(A_s); READ_DOUBLE(n_s); // Radiation parameters READ_DOUBLE(Omega_g); READ_DOUBLE(T_CMB); // BCM baryonic model parameters READ_DOUBLE(bcm_log10Mc); READ_DOUBLE(bcm_etab); READ_DOUBLE(bcm_ks); // Derived parameters READ_DOUBLE(sigma8); READ_DOUBLE(Omega_l); READ_DOUBLE(z_star); READ_INT(has_mgrowth); READ_INT(nz_mgrowth); double *z_mgrowth; double *df_mgrowth; if (has_mgrowth){ z_mgrowth = malloc(nz_mgrowth*sizeof(double)); df_mgrowth = malloc(nz_mgrowth*sizeof(double)); *status |= (0==fscanf(f, "z_mgrowth: [")); for (int i=0; i<nz_mgrowth; i++){ *status |= (0==fscanf(f, "%le, ", z_mgrowth+i)); } *status |= (0==fscanf(f, "]\n")); *status |= (0==fscanf(f, "df_mgrowth: [")); for (int i=0; i<nz_mgrowth; i++){ *status |= (0==fscanf(f, "%le, ", df_mgrowth+i)); } *status |= (0==fscanf(f, "]\n")); } else{ z_mgrowth = NULL; df_mgrowth = NULL; } #undef READ_DOUBLE #undef READ_INT fclose(f); if (status){ char msg[256]; snprintf(msg, 256, "ccl_core.c: Structure of YAML file incorrect: %s", filename); ccl_raise_exception(*status, msg); } double norm_pk; if (isnan(A_s)){ norm_pk = sigma8; } else{ norm_pk = A_s; } ccl_parameters params = ccl_parameters_create( Omega_c, Omega_b, Omega_k, Neff, mnu, ccl_mnu_list, w0, wa, h, norm_pk, n_s, bcm_log10Mc, bcm_etab, bcm_ks, nz_mgrowth, z_mgrowth, df_mgrowth, status); if(z_mgrowth) free(z_mgrowth); if (df_mgrowth) free(df_mgrowth); return params; } /* ------- ROUTINE: ccl_data_free -------- INPUT: ccl_data TASK: free the input data */ void ccl_data_free(ccl_data * data) { //We cannot assume that all of these have been allocated //TODO: it would actually make more sense to do this within ccl_cosmology_free, //where we could make use of the flags "computed_distances" etc. to figure out //what to free up gsl_spline_free(data->chi); gsl_spline_free(data->growth); gsl_spline_free(data->fgrowth); gsl_interp_accel_free(data->accelerator); gsl_interp_accel_free(data->accelerator_achi); gsl_spline_free(data->E); gsl_spline_free(data->achi); gsl_spline_free(data->logsigma); gsl_spline_free(data->dlnsigma_dlogm); gsl_spline2d_free(data->p_lin); gsl_spline2d_free(data->p_nl); gsl_spline_free(data->alphahmf); gsl_spline_free(data->betahmf); gsl_spline_free(data->gammahmf); gsl_spline_free(data->phihmf); gsl_spline_free(data->etahmf); gsl_interp_accel_free(data->accelerator_d); gsl_interp_accel_free(data->accelerator_m); gsl_interp_accel_free(data->accelerator_k); } /* ------- ROUTINE: ccl_cosmology_set_status_message -------- INPUT: ccl_cosmology struct, status_string TASK: set the status message safely. */ void ccl_cosmology_set_status_message(ccl_cosmology * cosmo, const char * message, ...) { const int trunc = 480; /* must be < 500 - 4 */ va_list va; va_start(va, message); vsnprintf(cosmo->status_message, trunc, message, va); va_end(va); /* if truncation happens, message[trunc - 1] is not NULL, ... will show up. */ strcpy(&cosmo->status_message[trunc], "..."); } /* ------- ROUTINE: ccl_parameters_free -------- INPUT: ccl_parameters struct TASK: free allocated quantities in the parameters struct */ void ccl_parameters_free(ccl_parameters * params) { if (params->mnu != NULL){ free(params->mnu); params->mnu = NULL; } if (params->z_mgrowth != NULL){ free(params->z_mgrowth); params->z_mgrowth = NULL; } if (params->df_mgrowth != NULL){ free(params->df_mgrowth); params->df_mgrowth = NULL; } } /* ------- ROUTINE: ccl_cosmology_free -------- INPUT: ccl_cosmology struct TASK: free the input data and the cosmology struct */ void ccl_cosmology_free(ccl_cosmology * cosmo) { ccl_data_free(&cosmo->data); free(cosmo); }
{ "alphanum_fraction": 0.6606228752, "avg_line_length": 30.8697225573, "ext": "c", "hexsha": "65ea1938aef1bf4adab4b63bc82476e12ec1552b", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "1cdc4ecb8ae6fb23806540b39799cc3317473e71", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "Russell-Jones-OxPhys/CCL", "max_forks_repo_path": "src/ccl_core.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "1cdc4ecb8ae6fb23806540b39799cc3317473e71", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "Russell-Jones-OxPhys/CCL", "max_issues_repo_path": "src/ccl_core.c", "max_line_length": 136, "max_stars_count": null, "max_stars_repo_head_hexsha": "1cdc4ecb8ae6fb23806540b39799cc3317473e71", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "Russell-Jones-OxPhys/CCL", "max_stars_repo_path": "src/ccl_core.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 7845, "size": 25591 }
/* spmatrix.c * * Copyright (C) 2012 Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_spmatrix.h> #include "avl.c" static int compare_triplet(const void *pa, const void *pb, void *param); static void *avl_spmalloc (size_t size, void *param); static void avl_spfree (void *block, void *param); static struct libavl_allocator avl_allocator_spmatrix = { avl_spmalloc, avl_spfree }; /* gsl_spmatrix_alloc() Allocate a sparse matrix in triplet representation Inputs: n1 - number of rows n2 - number of columns Notes: if (n1,n2) are not known at allocation time, they can each be set to 1, and they will be expanded as elements are added to the matrix */ gsl_spmatrix * gsl_spmatrix_alloc(const size_t n1, const size_t n2) { const double density = 0.1; /* estimate */ size_t nzmax = (size_t) floor(n1 * n2 * density); if (nzmax == 0) nzmax = 10; return gsl_spmatrix_alloc_nzmax(n1, n2, nzmax, GSL_SPMATRIX_TRIPLET); } /* gsl_spmatrix_alloc() */ /* gsl_spmatrix_alloc_nzmax() Allocate a sparse matrix with given nzmax Inputs: n1 - number of rows n2 - number of columns nzmax - maximum number of matrix elements sptype - type of matrix (triplet, CCS, CRS) Notes: if (n1,n2) are not known at allocation time, they can each be set to 1, and they will be expanded as elements are added to the matrix */ gsl_spmatrix * gsl_spmatrix_alloc_nzmax(const size_t n1, const size_t n2, const size_t nzmax, const size_t sptype) { gsl_spmatrix *m; if (n1 == 0) { GSL_ERROR_NULL ("matrix dimension n1 must be positive integer", GSL_EINVAL); } else if (n2 == 0) { GSL_ERROR_NULL ("matrix dimension n2 must be positive integer", GSL_EINVAL); } m = calloc(1, sizeof(gsl_spmatrix)); if (!m) { GSL_ERROR_NULL("failed to allocate space for spmatrix struct", GSL_ENOMEM); } m->size1 = n1; m->size2 = n2; m->nz = 0; m->nzmax = GSL_MAX(nzmax, 1); m->sptype = sptype; m->i = malloc(m->nzmax * sizeof(size_t)); if (!m->i) { gsl_spmatrix_free(m); GSL_ERROR_NULL("failed to allocate space for row indices", GSL_ENOMEM); } if (sptype == GSL_SPMATRIX_TRIPLET) { m->tree_data = malloc(sizeof(gsl_spmatrix_tree)); if (!m->tree_data) { gsl_spmatrix_free(m); GSL_ERROR_NULL("failed to allocate space for AVL tree struct", GSL_ENOMEM); } m->tree_data->n = 0; /* allocate tree data structure */ m->tree_data->tree = avl_create(compare_triplet, (void *) m, &avl_allocator_spmatrix); if (!m->tree_data->tree) { gsl_spmatrix_free(m); GSL_ERROR_NULL("failed to allocate space for AVL tree", GSL_ENOMEM); } /* preallocate nzmax tree nodes */ m->tree_data->node_array = malloc(m->nzmax * sizeof(struct avl_node)); if (!m->tree_data->node_array) { gsl_spmatrix_free(m); GSL_ERROR_NULL("failed to allocate space for AVL tree nodes", GSL_ENOMEM); } m->p = malloc(m->nzmax * sizeof(size_t)); if (!m->p) { gsl_spmatrix_free(m); GSL_ERROR_NULL("failed to allocate space for column indices", GSL_ENOMEM); } } else if (sptype == GSL_SPMATRIX_CCS) { m->p = malloc((n2 + 1) * sizeof(size_t)); m->work = malloc(GSL_MAX(n1, n2) * GSL_MAX(sizeof(size_t), sizeof(double))); if (!m->p || !m->work) { gsl_spmatrix_free(m); GSL_ERROR_NULL("failed to allocate space for column pointers", GSL_ENOMEM); } } else if (sptype == GSL_SPMATRIX_CRS) { m->p = malloc((n1 + 1) * sizeof(size_t)); m->work = malloc(GSL_MAX(n1, n2) * GSL_MAX(sizeof(size_t), sizeof(double))); if (!m->p || !m->work) { gsl_spmatrix_free(m); GSL_ERROR_NULL("failed to allocate space for row pointers", GSL_ENOMEM); } } m->data = malloc(m->nzmax * sizeof(double)); if (!m->data) { gsl_spmatrix_free(m); GSL_ERROR_NULL("failed to allocate space for data", GSL_ENOMEM); } return m; } /* gsl_spmatrix_alloc_nzmax() */ /* gsl_spmatrix_free() Free sparse matrix object */ void gsl_spmatrix_free(gsl_spmatrix *m) { if (m->i) free(m->i); if (m->p) free(m->p); if (m->data) free(m->data); if (m->work) free(m->work); if (m->tree_data) { if (m->tree_data->tree) avl_destroy(m->tree_data->tree, NULL); if (m->tree_data->node_array) free(m->tree_data->node_array); free(m->tree_data); } free(m); } /* gsl_spmatrix_free() */ /* gsl_spmatrix_realloc() As elements are added to the sparse matrix, its possible that they will exceed the previously specified nzmax - reallocate the matrix with a new nzmax */ int gsl_spmatrix_realloc(const size_t nzmax, gsl_spmatrix *m) { int s = GSL_SUCCESS; void *ptr; if (nzmax < m->nz) { GSL_ERROR("new nzmax is less than current nz", GSL_EINVAL); } ptr = realloc(m->i, nzmax * sizeof(size_t)); if (!ptr) { GSL_ERROR("failed to allocate space for row indices", GSL_ENOMEM); } m->i = (size_t *) ptr; if (GSL_SPMATRIX_ISTRIPLET(m)) { ptr = realloc(m->p, nzmax * sizeof(size_t)); if (!ptr) { GSL_ERROR("failed to allocate space for column indices", GSL_ENOMEM); } m->p = (size_t *) ptr; } ptr = realloc(m->data, nzmax * sizeof(double)); if (!ptr) { GSL_ERROR("failed to allocate space for data", GSL_ENOMEM); } m->data = (double *) ptr; /* rebuild binary tree */ if (GSL_SPMATRIX_ISTRIPLET(m)) { size_t n; /* reset tree to empty state, but don't free root tree ptr */ avl_empty(m->tree_data->tree, NULL); m->tree_data->n = 0; ptr = realloc(m->tree_data->node_array, nzmax * sizeof(struct avl_node)); if (!ptr) { GSL_ERROR("failed to allocate space for AVL tree nodes", GSL_ENOMEM); } m->tree_data->node_array = ptr; /* * need to reinsert all tree elements since the m->data addresses * have changed */ for (n = 0; n < m->nz; ++n) { ptr = avl_insert(m->tree_data->tree, &m->data[n]); if (ptr != NULL) { GSL_ERROR("detected duplicate entry", GSL_EINVAL); } } } /* update to new nzmax */ m->nzmax = nzmax; return s; } /* gsl_spmatrix_realloc() */ int gsl_spmatrix_set_zero(gsl_spmatrix *m) { m->nz = 0; if (GSL_SPMATRIX_ISTRIPLET(m)) { /* reset tree to empty state and node index pointer to 0 */ avl_empty(m->tree_data->tree, NULL); m->tree_data->n = 0; } return GSL_SUCCESS; } /* gsl_spmatrix_set_zero() */ size_t gsl_spmatrix_nnz(const gsl_spmatrix *m) { return m->nz; } /* gsl_spmatrix_nnz() */ /* gsl_spmatrix_compare_idx() Comparison function for searching binary tree in triplet representation. To detect duplicate elements in the tree, we want to determine if there already exists an entry for (i,j) in the tree. Since the actual tree node stores only the data elements data[n], we will do pointer arithmetic to get from the given data[n] to the row/column indices i[n] and j[n]. This compare function will sort the tree first by row i, and for equal rows, it will then sort by column j Inputs: ia - row index of element a ja - column index of element a ib - row index of element b jb - column index of element b Return: -1 if pa < pb: (ia,ja) < (ib,jb) +1 if pa > pb: (ia,ja) > (ib,jb) 0 if pa = pb: (ia,ja) == (ib,jb) */ int gsl_spmatrix_compare_idx(const size_t ia, const size_t ja, const size_t ib, const size_t jb) { if (ia < ib) return -1; else if (ia > ib) return 1; else { /* row indices are equal, sort by column index */ if (ja < jb) return -1; else if (ja > jb) return 1; else return 0; /* row and column indices are equal */ } } /* gsl_spmatrix_tree_rebuild() When reading a triplet matrix from disk, or when copying a triplet matrix, it is necessary to rebuild the binary tree for element searches. Inputs: m - triplet matrix */ int gsl_spmatrix_tree_rebuild(gsl_spmatrix * m) { if (!GSL_SPMATRIX_ISTRIPLET(m)) { GSL_ERROR("m must be in triplet format", GSL_EINVAL); } else { size_t n; /* reset tree to empty state, but don't free root tree ptr */ avl_empty(m->tree_data->tree, NULL); m->tree_data->n = 0; /* insert all tree elements */ for (n = 0; n < m->nz; ++n) { void *ptr = avl_insert(m->tree_data->tree, &m->data[n]); if (ptr != NULL) { GSL_ERROR("detected duplicate entry", GSL_EINVAL); } } return GSL_SUCCESS; } } /* compare_triplet() Comparison function for searching binary tree in triplet representation. To detect duplicate elements in the tree, we want to determine if there already exists an entry for (i,j) in the tree. Since the actual tree node stores only the data elements data[n], we will do pointer arithmetic to get from the given data[n] to the row/column indices i[n] and j[n]. This compare function will sort the tree first by row i, and for equal rows, it will then sort by column j Inputs: pa - element 1 for comparison (double *) pb - element 2 for comparison (double *) param - parameter (gsl_spmatrix) Return: -1 if pa < pb: (ia,ja) < (ib,jb) +1 if pa > pb: (ia,ja) > (ib,jb) 0 if pa = pb: (ia,ja) == (ib,jb) */ static int compare_triplet(const void *pa, const void *pb, void *param) { gsl_spmatrix *m = (gsl_spmatrix *) param; /* pointer arithmetic to find indices in data array */ const size_t idxa = (const double *) pa - m->data; const size_t idxb = (const double *) pb - m->data; return gsl_spmatrix_compare_idx(m->i[idxa], m->p[idxa], m->i[idxb], m->p[idxb]); } /* compare_triplet() */ static void * avl_spmalloc (size_t size, void *param) { gsl_spmatrix *m = (gsl_spmatrix *) param; if (size != sizeof(struct avl_node)) { GSL_ERROR_NULL("attemping to allocate incorrect node size", GSL_EBADLEN); } /* * return the next available avl_node slot; index * m->tree_data->n keeps track of next open slot */ if (m->tree_data->n < m->nzmax) { /* cast to char* for pointer arithmetic */ unsigned char *node_ptr = (unsigned char *) m->tree_data->node_array; /* offset in bytes for next node slot */ size_t offset = (m->tree_data->n)++ * sizeof(struct avl_node); return node_ptr + offset; } else { /* * we should never get here - gsl_spmatrix_realloc() should * be called before exceeding nzmax nodes */ GSL_ERROR_NULL("attemping to allocate tree node past nzmax", GSL_EINVAL); } } static void avl_spfree (void *block, void *param) { (void)block; (void)param; /* * do nothing - instead of allocating/freeing individual nodes, * we malloc and free nzmax nodes at a time */ }
{ "alphanum_fraction": 0.6077468191, "avg_line_length": 25.3428571429, "ext": "c", "hexsha": "02ecaa9579764cae2b5aa7e53ec11ec9512060d9", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/spmatrix/spmatrix.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/spmatrix/spmatrix.c", "max_line_length": 81, "max_stars_count": 1, "max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_stars_repo_path": "gsl-2.4/spmatrix/spmatrix.c", "max_stars_repo_stars_event_max_datetime": "2021-01-13T05:01:59.000Z", "max_stars_repo_stars_event_min_datetime": "2021-01-13T05:01:59.000Z", "num_tokens": 3425, "size": 12418 }
#include <math.h> #include <stdio.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> int main () { size_t i,j; gsl_matrix *m = gsl_matrix_alloc (10, 10); for (i = 0; i < 10; i++) for (j = 0; j < 10; j++) gsl_matrix_set (m, i, j, sin (i) + cos (j)); for (j = 0; j < 10; j++) { gsl_vector_view column = gsl_matrix_column (m, j); double d; d = gsl_blas_dnrm2 (&column.vector); printf ("matrix column %d, norm = %g\n", j, d); } gsl_matrix_free (m); }
{ "alphanum_fraction": 0.546875, "avg_line_length": 17.6551724138, "ext": "c", "hexsha": "d4a8473732ac26c3027d5136c7ce3c439a52ac05", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/matrix/demo.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/matrix/demo.c", "max_line_length": 56, "max_stars_count": 1, "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/matrix/demo.c", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "num_tokens": 181, "size": 512 }
/* linalg/trimult_complex.c * * Copyright (C) 2019 Patrick Alken * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 3, or (at your option) any * later version. * * This source is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * This module contains code to compute L^T L where L is a lower triangular matrix */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_complex_math.h> #include "recurse.h" static int triangular_multherm_L2(CBLAS_UPLO_t Uplo, gsl_matrix_complex * T); static int triangular_multherm_L3(CBLAS_UPLO_t Uplo, gsl_matrix_complex * T); static int triangular_mult_L2(CBLAS_UPLO_t Uplo, gsl_matrix_complex * LU); static int triangular_mult_L3(CBLAS_UPLO_t Uplo, gsl_matrix_complex * A); static void complex_conj_vector(gsl_vector_complex * v); int gsl_linalg_complex_tri_LHL(gsl_matrix_complex * L) { return triangular_multherm_L3(CblasLower, L); } int gsl_linalg_complex_tri_UL(gsl_matrix_complex * LU) { return triangular_mult_L3(CblasUpper, LU); } /* triangular_multherm_L2() Compute L^H L or U U^H Inputs: Uplo - CblasUpper or CblasLower T - on output the upper (or lower) part of T is replaced by L^H L or U U^H Return: success/error Notes: 1) Based on LAPACK routine ZLAUU2 using Level 2 BLAS */ static int triangular_multherm_L2(CBLAS_UPLO_t Uplo, gsl_matrix_complex * T) { const size_t N = T->size1; if (N != T->size2) { GSL_ERROR ("matrix must be square", GSL_ENOTSQR); } else { size_t i; if (Uplo == CblasUpper) { } else { for (i = 0; i < N; ++i) { gsl_complex * Tii = gsl_matrix_complex_ptr(T, i, i); gsl_complex z0 = *Tii; if (i < N - 1) { gsl_vector_complex_view v = gsl_matrix_complex_subcolumn(T, i, i + 1, N - i - 1); double norm = gsl_blas_dznrm2(&v.vector); GSL_REAL(*Tii) = gsl_complex_abs2(*Tii) + norm * norm; if (i > 0) { gsl_vector_complex_view w = gsl_matrix_complex_subrow(T, i, 0, i); gsl_matrix_complex_view m = gsl_matrix_complex_submatrix(T, i + 1, 0, N - i - 1, i); complex_conj_vector(&w.vector); gsl_blas_zgemv(CblasConjTrans, GSL_COMPLEX_ONE, &m.matrix, &v.vector, z0, &w.vector); complex_conj_vector(&w.vector); } } else { gsl_vector_complex_view w = gsl_matrix_complex_row(T, i); gsl_blas_zdscal(GSL_REAL(z0), &w.vector); } GSL_IMAG(*Tii) = 0.0; } } return GSL_SUCCESS; } } /* triangular_multherm_L3() Compute L^H L or U U^H Inputs: Uplo - CblasUpper or CblasLower T - on output the upper (or lower) part of T is replaced by L^H L or U U^H Return: success/error Notes: 1) Based on ReLAPACK using Level 3 BLAS */ static int triangular_multherm_L3(CBLAS_UPLO_t Uplo, gsl_matrix_complex * T) { const size_t N = T->size1; if (N != T->size2) { GSL_ERROR ("matrix must be square", GSL_ENOTSQR); } else if (N <= CROSSOVER_TRIMULT) { /* use Level 2 algorithm */ return triangular_multherm_L2(Uplo, T); } else { /* * partition matrix: * * T11 T12 * T21 T22 * * where T11 is N1-by-N1 */ int status; const size_t N1 = GSL_LINALG_SPLIT_COMPLEX(N); const size_t N2 = N - N1; gsl_matrix_complex_view T11 = gsl_matrix_complex_submatrix(T, 0, 0, N1, N1); gsl_matrix_complex_view T12 = gsl_matrix_complex_submatrix(T, 0, N1, N1, N2); gsl_matrix_complex_view T21 = gsl_matrix_complex_submatrix(T, N1, 0, N2, N1); gsl_matrix_complex_view T22 = gsl_matrix_complex_submatrix(T, N1, N1, N2, N2); /* recursion on T11 */ status = triangular_multherm_L3(Uplo, &T11.matrix); if (status) return status; if (Uplo == CblasLower) { /* T11 += T21^T T21 */ gsl_blas_zherk(Uplo, CblasConjTrans, 1.0, &T21.matrix, 1.0, &T11.matrix); /* T21 = T22^T * T21 */ gsl_blas_ztrmm(CblasLeft, Uplo, CblasConjTrans, CblasNonUnit, GSL_COMPLEX_ONE, &T22.matrix, &T21.matrix); } else { /* T11 += T12 T12^T */ gsl_blas_zherk(Uplo, CblasNoTrans, 1.0, &T12.matrix, 1.0, &T11.matrix); /* T12 = T12 * T22^T */ gsl_blas_ztrmm(CblasRight, Uplo, CblasConjTrans, CblasNonUnit, GSL_COMPLEX_ONE, &T22.matrix, &T12.matrix); } /* recursion on T22 */ status = triangular_multherm_L3(Uplo, &T22.matrix); if (status) return status; return GSL_SUCCESS; } } /******************************************** * INTERNAL ROUTINES * ********************************************/ /* triangular_mult_L2() Compute U L or L U Inputs: Uplo - CblasUpper or CblasLower (first triangular factor) LU - on input, matrix in LU form; on output U*L or L*U Return: success/error */ static int triangular_mult_L2(CBLAS_UPLO_t Uplo, gsl_matrix_complex * LU) { const size_t N = LU->size1; if (N != LU->size2) { GSL_ERROR ("matrix must be square", GSL_ENOTSQR); } else { size_t i; /* quick return */ if (N == 1) return GSL_SUCCESS; if (Uplo == CblasUpper) { /* compute U*L and store in LU */ for (i = 0; i < N; ++i) { gsl_complex * Aii = gsl_matrix_complex_ptr(LU, i, i); gsl_complex Uii = *Aii; if (i < N - 1) { gsl_vector_complex_view lb = gsl_matrix_complex_subcolumn(LU, i, i + 1, N - i - 1); gsl_vector_complex_view ur = gsl_matrix_complex_subrow(LU, i, i + 1, N - i - 1); gsl_complex dot; gsl_blas_zdotu(&lb.vector, &ur.vector, &dot); *Aii = gsl_complex_add(*Aii, dot); if (i > 0) { gsl_matrix_complex_view U_TR = gsl_matrix_complex_submatrix(LU, 0, i + 1, i, N - i - 1); gsl_matrix_complex_view L_BL = gsl_matrix_complex_submatrix(LU, i + 1, 0, N - i - 1, i); gsl_vector_complex_view ut = gsl_matrix_complex_subcolumn(LU, i, 0, i); gsl_vector_complex_view ll = gsl_matrix_complex_subrow(LU, i, 0, i); gsl_blas_zgemv(CblasTrans, GSL_COMPLEX_ONE, &L_BL.matrix, &ur.vector, Uii, &ll.vector); gsl_blas_zgemv(CblasNoTrans, GSL_COMPLEX_ONE, &U_TR.matrix, &lb.vector, GSL_COMPLEX_ONE, &ut.vector); } } else { gsl_vector_complex_view v = gsl_matrix_complex_subrow(LU, i, 0, i); gsl_blas_zscal(Uii, &v.vector); } } } else { } return GSL_SUCCESS; } } /* triangular_mult_L3() Compute U L or L U Inputs: Uplo - CblasUpper or CblasLower (for the first triangular factor) A - on input, matrix in LU format; on output, U L or L U Return: success/error */ static int triangular_mult_L3(CBLAS_UPLO_t Uplo, gsl_matrix_complex * A) { const size_t N = A->size1; if (N != A->size2) { GSL_ERROR ("matrix must be square", GSL_ENOTSQR); } else if (N <= CROSSOVER_TRIMULT) { return triangular_mult_L2(Uplo, A); } else { /* partition matrix: * * A11 A12 * A21 A22 * * where A11 is N1-by-N1 */ int status; const size_t N1 = GSL_LINALG_SPLIT_COMPLEX(N); const size_t N2 = N - N1; gsl_matrix_complex_view A11 = gsl_matrix_complex_submatrix(A, 0, 0, N1, N1); gsl_matrix_complex_view A12 = gsl_matrix_complex_submatrix(A, 0, N1, N1, N2); gsl_matrix_complex_view A21 = gsl_matrix_complex_submatrix(A, N1, 0, N2, N1); gsl_matrix_complex_view A22 = gsl_matrix_complex_submatrix(A, N1, N1, N2, N2); /* recursion on A11 */ status = triangular_mult_L3(Uplo, &A11.matrix); if (status) return status; if (Uplo == CblasLower) { } else { /* form U * L */ /* A11 += A12 A21 */ gsl_blas_zgemm(CblasNoTrans, CblasNoTrans, GSL_COMPLEX_ONE, &A12.matrix, &A21.matrix, GSL_COMPLEX_ONE, &A11.matrix); /* A12 = A12 * L22 */ gsl_blas_ztrmm(CblasRight, CblasLower, CblasNoTrans, CblasUnit, GSL_COMPLEX_ONE, &A22.matrix, &A12.matrix); /* A21 = U22 * A21 */ gsl_blas_ztrmm(CblasLeft, CblasUpper, CblasNoTrans, CblasNonUnit, GSL_COMPLEX_ONE, &A22.matrix, &A21.matrix); } /* recursion on A22 */ status = triangular_mult_L3(Uplo, &A22.matrix); if (status) return status; return GSL_SUCCESS; } } static void complex_conj_vector(gsl_vector_complex * v) { size_t i; for (i = 0; i < v->size; ++i) { gsl_complex * vi = gsl_vector_complex_ptr(v, i); GSL_IMAG(*vi) = -GSL_IMAG(*vi); } }
{ "alphanum_fraction": 0.5824557918, "avg_line_length": 28.1173184358, "ext": "c", "hexsha": "7410247e553449bf3a446424514e13ee2e67326b", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_path": "test/lib/gsl-2.6/linalg/trimult_complex.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_path": "gsl-2.6/linalg/trimult_complex.c", "max_line_length": 126, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/linalg/trimult_complex.c", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "num_tokens": 2849, "size": 10066 }
#ifndef TEST_MATRIX_UTIL #define TEST_MATRIX_UTIL #include "matrix_util.h" //#include <cblas.h> //int test_blas(int result); int test_my_zgemm(int result); int test_inv2by2(int result); int test_inv2by2inv2by2_overwrite(int result); int test_outer(int result); int test_my_zaxpy(int result); int test_my_zdot(int result); #endif
{ "alphanum_fraction": 0.7827380952, "avg_line_length": 16.8, "ext": "h", "hexsha": "057229165ed83ff44658b397c699c0e9dbf8814a", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "485345e730a4cbf5cff6dbdeeb5e1fb7c4283733", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ThayaFluss/cnl", "max_forks_repo_path": "src/cy_fde/test_matrix_util.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "485345e730a4cbf5cff6dbdeeb5e1fb7c4283733", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ThayaFluss/cnl", "max_issues_repo_path": "src/cy_fde/test_matrix_util.h", "max_line_length": 46, "max_stars_count": null, "max_stars_repo_head_hexsha": "485345e730a4cbf5cff6dbdeeb5e1fb7c4283733", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ThayaFluss/cnl", "max_stars_repo_path": "src/cy_fde/test_matrix_util.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 89, "size": 336 }
#ifndef TPEM_H #define TPEM_H #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #ifndef NO_GSL #include <gsl/gsl_integration.h> #include <gsl/gsl_errno.h> #endif #ifdef __cplusplus extern "C" { #endif #define COMPLEX 1 #ifdef COMPLEX typedef struct { double real, imag; } tpem_t; #else typedef double tpem_t; #endif /* COMPLEX */ void *tpem_malloc (size_t); void tpem_print (tpem_t a, FILE *b); tpem_t tpem_cast (double, double); double tpem_real (tpem_t); double tpem_imag (tpem_t z); double tpem_chebyshev(int m,double x); /* tpem_sparse.c * * struct tpem_sparse implements a sparse matrix in compressed row storage * format. * The CRS format puts the subsequent nonzero elements of the matrix rows * in contiguous memory locations. We create 3 vectors: one for tpem_t numbers * (*values) and the other two for integers (*colind, *rowptr). * * The *values vector stores the values of the nonzero elements of the matrix, * as they are traversed in a row-wise fashion. * * The *colind vector stores the column indices of the elements of the *values * vector. That is, if * values[k] = a[i][j] then colind[k] = j * * The *rowptr vector stores the locations in the *values vector that start * a row, that is * values[k] = a[i][j] if rowptr[i] <= i < rowptr[i + 1] * * By convention, we define rowptr[n] = #(nz), the number of nonzeros in the * matrix. The storage savings of this approach is significant. Instead of * storing n^2 elements, we need only 2#(nz) + n + 1 storage locations. * * As an example, consider the nonsymmetric matrix defined by * [10 0 0 0 -2 0 ] * [ 3 9 0 0 0 3 ] * A = [ 0 7 8 7 0 0 ] * [ 3 0 8 7 5 0 ] * [ 0 8 0 9 9 13 ] * [ 0 4 0 0 2 -1 ] * The CRS format for this matrix is then specified by the arrays given below * values = [10 -2 3 9 3 7 8 7 3 ... 9 13 4 2 -1 ] * colind = [ 0 4 0 1 5 1 2 3 0 ... 4 5 1 4 5 ] * rowptr = [ 0 2 5 8 12 16 19 ] * * Here's an example illustrating matrix vector product: * * void tpem_sparse_mult (sparse *matrix, tpem_t *dest, tpem_t *src) * { * size_t row, col, k; * tpem_t tmp; * * for (row = 0; row < matrix->rank; row++) { * sum = 0.0; * for (k = matrix->rowptr[row]; k < matrix->rowptr[row+1]; k++) { * col = matrix->colind[k]; * sum += matrix->values[k] * src[col]; * } * dest[row] = sum; * } * } * * new_tpem_sparse (rank, size) is a constructor * rank: number of rows (we don't consider degenerate matrices) * size: #(nz), the total number of nonzero elements * * tpem_sparse_element (this, row, col) * this: pointer to the matrix (think pathetic OO) * row: row index * col: column index * returns a pointer to a[row][col] or freaks * */ typedef struct { size_t rank; /* number of rows */ size_t *rowptr; size_t *colind; tpem_t *values; } tpem_sparse; tpem_sparse *new_tpem_sparse (size_t, size_t); void tpem_sparse_free (tpem_sparse *); void tpem_sparse_copy (tpem_sparse *, tpem_sparse *); tpem_t *tpem_sparse_element (tpem_sparse *, size_t, size_t); /* void tpem_sparse_print (tpem_sparse *, FILE *); */ void tpem_matrix_free (tpem_t **); tpem_t **new_tpem_matrix (size_t, size_t); /* subspace.c * * struct tpem_subspace is opaque to the user, don't worry about it. But if * you must know, the boolean *flags vector tells whether the i^th state has * been used so far, think of the macro * #define isused(i) (flags[i] != 0) * *stack and *top implement a stack of all states that have been used since * the last call to tpem_subspace_reset. The rest should be self-explanatory. * */ typedef struct { size_t size; int *flags; size_t *stack, *top; } tpem_subspace; tpem_subspace *new_tpem_subspace (size_t); void tpem_subspace_free (tpem_subspace *); void tpem_subspace_reset (tpem_subspace *); void tpem_subspace_push (tpem_subspace *, size_t); /* void tpem_subspace_print (tpem_subspace *, FILE *); */ /* tpem.c */ typedef double (*tpem_func_ptr) (double); void tpem_off_diagonal_element_tpem (tpem_sparse *, size_t, tpem_t **, size_t, double); void tpem_calculate_moment_tpem (tpem_sparse *, size_t, double *, double); void tpem_calculate_moment_pem (tpem_sparse *, size_t, double *); void tpem_calculate_moment_diff_tpem (tpem_sparse *, tpem_sparse *, size_t, double *, size_t, size_t *, double, double); void tpem_calculate_moment_diff_pem (tpem_sparse *, tpem_sparse *, size_t, double *); void tpem_calculate_coeffs (size_t, double *,tpem_func_ptr f); void tpem_calculate_coeffs_alt (size_t, double *,tpem_func_ptr f); void tpem_calculate_coeffs_dos (size_t , double *, size_t , size_t , size_t, size_t ); double tpem_expansion (size_t, double *, double *); void tpem_finalize (void); void tpem_init (void); /* * CALL TREE: * ---------- * * tpem_calculate_moment: * \tpem_diagonal_element: * \tpem_sparse_product * * tpem_calculate_moment_diff: * |tpem_subspace_for_trace: * | \tpem_diagonal_element: * | \tpem_sparse_product * \tpem_diagonal_element: * \tpem_sparse_product * * tpem_finalize: * |tpem_diagonal_element * |tpem_calculate_moment * \tpem_calculate_moment_diff */ #ifdef __cplusplus } #endif #endif
{ "alphanum_fraction": 0.6829638052, "avg_line_length": 27.6282722513, "ext": "h", "hexsha": "b131327c1fdf3ff85825c24ca6ce9a64daed0064", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "344a24705f0cbf0af942cefc1a03c4c9dbfc673c", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Greatliao/skyrmions", "max_forks_repo_path": "C_pem/tpemstatedensity/TPEM/tpem.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "344a24705f0cbf0af942cefc1a03c4c9dbfc673c", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "Greatliao/skyrmions", "max_issues_repo_path": "C_pem/tpemstatedensity/TPEM/tpem.h", "max_line_length": 88, "max_stars_count": null, "max_stars_repo_head_hexsha": "344a24705f0cbf0af942cefc1a03c4c9dbfc673c", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Greatliao/skyrmions", "max_stars_repo_path": "C_pem/tpemstatedensity/TPEM/tpem.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1718, "size": 5277 }
/* * The MIT License is a permissive free software license, which permits reuse * within both open source and proprietary software. The software is licensed * as is, and no warranty is given as to fitness for purpose or absence of * infringement of third parties' rights, such as patents. Generally use for * research activities is allowed regardless of any third party patents, but * commercial use may be subject to a separate license. * * * The MIT License (MIT) * * Copyright (c) 2015 Tuomo Raitio * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * * * * <><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><> * GlottHMM Speech Synthesis * <><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><> * * This program reads speech parameters and a glottal pulse/ * pulse library, and synthesizes speech from them. * * This program has been written in Aalto University, * Department of Signal Processign and Acoustics, Espoo, Finland * * Main author: Tuomo Raitio * Acknowledgements: Antti Suni, Paavo Alku, Martti Vainio * * File Synthesis.c * Version: 1.1 * */ /***********************************************/ /* INCLUDE */ /***********************************************/ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <time.h> #include <gsl/gsl_vector.h> /* GSL, Vector */ #include <gsl/gsl_matrix.h> /* GSL, Matrix */ #include <gsl/gsl_fft_real.h> /* GSL, FFT */ #include <libconfig.h> /* Configuration file */ #include "SynthesisFunctions.h" /*******************************************************************/ /* MAIN */ /*******************************************************************/ int main(int argc, char *argv[]) { /* Start counter */ double time1 = (double)clock(); /* Check command line format */ if(Check_command_line(argc) == EXIT_FAILURE) return EXIT_FAILURE; /* Read default configuration file and assign parameters */ struct config_t *conf_def = Read_config(argv[2]); if(conf_def == NULL) return EXIT_FAILURE; PARAM params; if(Assign_config_parameters(argv[1],conf_def,&params,DEF_CONF) == EXIT_FAILURE) { config_destroy(conf_def); free(conf_def); return EXIT_FAILURE; } /* Read user configuration file and assign parameters */ if(argc == 4) { struct config_t *conf_usr = Read_config(argv[3]); if(conf_usr == NULL) return EXIT_FAILURE; if(Assign_config_parameters(argv[1],conf_usr,&params,USR_CONF) == EXIT_FAILURE) { config_destroy(conf_usr); free(conf_usr); return EXIT_FAILURE; } } /* Print synthesis settings */ Print_synthesis_settings_start(&params); /*******************************************************************/ /* READ PULSE LIBRARY / PULSE */ /*******************************************************************/ /* Allocate space for pulse library and read data */ gsl_matrix *pulses,*pulses_rs,*plsf,*ptilt,*pharm,*phnr,*pwaveform,*pca_pc,*pca_w_lib; gsl_vector *pgain,*pulse_lengths,*ph1h2,*pnaq,*pca_mean,*stoch_env,*stoch_sp; if(Read_pulse_library(&params,&pulses,&pulses_rs,&plsf,&ptilt,&pharm,&phnr,&pwaveform,&pca_pc, &pca_w_lib,&stoch_env,&stoch_sp,&pgain,&ph1h2,&pnaq,&pca_mean,&pulse_lengths) == EXIT_FAILURE) return EXIT_FAILURE; /* Read pulse file if pulse library is not used */ gsl_vector *original_pulse = NULL; if(params.use_pulselib == 0) { original_pulse = ReadPulseFile(&params); if(original_pulse == NULL) return EXIT_FAILURE; } /* Read DNN pulse generation weights and allocate parameters */ gsl_matrix **DNN_W = (gsl_matrix**)malloc(params.dnn_weight_dims->size/2*sizeof(gsl_matrix*)); if(Read_DNN_weights(&params,DNN_W) == EXIT_FAILURE) return EXIT_FAILURE; gsl_vector **input_minmax = (gsl_vector**)malloc(sizeof(gsl_vector*)); if(Read_input_minmax(&params,input_minmax) == EXIT_FAILURE) return EXIT_FAILURE; gsl_vector *dnnpulseindices = NULL; gsl_vector *dnnpulses = NULL; /* Define variables */ gsl_vector *gain,*fundf,*excitation_voiced,*excitation_unvoiced; gsl_vector *gain_new,*pulse_clus_id,*h1h2,*naq,*resynthesis_pulse_index; gsl_matrix *LSF,*LSF2,*glflowsp,*glflowsp_new,*hnr,*hnr_new,*harmonics,*waveform,*pulse_clusters,*pca_w,*LSF_interp = NULL; int i; /****************************************************************************************/ /* START SYNTHESING FILE(S) */ /****************************************************************************************/ /* Start loop for synthesis list */ for(i=0; i<params.synlistlen; i++) { /* Initialize params */ if(Initialize_params(&params,i) == EXIT_FAILURE) return EXIT_FAILURE; /* Print synthesis settings */ Print_synthesis_settings_middle(&params); /* Compatibility check */ if(Compatibility_check(&params) == EXIT_FAILURE) return EXIT_FAILURE; /*****************************************************************************/ /* LOAD AND MODIFY PARAMETERS */ /*****************************************************************************/ /* Allocate and read synthesis parameters, initialize pulse clustering if used */ Allocate_params(&excitation_voiced,&excitation_unvoiced,&resynthesis_pulse_index,&gain_new,&glflowsp_new,&hnr_new,&params); if(Read_synthesis_parameters(&gain,&fundf,&LSF,&LSF2,&glflowsp,&hnr,&harmonics,&waveform,&h1h2,&naq,&pca_w,&params) == EXIT_FAILURE) continue; if(Pulse_clustering(&pulse_clus_id, &pulse_clusters, &params) == EXIT_FAILURE) continue; /* Miscellaneous operations */ Convert_logF0_to_lin(fundf,&params); Merge_voiced_unvoiced_spectra(LSF,LSF2,fundf,&params); Integrate_LSFs(&LSF,&params); if(params.use_tilt == 1) Integrate_LSFs(&glflowsp,&params); LSF_fix_matrix(LSF); LSF_fix_matrix(glflowsp); Smooth_matrix(hnr,params.hnr_smooth_len); if(params.use_hmm == 0) Smooth_matrix(harmonics,params.harmonics_smooth_len); if(params.use_hmm == 0) MA(gain,params.gain_smooth_len); /* Modification for noise robust speech */ Noise_robust_speech2(gain,harmonics,&params); /* Formant enhancement for LSFs */ Postfilter(LSF,&params); /* Apply noise reduction */ Noise_reduction(gain,&params); /* Normalize pulse library parameters according to synthesis parameters (normalize mean) */ Normalize_pulse_library_var(plsf,ptilt,pharm,phnr,pwaveform,pgain,ph1h2,pnaq,LSF,glflowsp, harmonics,hnr,waveform,gain,h1h2,naq,fundf,&params); /* Adapt synthesis parameters according to pulse library parameters (normalize mean) */ Adapt_synthesis_parameters_var(plsf,ptilt,pharm,phnr,pwaveform,pgain,ph1h2,pnaq,LSF,glflowsp, harmonics,hnr,waveform,gain,h1h2,naq,fundf,pulse_lengths,&params); /* Select vocal tract LSFs from pulse library */ // TODO: Viterbi int winsize = 5; Select_LSFs_from_pulse_library(LSF,plsf,fundf,winsize,&params); /* Smooth and interpolate LSFs to signal length */ LSF_interp = gsl_matrix_alloc(params.signal_length,params.lpc_order_vt); Smooth_interp_lsf(LSF_interp,LSF,params.signal_length,params.use_hmm,params.lsf_smooth_len); /* DNN pulse gen */ if(params.use_dnn_pulsegen == 1) { dnnpulseindices = gsl_vector_alloc(params.signal_length); dnnpulses = gsl_vector_alloc(2*params.signal_length); } /*******************************************************************/ /* CREATE EXCITATION */ /*******************************************************************/ printf(" - Creating excitation...\n"); /* Create excitation for estimating the HNR of the voiced excitation */ CreateExcitation(&params,excitation_voiced,excitation_unvoiced,fundf,gain,LSF,glflowsp,hnr,harmonics,waveform,h1h2,naq, original_pulse,pulses,pulses_rs,pulse_lengths,pgain,plsf,ptilt,phnr,pharm,pwaveform,ph1h2,pnaq, resynthesis_pulse_index,pulse_clus_id,pulse_clusters,gain,glflowsp_new,hnr_new,pca_mean,pca_pc,pca_w,pca_w_lib, stoch_env,stoch_sp,DNN_W,input_minmax,dnnpulseindices,dnnpulses); /* Compensate HNR etc */ HNR_compensation(hnr,hnr_new,&params); Fill_pulse_indices(resynthesis_pulse_index); params.resynth = 1; /* Create excitation */ CreateExcitation(&params,excitation_voiced,excitation_unvoiced,fundf,gain,LSF,glflowsp,hnr,harmonics,waveform,h1h2,naq, original_pulse,pulses,pulses_rs,pulse_lengths,pgain,plsf,ptilt,phnr,pharm,pwaveform,ph1h2,pnaq, resynthesis_pulse_index,pulse_clus_id,pulse_clusters,gain,glflowsp_new,hnr_new,pca_mean,pca_pc,pca_w,pca_w_lib, stoch_env,stoch_sp,DNN_W,input_minmax,dnnpulseindices,dnnpulses); Print_elapsed_time(&params); /* Compensate for the pre-emphasis during analysis (de-emphasis) */ if(params.unvoiced_pre_emphasis == 1) Integrate(excitation_unvoiced, 0.97); // Slightly less than leaky factor /*******************************************************************/ /* SPECTRAL MATCHING */ /*******************************************************************/ if((params.use_pulselib == 0 && params.use_dnn_pulsegen == 0) || (params.use_pulselib_pca == 1 && params.pca_spectral_matching == 1) || (params.use_dnn_pulsegen == 1 && params.use_dnn_specmatch == 1)) { printf(" - Spectral matching...\n"); Spectral_match(excitation_voiced, glflowsp, glflowsp_new, &params); if(params.use_pulselib_pca == 0 && params.use_dnn_pulsegen == 0 && params.two_pitch_period_diff_pulse == 0) LipRadiation(excitation_voiced); Print_elapsed_time(&params); } /*******************************************************************/ /* FILTER EXCITATION */ /*******************************************************************/ /* Combine excitations and filter */ printf(" - Filtering excitation...\n"); gsl_vector_add(excitation_voiced,excitation_unvoiced); Filter_excitation(excitation_voiced,LSF_interp,&params); Print_elapsed_time(&params); /*******************************************************************/ /* RESYNTHESIS FOR GAIN NORMALIZATION */ /*******************************************************************/ /* Evaluate new gain for re-synthesis */ printf(" - Re-synthesis for gain normalization...\n"); Evaluate_new_gain(excitation_voiced,gain_new,gain,fundf,&params); /* Re-synthesize with new gain */ CreateExcitation(&params,excitation_voiced,excitation_unvoiced,fundf,gain_new,LSF,glflowsp,hnr,harmonics,waveform,h1h2,naq, original_pulse,pulses,pulses_rs,pulse_lengths,pgain,plsf,ptilt,phnr,pharm,pwaveform,ph1h2,pnaq, resynthesis_pulse_index,pulse_clus_id,pulse_clusters,gain,glflowsp_new,hnr_new,pca_mean,pca_pc,pca_w,pca_w_lib, stoch_env,stoch_sp,DNN_W,input_minmax,dnnpulseindices,dnnpulses); if(params.unvoiced_pre_emphasis == 1) Integrate(excitation_unvoiced, 0.97); // Slightly less than leaky factor /* Spectral matching */ if((params.use_pulselib == 0 && params.use_dnn_pulsegen == 0) || (params.use_pulselib_pca == 1 && params.pca_spectral_matching == 1) || (params.use_dnn_pulsegen == 1 && params.use_dnn_specmatch == 1)) { Spectral_match(excitation_voiced, glflowsp, glflowsp_new, &params); if(params.use_pulselib_pca == 0 && params.use_dnn_pulsegen == 0 && params.two_pitch_period_diff_pulse == 0) LipRadiation(excitation_voiced); } /* Combine excitations and filter */ gsl_vector_add(excitation_voiced,excitation_unvoiced); /* Save excitation to wav file */ Save_excitation_to_wav(excitation_voiced,&params); /* Filter excitation */ Filter_excitation(excitation_voiced,LSF_interp,&params); /*******************************************************************/ /* POSTPROCESSING AND SAVE TO FILE */ /*******************************************************************/ /* Filter out signal below F0 */ Hp_filt_below_f0(excitation_voiced,fundf,&params); /* Compression of speech signal (only in noise robust speech) */ Compression(excitation_voiced, params.compcoeff); /* Scale (if > 1) and save signal to file */ Scale_signal(excitation_voiced,SCALE_IF_GREATER_THAN_ONE); Save_signal_to_file(excitation_voiced,&params,NULL); /* Report */ Print_synthesis_settings_end(&params,time1); } /*******************************************************************/ /* FREE MEMORY AND FINISH */ /*******************************************************************/ /* Free memory */ Free_pulselib_variables(pulses,pulses_rs,pwaveform,pulse_lengths,plsf,ptilt,pharm,phnr,pgain,ph1h2,pnaq,pca_mean,pca_pc,pca_w_lib,stoch_env,stoch_sp,&params); Free_variables(original_pulse,excitation_voiced,excitation_unvoiced,fundf,gain,gain_new,LSF,LSF2,LSF_interp,glflowsp,glflowsp_new, hnr,hnr_new,harmonics,waveform,h1h2,naq,resynthesis_pulse_index,pulse_clus_id,pulse_clusters,pca_w, DNN_W,input_minmax,dnnpulseindices,dnnpulses,&params); /* Exit */ return EXIT_SUCCESS; } /***********/ /* EOF */ /***********/
{ "alphanum_fraction": 0.6343643092, "avg_line_length": 40.3464788732, "ext": "c", "hexsha": "7cda94b470361b8ca1723b17f8f660dad46c3d9c", "lang": "C", "max_forks_count": 7, "max_forks_repo_forks_event_max_datetime": "2022-03-28T09:17:33.000Z", "max_forks_repo_forks_event_min_datetime": "2016-08-03T12:08:32.000Z", "max_forks_repo_head_hexsha": "4dfe5eb0b6dacc227299acc29c6df8b030de82b8", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "mjansche/GlottHMM", "max_forks_repo_path": "src/Synthesis.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "4dfe5eb0b6dacc227299acc29c6df8b030de82b8", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "mjansche/GlottHMM", "max_issues_repo_path": "src/Synthesis.c", "max_line_length": 159, "max_stars_count": 10, "max_stars_repo_head_hexsha": "4dfe5eb0b6dacc227299acc29c6df8b030de82b8", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "mjansche/GlottHMM", "max_stars_repo_path": "src/Synthesis.c", "max_stars_repo_stars_event_max_datetime": "2020-09-03T12:46:50.000Z", "max_stars_repo_stars_event_min_datetime": "2016-06-29T22:08:09.000Z", "num_tokens": 3664, "size": 14323 }
/* spcopy.c * * Copyright (C) 2014 Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_spmatrix.h> #include <gsl/gsl_errno.h> #include "avl.c" int gsl_spmatrix_memcpy(gsl_spmatrix *dest, const gsl_spmatrix *src) { const size_t M = src->size1; const size_t N = src->size2; if (M != dest->size1 || N != dest->size2) { GSL_ERROR("matrix sizes are different", GSL_EBADLEN); } else if (dest->sptype != src->sptype) { GSL_ERROR("cannot copy matrices of different storage formats", GSL_EINVAL); } else { int s = GSL_SUCCESS; size_t n; if (dest->nzmax < src->nz) { s = gsl_spmatrix_realloc(src->nz, dest); if (s) return s; } /* copy indices and data to dest */ if (GSL_SPMATRIX_ISTRIPLET(src)) { void *ptr; for (n = 0; n < src->nz; ++n) { dest->i[n] = src->i[n]; dest->p[n] = src->p[n]; dest->data[n] = src->data[n]; /* copy binary tree data */ ptr = avl_insert(dest->tree_data->tree, &dest->data[n]); if (ptr != NULL) { GSL_ERROR("detected duplicate entry", GSL_EINVAL); } } } else if (GSL_SPMATRIX_ISCCS(src)) { for (n = 0; n < src->nz; ++n) { dest->i[n] = src->i[n]; dest->data[n] = src->data[n]; } for (n = 0; n < src->size2 + 1; ++n) { dest->p[n] = src->p[n]; } } else if (GSL_SPMATRIX_ISCRS(src)) { for (n = 0; n < src->nz; ++n) { dest->i[n] = src->i[n]; dest->data[n] = src->data[n]; } for (n = 0; n < src->size1 + 1; ++n) { dest->p[n] = src->p[n]; } } else { GSL_ERROR("invalid matrix type for src", GSL_EINVAL); } dest->nz = src->nz; return s; } } /* gsl_spmatrix_memcpy() */
{ "alphanum_fraction": 0.5134482759, "avg_line_length": 26.3636363636, "ext": "c", "hexsha": "b96c21bf6290515fe7c355d047d39d30c5f1e95e", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/spmatrix/spcopy.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/spmatrix/spcopy.c", "max_line_length": 81, "max_stars_count": 1, "max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_stars_repo_path": "gsl-2.4/spmatrix/spcopy.c", "max_stars_repo_stars_event_max_datetime": "2021-01-13T05:01:59.000Z", "max_stars_repo_stars_event_min_datetime": "2021-01-13T05:01:59.000Z", "num_tokens": 784, "size": 2900 }