Search is not available for this dataset
text
string
meta
dict
/* $Header$ */ /* Purpose: Description (definition) of spherical geometry functions */ /* This file includes BSD-licensed code whose copyright is held by another author The copyright owner and license terms for the NCO modifications to that code are Copyright (C) 2018--present Charlie Zender This file is part of NCO, the netCDF Operators. NCO is free software. You may redistribute and/or modify NCO under the terms of the 3-Clause BSD License with exceptions described in the LICENSE file */ /* This copyright statement and license terms for modification and redistribution of the original code were agreed to by the original author, Joseph O'Rourke, on 20190517: This code is described in "Computational Geometry in C" (Second Edition), Chapter 7. It is not written to be comprehensible without the explanation in that book. Written by Joseph O'Rourke. Last modified: December 1997 Questions to jorourke@smith.edu. ------------------------------------------------------------------------- Copyright 1997 by Joseph O'Rourke <jorourke@smith.edu> 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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. ------------------------------------------------------------------------- */ /* Usage: #include "nco_sph.h" *//* Spherical geometry intersections */ #ifndef NCO_SPH_H /* Contents have not yet been inserted in current source file */ #define NCO_SPH_H #include <stdlib.h> #include <stdio.h> #include <math.h> #ifdef HAVE_CONFIG_H # include <config.h> /* Autotools tokens */ #endif /* !HAVE_CONFIG_H */ #ifdef ENABLE_GSL #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_permutation.h> #include <gsl/gsl_linalg.h> #endif /* Personal headers */ #include "nco.h" /* netCDF Operator (NCO) definitions */ #include "nco_mmr.h" /* Memory management */ #include "nco_omp.h" /* OpenMP utilities */ #include "nco_rgr.h" /* Regridding */ #include "nco_sld.h" /* Swath-Like Data */ #include "nco_sng_utl.h" /* String utilities */ #include "nco_crt.h" /* Cartesian geometry intersections */ #include "nco_ply.h" /* Polygon structure & utilities */ #define NBR_SPH (5) #define NBR_RLL (5) #define VP_MAX 1000 /* Max # of pts in polygon */ /* this is 1.0e-20 * PI / 180.0 */ #define ARC_MIN_LENGTH_RAD (1.0e-15) /* smallest RADIAN */ #define SIGMA_RAD (1.0e-12) #define SIGMA_TOLERANCE (1.0e-16) #define DOT_TOLERANCE (1.0e-14) /* this value plays nice with edges on grids/ne120np4_pentagons.100310.nc */ #define DIST_TOLERANCE (1.0e-14) /* convert Degrees to Radians */ #define D2R(x) ((x) * M_PI / 180.0) /* convert Radians to degrees */ #define R2D(x) ((x) * 180.0 / M_PI) /* if true then longitude 0-360 */ /* we need this to convert 3D back to 2D */ #define IS_LON_360 (1) // #define DEBUG_SPH (1) #ifdef __cplusplus /* Use C-bindings so C++-compiled and C-compiled libraries are compatible */ extern "C" { #endif /* !__cplusplus */ /*--------------------------------------------------------------------- Structures ---------------------------------------------------------------------*/ /* vertex info */ typedef struct { poly_vrl_flg_enm in_flag; /* if P_in - vertex from a, Q_in Vertex from b */ int p_vrt; /* if -1 then genuine intersection */ int q_vrt; double p0[NBR_SPH]; /* actual point - used for debuggging */ }vrt_info_sct; /*--------------------------------------------------------------------- Function prototypes. ---------------------------------------------------------------------*/ int nco_sph_intersect(poly_sct *P, poly_sct *Q, poly_sct *R, int *r, int flg_snp_to, const char *pq_pre); char nco_sph_seg_int_old(double *a, double *b, double *c, double *d, double *p, double *q); nco_bool nco_sph_seg_int(double *p0, double *p1, double *q0, double *q1, double *r0, double *r1, int *pq_cross, int flg_snp_to, char *codes); int nco_sph_mk_pqcross( double *p0, double *p1, double *pCross, double *q0, double *q1, double *qCross, int pqCross[], nco_edg_typ_enm rgr_edg_typ, nco_edg_typ_enm *p_edg_typ, nco_edg_typ_enm *q_edg_typ); nco_bool nco_sph_seg_parallel(double *p0, double *p1, double *q0, double *q1, double *r0, double *r1, poly_vrl_flg_enm *inflag, char *codes ); nco_bool nco_sph_seg_smc(double *p0, double *p1, double *q0, double *q1, double *r0, double *r1, int *pq_cross, int flg_snp_to, char *codes); nco_bool nco_sph_seg_vrt_int(double *a, double *b, double *c); int nco_sph_lhs(double *Pi, double *Qi); nco_bool nco_sph_face(int iLHS, int iRHS, int jRHS); double nco_sph_dot(double *a, double *b); double nco_sph_dot_nm(double *a, double *b); double nco_sph_cross(double *a, double *b, double *c); double nco_sph_cross_sub(double *a, double *b, double *c); double nco_sph_cross2(double *a, double *b, double *c); double nco_sph_trp(double *a, double *b, double *c); void nco_sph_add(double *a, double *b, double *c); void nco_sph_sub(double *a, double *b, double *c); void nco_sph_mlt(double *a, double m); double nco_sph_dist(double *a, double *b); double nco_sph_rad(double *a); double nco_sph_rad2(double *a); double nco_sph_sxcross(double *a, double *b, double *c); void nco_sph_adi(double *a, double *b); void nco_sph_add_pnt(double **R, int *r, double *P); bool nco_sph_vrt_info_cmp( vrt_info_sct *info_a, vrt_info_sct *info_b); void nco_sph_add_pnt_chk( vrt_info_sct *vrt_info, poly_vrl_flg_enm inflag, int p_vrt, int q_vrt, double **R, int *r, double *P); nco_bool nco_sph_between(double a, double b, double x); void nco_sph_prn_pnt(const char *sMsg, double *p, int style, nco_bool bRet); nco_bool nco_sph_is_convex(double **sP, int np); void nco_sph_prn(double **sR, int r, int istyle); int nco_sph_pnt_in_poly(double **sP, int n, double *pControl, double *pVertex); nco_bool nco_sph_poly_in_poly(poly_sct *sP,poly_sct *sQ); void nco_sph_set_domain(double lon_min_rad, double lon_max_rad, double lat_min_rad, double lat_max_rad); void nco_sph_add_lonlat(double *ds); int nco_sph_mk_control(poly_sct *sP, nco_bool bInside, double* pControl ); /* make a control point that is outside polygon */ nco_bool nco_sph_intersect_pre(poly_sct *sP,poly_sct *sQ, char *sq_sng ); int nco_sph_process_pre(poly_sct *sQ, char *sq_sng, nco_bool *bGenuine); void nco_sph_centroid_mk(poly_sct *sP, double *pControl); nco_bool nco_sph_inside_mk(poly_sct *sP, double *pControl); nco_bool nco_sph_metric( double *p, double *q); int nco_sph_metric_int(double *c, double *d, double *Icross); double nco_sph_area_karney( double **sP, int np); double nco_sph_area_quadrature(double **sP, int np); /***************** nco_geo functions these manimpulate lat & lon ***************************/ void nco_geo_sph_2_lonlat(double *a, double *lon, double *lat, nco_bool bDeg); void nco_geo_lonlat_2_sph(double lon, double lat, double *b, nco_bool bSimple, nco_bool bDeg); double nco_geo_lat_correct(double lat1, double lon1, double lon2); void nco_geo_get_lat_correct(double lon1, double lat1, double lon2, double lat2, double *dp_min, double *dp_max, nco_bool bDeg); /**************** functions for RLL grids ***************************************************/ int nco_rll_intersect(poly_sct *P, poly_sct *Q, poly_sct *R, int *r); char nco_rll_seg_int(double *a, double *b, double *c, double *d, double *p, double *q); nco_bool nco_rll_seg_parallel(double *p0, double *p1, double *q0, double *q1, double *r0, double *r1, poly_vrl_flg_enm *inflag, char *codes ); void nco_rll_area(poly_sct *pl); nco_bool nco_rll_is_lat_circle(double *p0, double *p1); int nco_rll_lhs(double *p0, double *QCross); int nco_rll_lhs_lat(double *p0, double *q0, double *q1); void nco_rll_add_pnt(double **R, int *r, double *P); /*********************** functions for matrix*****************************************************/ void nco_mat_mlt (double mat[], double vec[], double vec_out[]); nco_bool nco_mat_inv(double *mat, double *mat_inv); nco_bool nco_mat_int_pl(const double *p0, const double *p1, const double *q0, const double *q1, double *r0); #ifdef __cplusplus } /* end extern "C" */ #endif /* !__cplusplus */ #endif /* NCO_SPH_H */
{ "alphanum_fraction": 0.6828184511, "avg_line_length": 29.5375, "ext": "h", "hexsha": "cbf261874d2521cf9913f8d02dac2e788c8c37d1", "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": "69c05f48f99c524e3ed7a271e41824c584b317a2", "max_forks_repo_licenses": [ "BSD-3-Clause-Clear", "BSD-3-Clause" ], "max_forks_repo_name": "hbdch/nco", "max_forks_repo_path": "src/nco/nco_sph.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "69c05f48f99c524e3ed7a271e41824c584b317a2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause-Clear", "BSD-3-Clause" ], "max_issues_repo_name": "hbdch/nco", "max_issues_repo_path": "src/nco/nco_sph.h", "max_line_length": 203, "max_stars_count": 1, "max_stars_repo_head_hexsha": "69c05f48f99c524e3ed7a271e41824c584b317a2", "max_stars_repo_licenses": [ "BSD-3-Clause-Clear", "BSD-3-Clause" ], "max_stars_repo_name": "hbdch/nco", "max_stars_repo_path": "src/nco/nco_sph.h", "max_stars_repo_stars_event_max_datetime": "2020-07-22T21:12:21.000Z", "max_stars_repo_stars_event_min_datetime": "2020-07-22T21:12:21.000Z", "num_tokens": 2718, "size": 9452 }
/* These functions compute linear preprocessing for the UE using LAPACKE and CBLAS modules of LAPACK libraries. MMSE and MMSE whitening filters are available. Functions are using RowMajor storage of the matrices, like in conventional C. Traditional Fortran functions of LAPACK employ ColumnMajor data storage. */ #include<stdio.h> #include<math.h> #include<complex.h> #include <stdlib.h> #include <cblas.h> #include <string.h> #include <linux/version.h> #if RHEL_RELEASE_CODE >= 1796 #include <lapacke/lapacke_utils.h> #include <lapacke/lapacke.h> #else #include <lapacke_utils.h> #include <lapacke.h> #endif //#define DEBUG_PREPROC void transpose(int N, float complex *A, float complex *Result) { // COnputes C := alpha*op(A)*op(B) + beta*C, enum CBLAS_TRANSPOSE transa = CblasTrans; enum CBLAS_TRANSPOSE transb = CblasNoTrans; int rows_opA = N; // number of rows in op(A) and in C int col_opB = N; //number of columns of op(B) and in C int col_opA = N; //number of columns in op(A) and rows in op(B) int col_B; //number of columns in B float complex alpha = 1.0 + I * 0; int lda = rows_opA; float complex beta = 0.0 + I * 0; int ldc = rows_opA; int i; float complex *B; int ldb = col_opB; if(transb == CblasNoTrans) { B = (float complex *)calloc(ldb * col_opB, sizeof(float complex)); col_B = col_opB; } else { B = (float complex *)calloc(ldb * col_opA, sizeof(float complex)); col_B = col_opA; } float complex *C = (float complex *)malloc(ldc * col_opB * sizeof(float complex)); for(i = 0; i < lda * col_B; i += N + 1) { B[i] = 1.0 + I * 0; } cblas_cgemm(CblasRowMajor, transa, transb, rows_opA, col_opB, col_opA, &alpha, A, lda, B, ldb, &beta, C, ldc); memcpy(Result, C, N * N * sizeof(float complex)); free(B); free(C); } void conjugate_transpose(int N, float complex *A, float complex *Result) { // Computes C := alpha*op(A)*op(B) + beta*C, enum CBLAS_TRANSPOSE transa = CblasConjTrans; enum CBLAS_TRANSPOSE transb = CblasNoTrans; int rows_opA = N; // number of rows in op(A) and in C int col_opB = N; //number of columns of op(B) and in C int col_opA = N; //number of columns in op(A) and rows in op(B) int col_B; //number of columns in B float complex alpha = 1.0 + I * 0; int lda = rows_opA; float complex beta = 0.0 + I * 0; int ldc = rows_opA; int i; float complex *B; int ldb = col_opB; if(transb == CblasNoTrans) { B = (float complex *)calloc(ldb * col_opB, sizeof(float complex)); col_B = col_opB; } else { B = (float complex *)calloc(ldb * col_opA, sizeof(float complex)); col_B = col_opA; } float complex *C = (float complex *)malloc(ldc * col_opB * sizeof(float complex)); for(i = 0; i < lda * col_B; i += N + 1) { B[i] = 1.0 + I * 0; } cblas_cgemm(CblasRowMajor, transa, transb, rows_opA, col_opB, col_opA, &alpha, A, lda, B, ldb, &beta, C, ldc); memcpy(Result, C, N * N * sizeof(float complex)); free(B); free(C); } void H_hermH_plus_sigma2I(int N, int M, float complex *A, float sigma2, float complex *Result) { //C := alpha*op(A)*op(B) + beta*C, enum CBLAS_TRANSPOSE transa = CblasConjTrans; enum CBLAS_TRANSPOSE transb = CblasNoTrans; int rows_opA = N; // number of rows in op(A) and in C int col_opB = N; //number of columns of op(B) and in C int col_opA = N; //number of columns in op(A) and rows in op(B) int col_C = N; //number of columns in B float complex alpha = 1.0 + I * 0; int lda = col_opA; float complex beta = 1.0 + I * 0; int ldc = col_opA; int i; float complex *C = (float complex *)calloc(ldc * col_opB, sizeof(float complex)); for(i = 0; i < lda * col_C; i += N + 1) { C[i] = sigma2 * (1.0 + I * 0); } cblas_cgemm(CblasRowMajor, transa, transb, rows_opA, col_opB, col_opA, &alpha, A, lda, A, lda, &beta, C, ldc); memcpy(Result, C, N * M * sizeof(float complex)); free(C); } void HH_herm_plus_sigma2I(int M, int N, float complex *A, float sigma2, float complex *Result) { //C := alpha*op(A)*op(B) + beta*C, enum CBLAS_TRANSPOSE transa = CblasNoTrans; enum CBLAS_TRANSPOSE transb = CblasConjTrans; int k = N; //number of columns in op(A) and rows in op(B),k float complex alpha = 1.0 + I * 0; int lda = N; int ldb = N; int ldc = M; int i; float complex *C = (float complex *)calloc(M * M, sizeof(float complex)); for(i = 0; i < M * M; i += M + 1) { C[i] = 1.0 + I * 0; } cblas_cgemm(CblasRowMajor, transa, transb, M, M, k, &alpha, A, lda, A, ldb, &sigma2, C, ldc); memcpy(Result, C, M * M * sizeof(float complex)); free(C); } void eigen_vectors_values(int N, float complex *A, float complex *Vectors, float *Values_Matrix) { // This function computes ORTHONORMAL eigenvectors and eigenvalues of matrix A, // where Values_Matrix is a diagonal matrix of eigenvalues. // A=Vectors*Values_Matrix*Vectors' char jobz = 'V'; char uplo = 'U'; int order_A = N; int lda = N; int i; float *Values = (float *)malloc(sizeof(float) * 1 * N); LAPACKE_cheev(LAPACK_ROW_MAJOR, jobz, uplo, order_A, A, lda, Values); memcpy(Vectors, A, N * N * sizeof(float complex)); for(i = 0; i < lda; i += 1) { Values_Matrix[i * (lda + 1)] = Values[i]; } free(Values); } void lin_eq_solver(int N, float complex *A, float complex *B, float complex *Result) { int n = N; int lda = N; int ldb = N; int nrhs = N; char transa = 'N'; int *IPIV = malloc(N * N * sizeof(int)); // Compute LU-factorization LAPACKE_cgetrf(LAPACK_ROW_MAJOR, n, nrhs, A, lda, IPIV); // Solve AX=B LAPACKE_cgetrs(LAPACK_ROW_MAJOR, transa, n, nrhs, A, lda, IPIV, B, ldb); // cgetrs( "N", N, 4, A, lda, IPIV, B, ldb, INFO ) memcpy(Result, B, N * N * sizeof(float complex)); free(IPIV); } void mutl_matrix_matrix_row_based(float complex *M0, float complex *M1, int rows_M0, int col_M0, int rows_M1, int col_M1, float complex *Result) { enum CBLAS_TRANSPOSE transa = CblasNoTrans; enum CBLAS_TRANSPOSE transb = CblasNoTrans; int rows_opA = rows_M0; // number of rows in op(A) and in C int col_opB = col_M1; //number of columns of op(B) and in C int col_opA = col_M0; //number of columns in op(A) and rows in op(B) float complex alpha = 1.0; int lda = col_M0; float complex beta = 0.0; int ldc = col_M1; int ldb = col_M1; #ifdef DEBUG_PREPROC int i = 0; printf("rows_M0 %d, col_M0 %d, rows_M1 %d, col_M1 %d\n", rows_M0, col_M0, rows_M1, col_M1); for(i = 0; i < rows_M0 * col_M0; ++i) { printf(" rows_opA = %d, col_opB = %d, W_MMSE[%d] = (%f + i%f)\n", rows_opA, col_opB, i, creal(M0[i]), cimag(M0[i])); } for(i = 0; i < rows_M1 * col_M1; ++i) { printf(" M1[%d] = (%f + i%f)\n", i, creal(M1[i]), cimag(M1[i])); } #endif cblas_cgemm(CblasRowMajor, transa, transb, rows_opA, col_opB, col_opA, &alpha, M0, lda, M1, ldb, &beta, Result, ldc); #ifdef DEBUG_PREPROC for(i = 0; i < rows_opA * col_opB; ++i) { printf(" result[%d] = (%f + i%f)\n", i, creal(Result[i]), cimag(Result[i])); } #endif } void mutl_matrix_matrix_col_based(float complex *M0, float complex *M1, int rows_M0, int col_M0, int rows_M1, int col_M1, float complex *Result) { enum CBLAS_TRANSPOSE transa = CblasNoTrans; enum CBLAS_TRANSPOSE transb = CblasNoTrans; int rows_opA = rows_M0; // number of rows in op(A) and in C int col_opB = col_M1; //number of columns of op(B) and in C int col_opA = col_M0; //number of columns in op(A) and rows in op(B) float complex alpha = 1.0; int lda = col_M0; float complex beta = 0.0; int ldc = rows_M1; int ldb = rows_M1; #ifdef DEBUG_PREPROC int i = 0; printf("rows_M0 %d, col_M0 %d, rows_M1 %d, col_M1 %d\n", rows_M0, col_M0, rows_M1, col_M1); for(i = 0; i < rows_M0 * col_M0; ++i) { printf(" rows_opA = %d, col_opB = %d, W_MMSE[%d] = (%f + i%f)\n", rows_opA, col_opB, i, creal(M0[i]), cimag(M0[i])); } for(i = 0; i < rows_M1 * col_M1; ++i) { printf(" M1[%d] = (%f + i%f)\n", i, creal(M1[i]), cimag(M1[i])); } #endif cblas_cgemm(CblasColMajor, transa, transb, rows_opA, col_opB, col_opA, &alpha, M0, lda, M1, ldb, &beta, Result, ldc); #ifdef DEBUG_PREPROC for(i = 0; i < rows_opA * col_opB; ++i) { printf(" result[%d] = (%f + i%f)\n", i, creal(Result[i]), cimag(Result[i])); } #endif } /*FILTERS */ void compute_MMSE(float complex *H, int order_H, float sigma2, float complex *W_MMSE) { int N = order_H; float complex *H_hermH_sigmaI = malloc(N * N * sizeof(float complex)); float complex *H_herm = malloc(N * N * sizeof(float complex)); H_hermH_plus_sigma2I(N, N, H, sigma2, H_hermH_sigmaI); #ifdef DEBUG_PREPROC int i = 0; for(i = 0; i < N * N; i++) { printf(" H_hermH_sigmaI[%d] = (%f + i%f)\n", i, creal(H_hermH_sigmaI[i]), cimag(H_hermH_sigmaI[i])); } #endif conjugate_transpose(N, H, H_herm); //equals H_herm #ifdef DEBUG_PREPROC for(i = 0; i < N * N; i++) { printf(" H_herm[%d] = (%f + i%f)\n", i, creal(H_herm[i]), cimag(H_herm[i])); } #endif lin_eq_solver(N, H_hermH_sigmaI, H_herm, W_MMSE); #ifdef DEBUG_PREPROC for(i = 0; i < N * N; i++) { printf(" W_MMSE[%d] = (%f + i%f)\n", i, creal(W_MMSE[i]), cimag(W_MMSE[i])); } #endif free(H_hermH_sigmaI); free(H_herm); } float sqrt_float(float x, float sqrt_x) { sqrt_x = (float)(sqrt((double)(x))); return sqrt_x; }
{ "alphanum_fraction": 0.6040927971, "avg_line_length": 29.1179941003, "ext": "c", "hexsha": "0f7863384cb25cdbf0768d3a670da7a506919bdb", "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": "93e5617d68431a477e803af2fa66290fd52470d2", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "AManTw/oai5g", "max_forks_repo_path": "openair1/PHY/LTE_UE_TRANSPORT/linear_preprocessing_rec.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "93e5617d68431a477e803af2fa66290fd52470d2", "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": "AManTw/oai5g", "max_issues_repo_path": "openair1/PHY/LTE_UE_TRANSPORT/linear_preprocessing_rec.c", "max_line_length": 144, "max_stars_count": null, "max_stars_repo_head_hexsha": "93e5617d68431a477e803af2fa66290fd52470d2", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "AManTw/oai5g", "max_stars_repo_path": "openair1/PHY/LTE_UE_TRANSPORT/linear_preprocessing_rec.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3344, "size": 9871 }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <getopt.h> #include <mpi.h> #include <iniparser.h> #include "prepmt/prepmt_hpulse96.h" #include "prepmt/prepmt_event.h" #ifdef PARMT_USE_INTEL #include <mkl_cblas.h> #else #include <cblas.h> #endif #include "sacio.h" #include "cps.h" #include "cps_mpi.h" #include "cps_utils.h" #include "cps_defaults.h" #include "iscl/array/array.h" #include "iscl/memory/memory.h" #include "iscl/os/os.h" #include "iscl/string/string.h" #define PROGRAM_NAME "hspec96" static void grns2sac(const struct hwave_greens_struct grns, struct sacData_struct sac[10]); struct precompute_struct { char sourceModel[PATH_MAX]; /*!< Source model */ char crustDir[PATH_MAX]; /*!< Crust1.0 directory */ char hspecDistanceFile[PATH_MAX]; /*!< Table of distances for hspec */ char hspecArchiveFile[PATH_MAX]; /*!< Name of archive file with ff green's functions. */ double *depths; /*!< Depths (km) at which to compute greens fns */ double *dists; /*!< Distances (degrees) at which to compute surface wave greens fns */ double slat; /*!< Source latitude (degrees) */ double slon; /*!< Source longitude (degrees) */ double dt; /*!< Sampling period */ int npts; /*!< Number of samples */ int ndepths; /*!< Number of depths at which to compute greens fns */ int ndists; /*!< Number of distances to compute surface waves */ bool luseSourceMod; /*!< If true then use the local source model */ bool luseCrust; /*!< If true then use crust1.0 at teleseismic distances */ bool luseDistanceTable; /*!< If true then use a distance table. Otherwise linearly interpolate distances */ }; int prepmt_hspec96_readParameters(const char *iniFile, const char *section, struct precompute_struct *precompute); int prepmt_hspec96_initializeArchive( const char *archiveName, const char *model, const int ndepths, const double *__restrict__ depths, const int ngcarcs, const double *__restrict__ gcarcs); int prepmt_hspec96_readHspec96Parameters( const char *iniFile, struct hprep96_parms_struct *hprepParms, struct hspec96_parms_struct *hspecParms, struct hpulse96_parms_struct *hpulseParms); static void printUsage(void); static int parseArguments(int argc, char *argv[], char iniFile[PATH_MAX]); /*! * @brief Makes the regional fullwaveform fundamental fault Green's * functions archive. * */ int main(int argc, char **argv) { char fname[PATH_MAX], iniFile[PATH_MAX], groupName[512], *modelName; struct prepmtEventParms_struct event; struct sacData_struct *sac; struct precompute_struct precompute; struct hwave_greens_struct *grns; struct hpulse96_data_struct *zresp; struct hprep96_parms_struct hprepParms; struct hspec96_parms_struct hspecParms; struct hpulse96_parms_struct hpulseParms; struct vmodel_struct recmod, vmodel; double *depthr, *depths, *r, *tshift, *vred, dt; hid_t groupID, h5fl; int idep, idist, ierr, k, l, myid, ndeps, ndists, nprocs, npts, nwaves; // Here's the idea: I want to input magnitudes with units of N-m so: // N-m -> Dyne-dm (1.e+7) // CPS internally scales from Dyne-cm to cm (1.e+20) // Finally, I want outputs proprotional to m (1.e-2) const double xmom = 1.0; // no confusing `relative' magnitudes const double xcps = 1.e-20; // convert dyne-cm mt to output cm const double cm2m = 1.e-2; // cm to meters const double dcm2nm = 1.e+7; // magnitudes intended to be specified in // Dyne-cm but I work in N-m const char *cfaults[10] = {"ZDS\0", "ZSS\0", "ZDD", "ZEX\0", "RDS\0", "RSS\0", "RDD", "REX\0", "TDS\0", "TSS\0"}; // Given a M0 in Newton-meters get a seismogram in meters const double xscal = xmom*xcps*cm2m*dcm2nm; const int master = 0; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &myid); MPI_Comm_size(MPI_COMM_WORLD, &nprocs); sac = NULL; grns = NULL; zresp = NULL; modelName = NULL; r = NULL; depthr = NULL; depths = NULL; vred = NULL; tshift = NULL; memset(&hprepParms, 0, sizeof(struct hprep96_parms_struct)); memset(&hspecParms, 0, sizeof(struct hspec96_parms_struct)); memset(&hpulseParms, 0, sizeof(struct hpulse96_parms_struct)); memset(&vmodel, 0, sizeof(struct vmodel_struct)); if (myid == master) { // Parse the input arguments ierr = parseArguments(argc, argv, iniFile); if (ierr != 0) { if (ierr !=-1) { printf("%s: Failed to parse input commands\n", PROGRAM_NAME); } goto FINISH_EARLY; } // Read the CPS variables ierr = prepmt_hspec96_readHspec96Parameters(iniFile, &hprepParms, &hspecParms, &hpulseParms); if (ierr != 0) { printf("Error reading hprep parameters\n"); MPI_Abort(MPI_COMM_WORLD, 30); } // Read the additional contrived forward modeling variables ierr = prepmt_hspec96_readParameters(iniFile, "precompute", &precompute); if (ierr != 0) { printf("Error reading precompute parameters\n"); MPI_Abort(MPI_COMM_WORLD, 30); } ndists = precompute.ndists; ndeps = precompute.ndepths; // expand to make a grid r = (double *) calloc((size_t) (ndists*ndeps), sizeof(double)); depths = (double *) calloc((size_t) (ndists*ndeps), sizeof(double)); for (idep=0; idep<ndeps; idep++) { for (idist=0; idist<ndists; idist++) { k = idist*ndeps + idep; r[k] = precompute.dists[idist]*111.195; depths[k] = precompute.depths[idep]; printf("Wavform %d has distance %f (deg) and depth %f (km)\n", k+1, r[k]/111.195, depths[k]); } } npts = precompute.npts; dt = precompute.dt; //ndists = 31; //ndeps = 26; //npts = 1024; //2048; //dt = 1.0; //0.5; printf("%d %f %s\n", npts, dt, hprepParms.mfile); // load the model into memory if (precompute.luseSourceMod) { printf("%s: Loading source model %s...\n", PROGRAM_NAME, precompute.sourceModel); strcpy(hprepParms.mfile, precompute.sourceModel); ierr = cps_getmod(hprepParms.mfile, &vmodel); if (ierr != 0) { printf("Failed to load source model\n"); goto FINISH_EARLY; } } else if (precompute.luseCrust) { ierr = prepmt_event_initializeFromIniFile(iniFile, &event); if (ierr != 0) { printf("%s: Error getting event info\n", PROGRAM_NAME); goto FINISH_EARLY; } printf("%s: Loading CPS model (lat,lon)=(%f,%f)\n", PROGRAM_NAME, event.latitude, event.longitude); ierr = cps_crust1_getCrust1ForHerrmann(precompute.crustDir, false, event.latitude, event.longitude, &event.latitude, &event.longitude, 1, &vmodel, &recmod); cps_utils_freeVmodelStruct(&recmod); } else { printf("%s: Model is not set\n", PROGRAM_NAME); ierr = 1; goto FINISH_EARLY; } // Initialize the archive - remove NULL terminator modelName = string_strip(NULL, vmodel.title); printf("%s: Initializing archive file %s with model %s\n", PROGRAM_NAME, precompute.hspecArchiveFile, modelName); ierr = prepmt_hspec96_initializeArchive(precompute.hspecArchiveFile, modelName, ndeps, depths, ndists, precompute.dists); if (ierr != 0) { printf("%s: Failed to initialize archive\n", PROGRAM_NAME); goto FINISH_EARLY; } free(precompute.depths); free(precompute.dists); } FINISH_EARLY:; MPI_Barrier(MPI_COMM_WORLD); MPI_Bcast(&ierr, 1, MPI_INTEGER, master, MPI_COMM_WORLD); if (ierr != 0){goto FINISH;} cps_broadcast_vmodelStruct(MPI_COMM_WORLD, master, &vmodel); cps_broadcast_hprep96ParmsStruct(MPI_COMM_WORLD, master, &hprepParms); cps_broadcast_hspec96ParmsStruct(MPI_COMM_WORLD, master, &hspecParms); cps_broadcast_hpulse96ParmsStruct(MPI_COMM_WORLD, master, &hpulseParms); MPI_Bcast(&ndists, 1, MPI_INTEGER, master, MPI_COMM_WORLD); MPI_Bcast(&ndeps, 1, MPI_INTEGER, master, MPI_COMM_WORLD); MPI_Bcast(&npts, 1, MPI_INTEGER, master, MPI_COMM_WORLD); MPI_Bcast(&dt, 1, MPI_DOUBLE, master, MPI_COMM_WORLD); // initialize receiver information nwaves = ndists*ndeps; depthr = (double *) calloc((size_t) nwaves, sizeof(double)); if (myid != master) { depths = (double *) calloc((size_t) nwaves, sizeof(double)); r = (double *) calloc((size_t) nwaves, sizeof(double)); } tshift = (double *) calloc((size_t) nwaves, sizeof(double)); vred = (double *) calloc((size_t) nwaves, sizeof(double)); MPI_Bcast(depths, nwaves, MPI_DOUBLE, master, MPI_COMM_WORLD); MPI_Bcast(r, nwaves, MPI_DOUBLE, master, MPI_COMM_WORLD); // set the receiver distances //r[0] = 55.597; //111.195; //r[1] = 111.195; //r[2] = 166.792; //depths[0] = 7.0; //for (idep=0; idep<ndeps; idep++) //{ // for (idist=0; idist<ndists; idist++) // { // k = idist*ndeps + idep; // r[k] = 55.597*(double) (idist + 1); // depths[k] = (double) idep; // } //} /* printf("premature end\n"); MPI_Finalize(); return 0; */ // call hspec zresp = hspec96_mpi_interface(MPI_COMM_WORLD, nwaves, npts, dt, r, tshift, vred, depthr, depths, hprepParms, hspecParms, vmodel, &ierr); MPI_Barrier(MPI_COMM_WORLD); if (ierr != 0) { printf("Error calling hspec\n"); goto FINISH; } // convolve STF and convert back to time domain grns = hpulse96_mpi_interface(MPI_COMM_WORLD, nwaves, hpulseParms, zresp, &ierr); if (ierr != 0) { printf("Error computing greens fns\n"); goto FINISH; } // dump the results if (myid == master) { printf("Writing results...\n"); h5fl = H5Fopen(precompute.hspecArchiveFile, H5F_ACC_RDWR, H5P_DEFAULT); sac = (struct sacData_struct *) calloc(10, sizeof(struct sacData_struct)); k = 0; //for (idist=0; idist<ndists; idist++) for (idep=0; idep<ndeps; idep++) { memset(fname, 0, PATH_MAX*sizeof(char)); sprintf(fname, "dump/depth_%d", idep); os_makedirs(fname); memset(groupName, 0, 512*sizeof(char)); sprintf(groupName, "/%s/Depth_%d", modelName, idep); groupID = H5Gopen(h5fl, groupName, H5P_DEFAULT); //for (idep=0; idep<ndeps; idep++) for (idist=0; idist<ndists; idist++) { k = idist*ndeps + idep; grns2sac(grns[k], sac); memset(fname, 0, PATH_MAX*sizeof(char)); sprintf(fname, "dump/depth_%d/%04d01ZDD.SAC", idep, idist+1); sacio_writeTimeSeriesFile(fname, sac[0]); sprintf(fname, "dump/depth_%d/%04d02RDD.SAC", idep, idist+1); sacio_writeTimeSeriesFile(fname, sac[1]); sprintf(fname, "dump/depth_%d/%04d03ZDS.SAC", idep, idist+1); sacio_writeTimeSeriesFile(fname, sac[2]); sprintf(fname, "dump/depth_%d/%04d04RDS.SAC", idep, idist+1); sacio_writeTimeSeriesFile(fname, sac[3]); sprintf(fname, "dump/depth_%d/%04d05TDS.SAC", idep, idist+1); sacio_writeTimeSeriesFile(fname, sac[4]); sprintf(fname, "dump/depth_%d/%04d06ZSS.SAC", idep, idist+1); sacio_writeTimeSeriesFile(fname, sac[5]); sprintf(fname, "dump/depth_%d/%04d07RSS.SAC", idep, idist+1); sacio_writeTimeSeriesFile(fname, sac[6]); sprintf(fname, "dump/depth_%d/%04d08TSS.SAC", idep, idist+1); sacio_writeTimeSeriesFile(fname, sac[7]); sprintf(fname, "dump/depth_%d/%04d09ZEX.SAC", idep, idist+1); sacio_writeTimeSeriesFile(fname, sac[8]); sprintf(fname, "dump/depth_%d/%04d10REX.SAC", idep, idist+1); sacio_writeTimeSeriesFile(fname, sac[9]); // Dump to the H5 archive and release memory for (l=0; l<10; l++) { // Rescale to unit magnitude cblas_dscal(sac[l].npts, xscal, sac[l].data, 1); sprintf(fname, "Greens_%s_%d", cfaults[l], idist); sacioh5_writeTimeSeries2(fname, groupID, sac[l]); sacio_free(&sac[l]); } //break; } H5Gclose(groupID); //break; } if (sac != NULL){free(sac);} H5Fclose(h5fl); printf("%s: Finishing program\n", PROGRAM_NAME); } MPI_Barrier(MPI_COMM_WORLD); FINISH:; if (grns != NULL) { for (k=0; k<nwaves; k++) { cps_utils_freeHwaveGreensStruct(&grns[k]); } free(grns); grns = NULL; } if (zresp != NULL) { for (k=0; k<nwaves; k++) { cps_utils_freeHpulse96DataStruct(&zresp[k]); } free(zresp); zresp = NULL; } // release memory memory_free8c(&modelName); free(depthr); free(depths); free(r); free(tshift); free(vred); cps_utils_freeHpulse96ParmsStruct(&hpulseParms); cps_utils_freeVmodelStruct(&vmodel); MPI_Finalize(); return 0; } //============================================================================// int prepmt_hspec96_initializeArchive( const char *archiveName, const char *model, const int ndepths, const double *__restrict__ depths, const int ngcarcs, const double *__restrict__ gcarcs) { char modelName[512], depthName[512]; //, varName[512]; hid_t h5fl, dataSet, dataSpace, depthGroup, modelGroup; hsize_t dims[1]; int idep; //------------------------------------------------------------------------// h5fl = H5Fcreate(archiveName, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT); memset(modelName, 0, 512*sizeof(char)); sprintf(modelName, "/%s", model); printf("%s: Initializing model: %s\n", __func__, modelName); modelGroup = H5Gcreate2(h5fl, modelName, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); // write the depths and distances dims[0] = (hsize_t) ndepths; dataSpace = H5Screate_simple(1, dims, NULL); dataSet = H5Dcreate2(modelGroup, "Depths\0", H5T_NATIVE_DOUBLE, dataSpace, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); H5Dwrite(dataSet, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, depths); H5Dclose(dataSet); H5Sclose(dataSpace); // Write the distances dims[0] = (hsize_t) ngcarcs; dataSpace = H5Screate_simple(1, dims, NULL); dataSet = H5Dcreate2(modelGroup, "Distances\0", H5T_NATIVE_DOUBLE, dataSpace, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); H5Dwrite(dataSet, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, gcarcs); H5Dclose(dataSet); H5Sclose(dataSpace); // Create the depths groups for (idep=0; idep<ndepths; idep++) { memset(depthName, 0, 512*sizeof(char)); sprintf(depthName, "%s/Depth_%d", modelName, idep); depthGroup = H5Gcreate2(h5fl, depthName, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); H5Gclose(depthGroup); } H5Gclose(modelGroup); H5Fclose(h5fl); return 0; } //============================================================================// int prepmt_hspec96_readParameters(const char *iniFile, const char *section, struct precompute_struct *precompute) { const char *fcnm = "prepmt_hspec96_readParameters\0"; FILE *dfl; const char *s; char *dirName, cline[256], vname[128]; double depth0, depth1, dist0, dist1; int i, ierr; dictionary *ini; memset(precompute, 0, sizeof(struct precompute_struct)); if (!os_path_isfile(iniFile)) { printf("%s: ini file: %s does not exist\n", fcnm, iniFile); return -1; } ini = iniparser_load(iniFile); if (ini == NULL) { printf("%s: Cannot parse ini file\n", fcnm); return -1; } memset(vname, 0, 128*sizeof(char)); sprintf(vname, "%s:ndepths", section); precompute->ndepths = iniparser_getint(ini, vname, 1); memset(vname, 0, 128*sizeof(char)); sprintf(vname, "%s:depthMin", section); depth0 = iniparser_getdouble(ini, vname, 1.0); memset(vname, 0, 128*sizeof(char)); sprintf(vname, "%s:depthMax", section); depth1 = iniparser_getdouble(ini, vname, 1.0); memset(vname, 0, 128*sizeof(char)); sprintf(vname, "%s:ndists", section); precompute->ndists = iniparser_getint(ini, vname, 1); memset(vname, 0, 128*sizeof(char)); sprintf(vname, "%s:minDistance", section); dist0 = iniparser_getdouble(ini, vname, 1.0); memset(vname, 0, 128*sizeof(char)); sprintf(vname, "%s:maxDistance", section); dist1 = iniparser_getdouble(ini, vname, 1.0); memset(vname, 0, 128*sizeof(char)); sprintf(vname, "%s:dtHspec", section); precompute->dt = iniparser_getdouble(ini, vname, 1.0); memset(vname, 0, 128*sizeof(char)); sprintf(vname, "%s:nptsHspec", section); precompute->npts = iniparser_getint(ini, vname, 1024); memset(vname, 0, 128*sizeof(char)); sprintf(vname, "%s:luseCrust1", section); precompute->luseCrust = iniparser_getboolean(ini, vname, 0); memset(vname, 0, 128*sizeof(char)); sprintf(vname, "%s:luseSourceModel", section); precompute->luseSourceMod = iniparser_getboolean(ini, vname, 1); memset(vname, 0, 128*sizeof(char)); sprintf(vname, "%s:sourceModel", section); s = iniparser_getstring(ini, vname, NULL); if (s != NULL) { strcpy(precompute->sourceModel, s); if (!os_path_isfile(precompute->sourceModel) && precompute->luseSourceMod) { printf("%s: Source model doesn't %s exist\n", fcnm, s); precompute->luseSourceMod = false; } } else { precompute->luseSourceMod = false; } memset(vname, 0, 128*sizeof(char)); sprintf(vname, "%s:hspecArchiveFile", section); s = iniparser_getstring(ini, vname, "hspecFFgreens.h5"); dirName = os_dirname(s, &ierr); if (!os_path_isdir(dirName)) { ierr = os_makedirs(dirName); if (ierr != 0) { printf("%s: Failed to make output directory: %s\n", fcnm, dirName); return -1; } } memory_free8c(&dirName); strcpy(precompute->hspecArchiveFile, s); //memset(vname, 0, 128*sizeof(char)); //sprintf(vname, "%s:modelIdentifier", section); //s = iniparser_getstring(ini, vname, "UNKNOWN"); //strcpy(precompute->modelIdentifer, s); memset(vname, 0, 128*sizeof(char)); sprintf(vname, "%s:crustDir", section); s = iniparser_getstring(ini, vname, CPS_DEFAULT_CRUST1_DIRECTORY); if (s != NULL) { strcpy(precompute->crustDir, s); if (!os_path_isdir(precompute->crustDir) && precompute->luseCrust) { printf("%s: crust1.0 directory %s doesn't exist\n", fcnm, s); precompute->luseCrust = false; } } else { precompute->luseCrust = false; } memset(vname, 0, 128*sizeof(char)); sprintf(vname, "%s:luseDistanceTable", section); precompute->luseDistanceTable = iniparser_getboolean(ini, vname, false); if (precompute->luseDistanceTable) { memset(vname, 0, 128*sizeof(char)); sprintf(vname, "%s:hspecDistanceFile", section); s = iniparser_getstring(ini, vname, NULL); if (!os_path_isfile(s)) { printf("%s: files %s doesn't exist\n", fcnm, s); return -1; } strcpy(precompute->hspecDistanceFile, s); dfl = fopen(s, "r"); memset(cline, 0, 256*sizeof(char)); fgets(cline, 256, dfl); memset(cline, 0, 256*sizeof(char)); fgets(cline, 256, dfl); precompute->ndists = atoi(cline); if (precompute->ndists < 1) { printf("%s: Invalid number of distances\n", fcnm); return -1; } precompute->dists = (double *) calloc((size_t) precompute->ndists, sizeof(double)); for (i=0; i<precompute->ndists; i++) { memset(cline, 0, 256*sizeof(char)); if (fgets(cline, 256, dfl) == NULL) { printf("%s: premature end of distance file\n", fcnm); return -1; } precompute->dists[i] = atof(cline); } fclose(dfl); } else { precompute->dists = (double *) calloc((size_t) precompute->ndists, sizeof(double)); ierr = array_linspace64f_work(dist0, dist1, precompute->ndists, precompute->dists); } // depths precompute->depths = (double *) calloc((size_t) precompute->ndepths, sizeof(double)); ierr = array_linspace64f_work(depth0, depth1, precompute->ndepths, precompute->depths); iniparser_freedict(ini); return ierr; } //============================================================================// int prepmt_hspec96_readHspec96Parameters( const char *iniFile, struct hprep96_parms_struct *hprepParms, struct hspec96_parms_struct *hspecParms, struct hpulse96_parms_struct *hpulseParms) { const char *fcnm = "prepmt_hspec96_readHspec96Parameters\0"; int ierr; cps_setHprep96Defaults(hprepParms); cps_setHspec96Defaults(hspecParms); ierr = prepmt_hpulse96_readHpulse96Parameters(iniFile, "hpulse96\0", hpulseParms); if (ierr != 0) { printf("%s: Error reading hpulse parameters\n", fcnm); } return ierr; } //============================================================================// /*! * @brief Parses the command line arguments for the ini file. * * @param[in] argc Number of arguments input to the program. * @param[in] argv Command line arguments. * * @param[out] iniFile If the result is 0 then this is the ini file. * * @result 0 indicates success. \n * -1 indicates the user inquired about the usage. \n * -2 indicates the command line argument is invalid. * * @author Ben Baker, ISTI * */ static int parseArguments(int argc, char *argv[], char iniFile[PATH_MAX]) { bool linFile; linFile = false; memset(iniFile, 0, PATH_MAX*sizeof(char)); while (true) { static struct option longOptions[] = { {"help", no_argument, 0, '?'}, {"help", no_argument, 0, 'h'}, {"ini_file", required_argument, 0, 'i'}, {"section", required_argument, 0, 's'}, {0, 0, 0, 0} }; int c, optionIndex; c = getopt_long(argc, argv, "?hi:", longOptions, &optionIndex); if (c ==-1){break;} if (c == 'i') { strcpy(iniFile, (const char *) optarg); linFile = true; } else if (c == 'h' || c == '?') { printUsage(); return -2; } else { printf("%s: Unknown options: %s\n", PROGRAM_NAME, argv[optionIndex]); } } if (!linFile) { printf("%s: Error must specify ini file\n\n", PROGRAM_NAME); printUsage(); return -1; } else { if (!os_path_isfile(iniFile)) { printf("%s: Error - ini file: %s does not exist\n", PROGRAM_NAME, iniFile); return EXIT_FAILURE; } } return 0; } //============================================================================// static void printUsage(void) { printf("Usage:\n %s -i iniFile\n", PROGRAM_NAME); printf("or\n"); printf(" mpirun -np nProcessors %s -i iniFile\n", PROGRAM_NAME); printf("Required arguments:\n"); printf(" -i ini_file specifies the initialization file\n"); printf("Optional arguments:\n"); printf(" -h displays this message\n"); printf(" -np Number of computer processors to use\n"); return; } //============================================================================// static void grns2sac(const struct hwave_greens_struct grns, struct sacData_struct sac[10]) { const char *kcmpnm[10] = {"ZDD\0", "RDD\0", "ZDS\0", "RDS\0", "TDS\0", "ZSS\0", "RSS\0", "TSS\0", "ZEX\0", "REX\0"}; double cmpinc, cmpaz; int i, k; bool lsh; for (k=0; k<10; k++) { memset(&sac[k], 0, sizeof(struct sacData_struct)); sacio_setDefaultHeader(&sac[k].header); lsh = false; sac[k].header.npts = grns.npts; //sac[k].header.b = grns.b; sac[k].npts = grns.npts; sac[k].header.b = grns.t0; sac[k].header.e = grns.t0 + (double) (grns.npts - 1)*grns.dt; sac[k].header.delta = grns.dt; sac[k].header.dist = grns.dist; sac[k].header.evdp = grns.evdep; sac[k].header.stel = grns.stelel; sac[k].header.gcarc = grns.dist/111.195; sac[k].header.o =-grns.t0; strcpy(sac[k].header.kevnm, "SYNTHETIC"); strcpy(sac[k].header.ko, "O\0"); sac[k].header.a = grns.timep; strcpy(sac[k].header.ka, "P\0"); sac[k].header.az = 0.0; sac[k].header.baz = 180.0; sac[k].header.lcalda = 0; sac[k].header.norid = 0; sac[k].header.nevid = 0; sac[k].header.nzyear = 1970; sac[k].header.nzjday = 1; sac[k].header.nzhour = 0; sac[k].header.nzmin = 0; sac[k].header.nzsec = 0; sac[k].header.nzmsec = 0; sac[k].header.lhaveHeader = true; strcpy(sac[k].header.kcmpnm, kcmpnm[k]); sac[k].data = (double *) calloc((size_t) grns.npts, sizeof(double)); cmpaz = 0.0; cmpinc = 0.0; if (k == 0) { for (i=0; i<grns.npts; i++){sac[k].data[i] = grns.zdd[i];} } else if (k == 1) { for (i=0; i<grns.npts; i++){sac[k].data[i] = grns.rdd[i];} cmpinc = 90.0; } else if (k == 2) { for (i=0; i<grns.npts; i++){sac[k].data[i] = grns.zds[i];} } else if (k == 3) { for (i=0; i<grns.npts; i++){sac[k].data[i] = grns.rds[i];} cmpinc = 90.0; } else if (k == 4) { for (i=0; i<grns.npts; i++){sac[k].data[i] = grns.tds[i];} lsh = true; cmpaz = 90.0; cmpinc = 90.0; } else if (k == 5) { for (i=0; i<grns.npts; i++){sac[k].data[i] = grns.zss[i];} } else if (k == 6) { for (i=0; i<grns.npts; i++){sac[k].data[i] = grns.rss[i];} cmpinc = 90.0; } else if (k == 7) { for (i=0; i<grns.npts; i++){sac[k].data[i] = grns.tss[i];} lsh = true; cmpaz = 90.0; cmpinc = 90.0; } else if (k == 8) { for (i=0; i<grns.npts; i++){sac[k].data[i] = grns.zex[i];} } else if (k == 9) { for (i=0; i<grns.npts; i++){sac[k].data[i] = grns.rex[i];} cmpinc = 90.0; } if (lsh) { sac[k].header.t1 = grns.timesh; strcpy(sac[k].header.kt0, "SH\0"); } else { sac[k].header.t1 = grns.timesv; strcpy(sac[k].header.kt0, "SV\0"); } sac[k].header.cmpaz = cmpaz; sac[k].header.cmpinc = cmpinc; } return; }
{ "alphanum_fraction": 0.5465426441, "avg_line_length": 36.1905940594, "ext": "c", "hexsha": "89b51f096ed808feef64a46baf7a4547816ae913", "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": "prepmt/hspec96.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": "prepmt/hspec96.c", "max_line_length": 80, "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": "prepmt/hspec96.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 8120, "size": 29242 }
#include <stdio.h> #include <stdlib.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_statistics_double.h> #include <math.h> #include "tz_error.h" #include "tz_constant.h" #include "tz_voxel_linked_list.h" #include "tz_stack_sampling.h" #include "tz_voxel_graphics.h" #include "tz_neurotrace.h" #include "tz_stack_math.h" #include "tz_stack_utils.h" #include "tz_objdetect.h" #include "tz_voxeltrans.h" #include "tz_stack_stat.h" #include "tz_stack_draw.h" #include "tz_geo3d_vector.h" #include "tz_stack_bwmorph.h" #include "tz_stack_bwdist.h" INIT_EXCEPTION_MAIN(e) int main(int argc, char* argv[]) { Stack *seedimg = Read_Stack("../data/fly_neuron_objseed.tif"); Object_3d_List *objs = Stack_Find_Object(seedimg, 1, 0); Stack *stack2 = NULL; Object_3d *obj = NULL; stack2 = NULL; Object_3d_List *objs2 = NULL; while (objs != NULL) { stack2 = Read_Stack("../data/fly_neuron_bundle.tif"); obj = Stack_Grow_Object(stack2, 1, objs->data->voxels[0]); if (obj->size > 1000) { if (objs2 == NULL) { objs2 = Object_3d_List_New(); objs2->data = obj; } else { Object_3d_List_Add(&objs2, obj); Print_Object_3d_Info(obj); } } else { Kill_Object_3d(obj); } objs = objs->next; } Print_Object_3d_List_Compact(objs2); Stack *sig = Read_Stack("../data/fly_neuron.tif"); //Stack *sig = Read_Stack("../data/fly_neuron.tif"); Stack *stack = Translate_Stack(sig, COLOR, 0); //Stack *stack = Read_Stack("../data/blobimg2.tif"); Stack *traced = Make_Stack(GREY, sig->width, sig->height, sig->depth); One_Stack(traced); Stack *soma = Read_Stack("../data/fly_neuron_soma.tif"); Stack_Threshold(soma, 1); Stack_Binarize(soma); Stack_Not(soma, soma); Stack_And(traced, soma, traced); Kill_Stack(soma); Neurochain *chain = New_Neurochain(); Neurochain *chain2 = NULL; while (objs2 != NULL) { if (objs2->data->size > 100) { Set_Neuroseg(&(chain->seg), 5, 5, 12, -TZ_PI_2, 0.0); Set_Position(chain->position, objs2->data->voxels[0][0], objs2->data->voxels[0][1], objs2->data->voxels[0][2]); #if 1 Try { Fit_Neuroseg(sig, &(chain->seg), chain->position, TRUE); } Catch(e) { TZ_ERROR(e); } #endif #if 1 Try { chain2 = Trace_Neuron(sig, chain, BOTH, traced); } Catch(e) { TZ_ERROR(e); } #endif Neurochain_Erase(traced, chain2); chain = Extend_Neurochain(chain2); } objs2 = objs2->next; } Neurochain_Label(stack, Neurochain_Head(chain)); Write_Stack("../data/fly_neuron_trace.tif", stack); return 0; }
{ "alphanum_fraction": 0.660472319, "avg_line_length": 25.0776699029, "ext": "c", "hexsha": "f479202b7fc074057bd5726e1902c767872f668d", "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": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzhmark/vaa3d_tools", "max_forks_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/trace_fly_neuron.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_issues_repo_issues_event_max_datetime": "2016-12-03T05:33:13.000Z", "max_issues_repo_issues_event_min_datetime": "2016-12-03T05:33:13.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzhmark/vaa3d_tools", "max_issues_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/trace_fly_neuron.c", "max_line_length": 72, "max_stars_count": 1, "max_stars_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zzhmark/vaa3d_tools", "max_stars_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/trace_fly_neuron.c", "max_stars_repo_stars_event_max_datetime": "2021-12-27T19:14:03.000Z", "max_stars_repo_stars_event_min_datetime": "2021-12-27T19:14:03.000Z", "num_tokens": 816, "size": 2583 }
#ifndef __UTILS_UTILS_H_INCLUDED__ #include <iostream> #include <vector> #include <Eigen/Dense> #include <gsl/gsl> #include <numeric> #include <random> #define __UTILS_UTILS_H_INCLUDED__ template<typename Matrix> void removeRow(Matrix& matrix, gsl::index rowToRemove) { gsl::index numRows = matrix.rows()-1; gsl::index numCols = matrix.cols(); if( rowToRemove < numRows ) matrix.block(rowToRemove,0,numRows-rowToRemove,numCols) = matrix.block(rowToRemove+1,0,numRows-rowToRemove,numCols).eval(); matrix.conservativeResize(numRows,numCols); } template<typename Matrix> void removeColumn(Matrix& matrix, gsl::index colToRemove) { gsl::index numRows = matrix.rows(); gsl::index numCols = matrix.cols()-1; if( colToRemove < numCols ) matrix.block(0,colToRemove,numRows,numCols-colToRemove) = matrix.block(0,colToRemove+1,numRows,numCols-colToRemove).eval(); matrix.conservativeResize(numRows,numCols); } template <typename T> void select(std::vector<T>& result, const std::vector<T>& in, const std::vector<typename std::vector<T>::size_type>& s) { result.reserve(s.size()); std::transform(s.begin(), s.end(), std::back_inserter(result), [&in](typename std::vector<T>::size_type idx) { return in.at(idx); }); } std::tuple<std::vector<gsl::index>,std::vector<gsl::index> > TrainTestSplit(gsl::index nrows,double testRatio=0.3){ assert(testRatio>=0 && testRatio<=1); gsl::index ntest = (gsl::index) nrows*(testRatio); gsl::index ntrain = nrows - ntest; std::vector<int> idx(nrows); std::iota(idx.begin(), idx.end(), 0); std::vector<gsl::index> trainIdx, testIdx; trainIdx.resize(ntrain); testIdx.resize(ntest); std::sample(idx.begin(), idx.end(), std::back_inserter(testIdx), ntest, std::mt19937{std::random_device{}()}); std::sort(testIdx.begin(),testIdx.end()); std::set_difference(idx.begin(), idx.end(), trainIdx.begin(), trainIdx.end(), std::inserter(testIdx, testIdx.begin())); return {trainIdx,testIdx}; } std::tuple<std::vector<gsl::index>,std::vector<gsl::index> > TrainTestSplit(std::vector<gsl::index> inputIdx,double testRatio=0.3){ assert(testRatio>=0 && testRatio<=1); gsl::index nrows = inputIdx.size(); gsl::index ntest = (gsl::index) nrows*(testRatio); gsl::index ntrain = nrows - ntest; std::vector<int> idx(nrows); std::iota(idx.begin(), idx.end(), 0); std::vector<gsl::index> trainIdx, testIdx; trainIdx.resize(ntrain); testIdx.resize(ntest); std::sample(inputIdx.begin(), inputIdx.end(), std::back_inserter(testIdx), ntest, std::mt19937{std::random_device{}()}); std::sort(testIdx.begin(),testIdx.end()); std::sort(inputIdx.begin(),inputIdx.end()); std::set_difference(inputIdx.begin(), inputIdx.end(), trainIdx.begin(), trainIdx.end(), std::inserter(testIdx, testIdx.begin())); return {trainIdx,testIdx}; } template<typename T> std::vector<T> linspace(T start_in, T end_in, int num_in) { std::vector<T> linspaced; double start = static_cast<double>(start_in); double end = static_cast<double>(end_in); double num = static_cast<double>(num_in); if (num == 0) { return linspaced; } if (num == 1) { linspaced.push_back(start); return linspaced; } double delta = (end - start) / (num - 1); for(int i=0; i < num-1; ++i) { linspaced.push_back(start + delta * i); } linspaced.push_back(end); return linspaced; } template<typename T> void print_vector(std::vector<T> vec) { std::cout << "size: " << vec.size() << std::endl; for (T & d : vec) std::cout << d << " "; std::cout << std::endl; } #endif
{ "alphanum_fraction": 0.6391941392, "avg_line_length": 33.2347826087, "ext": "h", "hexsha": "e984862f2f063253af01a5964f213738856b60f5", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-04-13T05:56:38.000Z", "max_forks_repo_forks_event_min_datetime": "2021-04-13T05:56:38.000Z", "max_forks_repo_head_hexsha": "ea93704782e6c66f6bcf65362c957d719e25b074", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zhxinyu/cosan", "max_forks_repo_path": "cosan/utils/utils.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "ea93704782e6c66f6bcf65362c957d719e25b074", "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": "zhxinyu/cosan", "max_issues_repo_path": "cosan/utils/utils.h", "max_line_length": 131, "max_stars_count": null, "max_stars_repo_head_hexsha": "ea93704782e6c66f6bcf65362c957d719e25b074", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zhxinyu/cosan", "max_stars_repo_path": "cosan/utils/utils.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1011, "size": 3822 }
#ifndef BCT_TEST_H #define BCT_TEST_H #include <bct/bct.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <octave/oct.h> #include <vector> namespace bct_test { Matrix from_gsl(const gsl_vector*, int = 0); Matrix from_gsl(const gsl_matrix*, int = 0, int = 0); NDArray from_gsl(const std::vector<gsl_matrix*>, int = 0); gsl_vector* to_gslv(const Matrix, int = 0); gsl_matrix* to_gslm(const Matrix, int = 0, int = 0); std::vector<gsl_matrix*> to_gsl(const NDArray, int = 0); } #include "bct_test.cpp" #define MATRIX_TO_SCALAR_FUNCTION(function_name) \ DEFUN_DLD(function_name##_cpp, args, , "Wrapper for C++ function.") { \ if (args.length() == 0) { \ return octave_value_list(); \ } \ Matrix m = args(0).matrix_value(); \ if (!error_state) { \ gsl_matrix* m_gsl = bct_test::to_gslm(m); \ octave_value ret = octave_value(bct::function_name(m_gsl)); \ gsl_matrix_free(m_gsl); \ return ret; \ } else { \ return octave_value_list(); \ } \ } #define MATRIX_TO_VECTOR_FUNCTION(function_name) \ DEFUN_DLD(function_name##_cpp, args, , "Wrapper for C++ function.") { \ if (args.length() == 0) { \ return octave_value_list(); \ } \ Matrix m = args(0).matrix_value(); \ if (!error_state) { \ gsl_matrix* m_gsl = bct_test::to_gslm(m); \ gsl_vector* ret_gsl = bct::function_name(m_gsl); \ octave_value ret = bct_test::from_gsl(ret_gsl); \ gsl_matrix_free(m_gsl); \ gsl_vector_free(ret_gsl); \ return ret; \ } else { \ return octave_value_list(); \ } \ } #define MATRIX_TO_MATRIX_FUNCTION(function_name) \ DEFUN_DLD(function_name##_cpp, args, , "Wrapper for C++ function.") { \ if (args.length() == 0) { \ return octave_value_list(); \ } \ Matrix m = args(0).matrix_value(); \ if (!error_state) { \ gsl_matrix* m_gsl = bct_test::to_gslm(m); \ gsl_matrix* ret_gsl = bct::function_name(m_gsl); \ octave_value ret = bct_test::from_gsl(ret_gsl); \ gsl_matrix_free(m_gsl); \ gsl_matrix_free(ret_gsl); \ return ret; \ } else { \ return octave_value_list(); \ } \ } #endif
{ "alphanum_fraction": 0.6620392532, "avg_line_length": 28.2297297297, "ext": "h", "hexsha": "d2ef78d7714381bb7ff5a828ee6cd436ec63152a", "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": "test/bct_test.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": "test/bct_test.h", "max_line_length": 72, "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": "test/bct_test.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 671, "size": 2089 }
/* * Copyright (c) 2010-2018 The University of Tennessee and The University * of Tennessee Research Foundation. All rights * reserved. * Copyright (c) 2013 Inria. All rights reserved. * $COPYRIGHT * * @precisions normal z -> s d c * */ #include "dplasma.h" #include <math.h> #include <lapacke.h> #include "parsec/data_dist/matrix/two_dim_rectangle_cyclic.h" /** ******************************************************************************* * * @ingroup dplasma_complex64_check * * check_zpotrf - Check the correctness of the Cholesky factorization computed * Cholesky functions with the following criteria: * * \f[ ||L'L-A||_oo/(||A||_oo.N.eps) < 60. \f] * * or * * \f[ ||UU'-A||_oo/(||A||_oo.N.eps) < 60. \f] * * where A is the original matrix, and L, or U, the result of the Cholesky * factorization. * ******************************************************************************* * * @param[in,out] parsec * The parsec context of the application that will run the operation. * * @param[in] loud * The level of verbosity required. * * @param[in] uplo * = PlasmaUpper: Upper triangle of A and A0 are referenced; * = PlasmaLower: Lower triangle of A and A0 are referenced. * * @param[in] A * Descriptor of the distributed matrix A result of the Cholesky * factorization. Holds L or U. If uplo == PlasmaUpper, the only the * upper part is referenced, otherwise if uplo == PlasmaLower, the * lower part is referenced. * * @param[in] A0 * Descriptor of the original distributed matrix A before * factorization. If uplo == PlasmaUpper, the only the upper part is * referenced, otherwise if uplo == PlasmaLower, the lower part is * referenced. * ******************************************************************************* * * @return * \retval 1, if the result is incorrect * \retval 0, if the result is correct * ******************************************************************************/ int check_zpotrf( parsec_context_t *parsec, int loud, PLASMA_enum uplo, parsec_tiled_matrix_dc_t *A, parsec_tiled_matrix_dc_t *A0 ) { two_dim_block_cyclic_t *twodA = (two_dim_block_cyclic_t *)A0; two_dim_block_cyclic_t LLt; int info_factorization; double Rnorm = 0.0; double Anorm = 0.0; double result = 0.0; int M = A->m; int N = A->n; double eps = LAPACKE_dlamch_work('e'); PLASMA_enum side; two_dim_block_cyclic_init(&LLt, matrix_ComplexDouble, matrix_Tile, A->super.nodes, twodA->grid.rank, A->mb, A->nb, M, N, 0, 0, M, N, twodA->grid.strows, twodA->grid.stcols, twodA->grid.rows); LLt.mat = parsec_data_allocate((size_t)LLt.super.nb_local_tiles * (size_t)LLt.super.bsiz * (size_t)parsec_datadist_getsizeoftype(LLt.super.mtype)); dplasma_zlaset( parsec, PlasmaUpperLower, 0., 0.,(parsec_tiled_matrix_dc_t *)&LLt ); dplasma_zlacpy( parsec, uplo, A, (parsec_tiled_matrix_dc_t *)&LLt ); /* Compute LL' or U'U */ side = (uplo == PlasmaUpper ) ? PlasmaLeft : PlasmaRight; dplasma_ztrmm( parsec, side, uplo, PlasmaConjTrans, PlasmaNonUnit, 1.0, A, (parsec_tiled_matrix_dc_t*)&LLt); /* compute LL' - A or U'U - A */ dplasma_ztradd( parsec, uplo, PlasmaNoTrans, -1.0, A0, 1., (parsec_tiled_matrix_dc_t*)&LLt); Anorm = dplasma_zlanhe(parsec, PlasmaInfNorm, uplo, A0); Rnorm = dplasma_zlanhe(parsec, PlasmaInfNorm, uplo, (parsec_tiled_matrix_dc_t*)&LLt); result = Rnorm / ( Anorm * N * eps ) ; if ( loud > 2 ) { printf("============\n"); printf("Checking the Cholesky factorization \n"); if ( loud > 3 ) printf( "-- ||A||_oo = %e, ||L'L-A||_oo = %e\n", Anorm, Rnorm ); printf("-- ||L'L-A||_oo/(||A||_oo.N.eps) = %e \n", result); } if ( isnan(Rnorm) || isinf(Rnorm) || isnan(result) || isinf(result) || (result > 60.0) ) { if( loud ) printf("-- Factorization is suspicious ! \n"); info_factorization = 1; } else { if( loud ) printf("-- Factorization is CORRECT ! \n"); info_factorization = 0; } parsec_data_free(LLt.mat); LLt.mat = NULL; parsec_tiled_matrix_dc_destroy( (parsec_tiled_matrix_dc_t*)&LLt); return info_factorization; } /** ******************************************************************************* * * @ingroup dplasma_complex64_check * * check_zaxmb - Returns the result of the following test * * \f[ (|| A x - b ||_oo / ((||A||_oo * ||x||_oo + ||b||_oo) * N * eps) ) < 60. \f] * * where A is the original matrix, b the original right hand side, and x the * solution computed through any factorization. * ******************************************************************************* * * @param[in,out] parsec * The parsec context of the application that will run the operation. * * @param[in] loud * The level of verbosity required. * * @param[in] uplo * = PlasmaUpper: Upper triangle of A is referenced; * = PlasmaLower: Lower triangle of A is referenced. * * @param[in] A * Descriptor of the distributed matrix A result of the Cholesky * factorization. Holds L or U. If uplo == PlasmaUpper, the only the * upper part is referenced, otherwise if uplo == PlasmaLower, the * lower part is referenced. * * @param[in,out] b * Descriptor of the original distributed right hand side b. * On exit, b is overwritten by (b - A * x). * * @param[in] x * Descriptor of the solution to the problem, x. * ******************************************************************************* * * @return * \retval 1, if the result is incorrect * \retval 0, if the result is correct * ******************************************************************************/ int check_zaxmb( parsec_context_t *parsec, int loud, PLASMA_enum uplo, parsec_tiled_matrix_dc_t *A, parsec_tiled_matrix_dc_t *b, parsec_tiled_matrix_dc_t *x ) { int info_solution; double Rnorm = 0.0; double Anorm = 0.0; double Bnorm = 0.0; double Xnorm, result; int N = b->m; double eps = LAPACKE_dlamch_work('e'); Anorm = dplasma_zlanhe(parsec, PlasmaInfNorm, uplo, A); Bnorm = dplasma_zlange(parsec, PlasmaInfNorm, b); Xnorm = dplasma_zlange(parsec, PlasmaInfNorm, x); /* Compute b - A*x */ dplasma_zhemm( parsec, PlasmaLeft, uplo, -1.0, A, x, 1.0, b); Rnorm = dplasma_zlange(parsec, PlasmaInfNorm, b); result = Rnorm / ( ( Anorm * Xnorm + Bnorm ) * N * eps ) ; if ( loud > 2 ) { printf("============\n"); printf("Checking the Residual of the solution \n"); if ( loud > 3 ) printf( "-- ||A||_oo = %e, ||X||_oo = %e, ||B||_oo= %e, ||A X - B||_oo = %e\n", Anorm, Xnorm, Bnorm, Rnorm ); printf("-- ||Ax-B||_oo/((||A||_oo||x||_oo+||B||_oo).N.eps) = %e \n", result); } if ( isnan(Xnorm) || isinf(Xnorm) || isnan(result) || isinf(result) || (result > 60.0) ) { if( loud ) printf("-- Solution is suspicious ! \n"); info_solution = 1; } else{ if( loud ) printf("-- Solution is CORRECT ! \n"); info_solution = 0; } return info_solution; } /** ******************************************************************************* * * @ingroup dplasma_complex64_check * * check_zpoinv - Returns the result of the following test * * \f[ (|| I - A * A^(-1) ||_one / (||A||_one * ||A^(-1)||_one * N * eps) ) < 10. \f] * * where A is the original matrix, and Ainv the result of a cholesky inversion. * ******************************************************************************* * * @param[in,out] parsec * The parsec context of the application that will run the operation. * * @param[in] loud * The level of verbosity required. * * @param[in] uplo * = PlasmaUpper: Upper triangle of A is referenced; * = PlasmaLower: Lower triangle of A is referenced. * * @param[in] A * Descriptor of the distributed original matrix A. * A must be two_dim_block_cyclic and fully generated. * * @param[in] Ainv * Descriptor of the computed distributed A inverse. * ******************************************************************************* * * @return * \retval 1, if the result is incorrect * \retval 0, if the result is correct * ******************************************************************************/ int check_zpoinv( parsec_context_t *parsec, int loud, PLASMA_enum uplo, parsec_tiled_matrix_dc_t *A, parsec_tiled_matrix_dc_t *Ainv ) { two_dim_block_cyclic_t *twodA = (two_dim_block_cyclic_t *)A; two_dim_block_cyclic_t Id; int info_solution; double Anorm, Ainvnorm, Rnorm; double eps, result; eps = LAPACKE_dlamch_work('e'); two_dim_block_cyclic_init(&Id, matrix_ComplexDouble, matrix_Tile, A->super.nodes, twodA->grid.rank, A->mb, A->nb, A->n, A->n, 0, 0, A->n, A->n, twodA->grid.strows, twodA->grid.stcols, twodA->grid.rows); Id.mat = parsec_data_allocate((size_t)Id.super.nb_local_tiles * (size_t)Id.super.bsiz * (size_t)parsec_datadist_getsizeoftype(Id.super.mtype)); dplasma_zlaset( parsec, PlasmaUpperLower, 0., 1., (parsec_tiled_matrix_dc_t *)&Id); /* Id - A^-1 * A */ dplasma_zhemm(parsec, PlasmaLeft, uplo, -1., Ainv, A, 1., (parsec_tiled_matrix_dc_t *)&Id ); Anorm = dplasma_zlanhe( parsec, PlasmaOneNorm, uplo, A ); Ainvnorm = dplasma_zlanhe( parsec, PlasmaOneNorm, uplo, Ainv ); Rnorm = dplasma_zlange( parsec, PlasmaOneNorm, (parsec_tiled_matrix_dc_t*)&Id ); result = Rnorm / ( (Anorm*Ainvnorm)*A->n*eps ); if ( loud > 2 ) { printf(" ||A||_one = %e, ||A^(-1)||_one = %e, ||I - A * A^(-1)||_one = %e, result = %e\n", Anorm, Ainvnorm, Rnorm, result); } if ( isinf(Ainvnorm) || isnan(result) || isinf(result) || (result > 10.0) ) { info_solution = 1; } else { info_solution = 0; } parsec_data_free(Id.mat); parsec_tiled_matrix_dc_destroy((parsec_tiled_matrix_dc_t*)&Id); return info_solution; }
{ "alphanum_fraction": 0.5258164569, "avg_line_length": 34.6898734177, "ext": "c", "hexsha": "af01957fb8f0fd4e6023bc08bbf5fbc4164d10cc", "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": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8", "max_forks_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_forks_repo_name": "NLAFET/ABFT", "max_forks_repo_path": "dplasma/lib/dplasma_zcheck.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_issues_repo_name": "NLAFET/ABFT", "max_issues_repo_path": "dplasma/lib/dplasma_zcheck.c", "max_line_length": 101, "max_stars_count": 1, "max_stars_repo_head_hexsha": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8", "max_stars_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_stars_repo_name": "NLAFET/ABFT", "max_stars_repo_path": "dplasma/lib/dplasma_zcheck.c", "max_stars_repo_stars_event_max_datetime": "2019-08-13T10:13:00.000Z", "max_stars_repo_stars_event_min_datetime": "2019-08-13T10:13:00.000Z", "num_tokens": 2965, "size": 10962 }
#include <math.h> #include <cblas.h> void matmult_mnk(int M, int N, int K, double **A, double **B, double **C) { for (int l = 0; l < M*N; l++) { C[0][l] = 0; } for (int m = 0; m < M; m++) { for (int n = 0; n < N; n++) { for (int k = 0; k < K; k++) { C[m][n] += A[m][k] * B[k][n]; } } } } void matmult_mkn(int M, int N, int K, double **A, double **B, double **C) { for (int l = 0; l < M*N; l++) { C[0][l] = 0; } for (int m = 0; m < M; m++) { for (int k = 0; k < K; k++) { for (int n = 0; n < N; n++) { C[m][n] += A[m][k] * B[k][n]; } } } } void matmult_nmk(int M, int N, int K, double **A, double **B, double **C) { for (int l = 0; l < M*N; l++) { C[0][l] = 0; } for (int n = 0; n < N; n++) { for (int m = 0; m < M; m++) { for (int k = 0; k < K; k++) { C[m][n] += A[m][k] * B[k][n]; } } } } void matmult_nkm(int M, int N, int K, double **A, double **B, double **C) { for (int l = 0; l < M*N; l++) { C[0][l] = 0; } for (int n = 0; n < N; n++) { for (int k = 0; k < K; k++) { for (int m = 0; m < M; m++) { C[m][n] += A[m][k] * B[k][n]; } } } } void matmult_kmn(int M, int N, int K, double **A, double **B, double **C) { for (int l = 0; l < M*N; l++) { C[0][l] = 0; } for (int k = 0; k < K; k++) { for (int m = 0; m < M; m++) { for (int n = 0; n < N; n++) { C[m][n] += A[m][k] * B[k][n]; } } } } void matmult_knm(int M, int N, int K, double **A, double **B, double **C) { for (int l = 0; l < M*N; l++) { C[0][l] = 0; } for (int k = 0; k < K; k++) { for (int n = 0; n < N; n++) { for (int m = 0; m < M; m++) { C[m][n] += A[m][k] * B[k][n]; } } } } void matmult_nat(int M, int N, int K, double **A, double **B, double **C) { for (int m = 0; m < M; m++) { for (int n = 0; n < N; n++) { C[m][n] = 0; for (int k = 0; k < K; k++) { C[m][n] += A[m][k] * B[k][n]; } } } } void matmult_lib(int M, int N, int K, double **A, double **B, double **C) { int layout, TRANSA, TRANSB, LDA, LDB, LDC; double alpha, beta; layout = 101; // rowmajor TRANSA = 111; // A is not transposed TRANSB = 111; // B is not transposed LDA = fmax(1,K); // leading dimension of A LDB = fmax(1,N); // leading dimension of B LDC = fmax(1,N); // leading dimension of C alpha = 1.0; // no scaling beta = 0.0; // cblas_dgemm(layout, TRANSA, TRANSB, M, N, K, alpha, *A, LDA, *B, LDB, beta, *C, LDC); } void matmult_blk(int M, int N, int K, double **A, double **B, double **C, int bs) { // MKN bs = fmax(1, fmin(bs, K)); for (int i = 0; i < M*N; i++) C[0][i] = 0.0; for (int m0 = 0; m0 < M; m0 += bs) { for (int k0 = 0; k0 < K; k0 += bs) { for (int n0 = 0; n0 < N; n0 += bs) { for (int m = m0; m < fmin(m0 + bs, M); m++) { for (int k = k0; k < fmin(k0 + bs, K); k++) { for (int n = n0; n < fmin(n0 + bs, N); n++) C[m][n] += A[m][k] * B[k][n]; } } } } } }
{ "alphanum_fraction": 0.4209486166, "avg_line_length": 21.5319148936, "ext": "c", "hexsha": "07955c9e0d7df07054cff0d20eb9f89c20fcbb1b", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-01-18T16:42:40.000Z", "max_forks_repo_forks_event_min_datetime": "2019-01-22T10:34:10.000Z", "max_forks_repo_head_hexsha": "c63201022e2715112bc38dcc2a53316ea1e2b055", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "anderslaunerbaek/HPC", "max_forks_repo_path": "projects/assign_1/func.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "c63201022e2715112bc38dcc2a53316ea1e2b055", "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": "anderslaunerbaek/HPC", "max_issues_repo_path": "projects/assign_1/func.c", "max_line_length": 90, "max_stars_count": 1, "max_stars_repo_head_hexsha": "c63201022e2715112bc38dcc2a53316ea1e2b055", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "anderslaunerbaek/HPC", "max_stars_repo_path": "projects/assign_1/func.c", "max_stars_repo_stars_event_max_datetime": "2022-01-06T08:58:43.000Z", "max_stars_repo_stars_event_min_datetime": "2022-01-06T08:58:43.000Z", "num_tokens": 1358, "size": 3036 }
#ifndef EIGEN_BENCH_UTIL_H #define EIGEN_BENCH_UTIL_H #include <Eigen/Core> #include "BenchTimer.h" using namespace std; using namespace Eigen; #include <boost/preprocessor/repetition/enum_params.hpp> #include <boost/preprocessor/repetition.hpp> #include <boost/preprocessor/seq.hpp> #include <boost/preprocessor/array.hpp> #include <boost/preprocessor/arithmetic.hpp> #include <boost/preprocessor/comparison.hpp> #include <boost/preprocessor/punctuation.hpp> #include <boost/preprocessor/punctuation/comma.hpp> #include <boost/preprocessor/stringize.hpp> template<typename MatrixType> void initMatrix_random(MatrixType& mat) __attribute__((noinline)); template<typename MatrixType> void initMatrix_random(MatrixType& mat) { mat.setRandom();// = MatrixType::random(mat.rows(), mat.cols()); } template<typename MatrixType> void initMatrix_identity(MatrixType& mat) __attribute__((noinline)); template<typename MatrixType> void initMatrix_identity(MatrixType& mat) { mat.setIdentity(); } #ifndef __INTEL_COMPILER #define DISABLE_SSE_EXCEPTIONS() { \ int aux; \ asm( \ "stmxcsr %[aux] \n\t" \ "orl $32832, %[aux] \n\t" \ "ldmxcsr %[aux] \n\t" \ : : [aux] "m" (aux)); \ } #else #define DISABLE_SSE_EXCEPTIONS() #endif #ifdef BENCH_GMM #include <gmm/gmm.h> template <typename EigenMatrixType, typename GmmMatrixType> void eiToGmm(const EigenMatrixType& src, GmmMatrixType& dst) { dst.resize(src.rows(),src.cols()); for (int j=0; j<src.cols(); ++j) for (int i=0; i<src.rows(); ++i) dst(i,j) = src.coeff(i,j); } #endif #ifdef BENCH_GSL #include <gsl/gsl_matrix.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_eigen.h> template <typename EigenMatrixType> void eiToGsl(const EigenMatrixType& src, gsl_matrix** dst) { for (int j=0; j<src.cols(); ++j) for (int i=0; i<src.rows(); ++i) gsl_matrix_set(*dst, i, j, src.coeff(i,j)); } #endif #ifdef BENCH_UBLAS #include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/vector.hpp> template <typename EigenMatrixType, typename UblasMatrixType> void eiToUblas(const EigenMatrixType& src, UblasMatrixType& dst) { dst.resize(src.rows(),src.cols()); for (int j=0; j<src.cols(); ++j) for (int i=0; i<src.rows(); ++i) dst(i,j) = src.coeff(i,j); } template <typename EigenType, typename UblasType> void eiToUblasVec(const EigenType& src, UblasType& dst) { dst.resize(src.size()); for (int j=0; j<src.size(); ++j) dst[j] = src.coeff(j); } #endif #endif // EIGEN_BENCH_UTIL_H
{ "alphanum_fraction": 0.6829454407, "avg_line_length": 28.1827956989, "ext": "h", "hexsha": "6489ab7e1156d9f860de040e71db43160004829e", "lang": "C", "max_forks_count": 23, "max_forks_repo_forks_event_max_datetime": "2021-10-11T07:10:06.000Z", "max_forks_repo_forks_event_min_datetime": "2018-10-14T02:14:38.000Z", "max_forks_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "k4rth33k/dnnc-operators", "max_forks_repo_path": "packages/eigen-eigen-323c052e1731/bench/BenchUtil.h", "max_issues_count": 11, "max_issues_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_issues_repo_issues_event_max_datetime": "2021-06-16T11:46:57.000Z", "max_issues_repo_issues_event_min_datetime": "2018-10-18T06:15:26.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "k4rth33k/dnnc-operators", "max_issues_repo_path": "packages/eigen-eigen-323c052e1731/bench/BenchUtil.h", "max_line_length": 99, "max_stars_count": 59, "max_stars_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "k4rth33k/dnnc-operators", "max_stars_repo_path": "packages/eigen-eigen-323c052e1731/bench/BenchUtil.h", "max_stars_repo_stars_event_max_datetime": "2021-05-29T07:50:37.000Z", "max_stars_repo_stars_event_min_datetime": "2018-10-08T14:03:48.000Z", "num_tokens": 714, "size": 2621 }
#pragma once #include <gsl\gsl> #include <winrt\Windows.Foundation.h> #include <d3d11.h> #include "DrawableGameComponent.h" #include "MatrixHelper.h" #include "DirectionalLight.h" namespace Library { class ProxyModel; } namespace Rendering { class TransparencyMaterial; class TransparencyDemo final : public Library::DrawableGameComponent { public: TransparencyDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera); TransparencyDemo(const TransparencyDemo&) = delete; TransparencyDemo(TransparencyDemo&&) = default; TransparencyDemo& operator=(const TransparencyDemo&) = default; TransparencyDemo& operator=(TransparencyDemo&&) = default; ~TransparencyDemo(); float AmbientLightIntensity() const; void SetAmbientLightIntensity(float intensity); float DirectionalLightIntensity() const; void SetDirectionalLightIntensity(float intensity); const DirectX::XMFLOAT3& LightDirection() const; void RotateDirectionalLight(DirectX::XMFLOAT2 amount); float SpecularIntensity() const; void SetSpecularIntensity(float intensity); float SpecularPower() const; void SetSpecularPower(float power); float FogStart() const; void SetFogStart(float fogStart); float FogRange() const; void SetFogRange(float fogRange); virtual void Initialize() override; virtual void Update(const Library::GameTime& gameTime) override; virtual void Draw(const Library::GameTime& gameTime) override; private: inline static const float RotationRate{ DirectX::XM_PI }; std::shared_ptr<TransparencyMaterial> mMaterial; DirectX::XMFLOAT4X4 mWorldMatrix{ Library::MatrixHelper::Identity }; winrt::com_ptr<ID3D11Buffer> mVertexBuffer; std::uint32_t mVertexCount{ 0 }; Library::DirectionalLight mDirectionalLight; std::unique_ptr<Library::ProxyModel> mProxyModel; bool mUpdateMaterial{ true }; }; }
{ "alphanum_fraction": 0.7741416309, "avg_line_length": 28.6769230769, "ext": "h", "hexsha": "2fd0cfcf2e15ee980324c5ad4c65910d6dbe95b4", "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/5.4_Transparency/TransparencyDemo.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/5.4_Transparency/TransparencyDemo.h", "max_line_length": 88, "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/5.4_Transparency/TransparencyDemo.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 455, "size": 1864 }
/* siman/siman_test.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Mark Galassi * * 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. */ #include <config.h> #include <math.h> #include <stdio.h> #include <string.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_siman.h> #include <gsl/gsl_ieee_utils.h> /* A cute example of this program to then look at stuff would be: ./siman_test D3 | grep -v "^#" | awk '{print $3}' | sed 's/::/ /gp' > output then go into gnuplot and try typing: gnuplot> set parametric gnuplot> splot 'output' with lines Or you can plot from a pipe: gnuplot> plot '<../siman/siman_test | grep -v "^#"' using 1:2 with lines gnuplot> plot '<../siman/siman_test | grep -v "^#"' using 1:3 with lines and so forth. */ /* set up parameters for this simulated annealing run */ #define N_TRIES 200 /* how many points do we try before stepping */ #define ITERS_FIXED_T 1000 /* how many iterations for each T? */ #define STEP_SIZE 1.0 /* max step size in random walk */ #define K 1.0 /* Boltzmann constant */ #define T_INITIAL 0.008 /* initial temperature */ #define MU_T 1.003 /* damping factor for temperature */ #define T_MIN 2.0e-6 gsl_siman_params_t params = {N_TRIES, ITERS_FIXED_T, STEP_SIZE, K, T_INITIAL, MU_T, T_MIN}; double square(double x); double test_E_1D(Element x); void test_step_1D(const gsl_rng * r, Element *x_p, double step_size); void print_pos_1D(Element x); double distance_1D(Element x, Element y); double test_E_2D(Element x); void test_step_2D(const gsl_rng * r, Element *x_p, double step_size); void print_pos_2D(Element x); double distance_2D(Element x, Element y); double test_E_3D(Element x); void test_step_3D(const gsl_rng * r, Element *x_p, double step_size); void print_pos_3D(Element x); double distance_3D(Element x, Element y); double E1(void *xp); double M1(void *xp, void *yp); void S1(const gsl_rng * r, void *xp, double step_size); void P1(void *xp); int main(int argc, char *argv[]) { Element x0; /* initial guess for search */ /* double x_initial = 2.5; */ double x_initial = -10.0; gsl_rng * r = gsl_rng_alloc (gsl_rng_env_setup()) ; gsl_ieee_env_setup (); gsl_siman_solve(r, &x_initial, E1, S1, M1, P1, NULL, NULL, NULL, sizeof(double), params); return 0; if (argc != 2) { /* fprintf(stderr, "usage: %s [D1, D2, D3, CA]\n", argv[0]); */ fprintf(stderr, "usage: %s [D1 | D2 | D3]\n", argv[0]); return 1; } printf("#testing the simulated annealing routines\n"); if (strcmp(argv[1], "D1") == 0) { x0.D1 = 12.0; printf("#one dimensional problem, x0 = %f\n", x0.D1); /* gsl_siman_Usolve(r, &x0, test_E_1D, test_step_1D, distance_1D, */ /* print_pos_1D, params); */ return 0; } if (strcmp(argv[1], "D2") == 0) { x0.D2[0] = 12.0; x0.D2[1] = 5.5; printf("#two dimensional problem, (x0,y0) = (%f,%f)\n", x0.D2[0], x0.D2[1]); /* gsl_siman_Usolve(r, &x0, test_E_2D, test_step_2D, distance_2D, */ /* print_pos_2D, params); */ return 0; } if (strcmp(argv[1], "D3") == 0) { x0.D3[0] = 12.2; x0.D3[1] = 5.5; x0.D3[2] = -15.5; printf("#three dimensional problem, (x0,y0,z0) = (%f,%f,%f)\n", x0.D3[0], x0.D3[1], x0.D3[2]); /* gsl_siman_Usolve(r, &x0, test_E_3D, test_step_3D, distance_3D, */ /* print_pos_3D, params); */ } /* x0.D2[0] = 12.2; x0.D2[1] = 5.5; gsl_siman_solve(r, &x0, test_E_2D, test_step_2D, distance_2D, print_pos_2D, params); */ /* x0.D3[0] = 12.2; x0.D3[1] = 5.5; x0.D3[2] = -15.5; gsl_siman_solve(r, &x0, test_E_3D, test_step_3D, distance_3D, print_pos_3D, params); */ return 0; } double square(double x) { return x*x; } double test_E_1D(Element x) { double val = x.D1; /*return sin(sin(val*val) - cos(val)) + cos(sin(val) + sin(val)*sin(val));*/ return exp(-square(val-1))*sin(8*val); /* return 1.0/(square(x-1.0) + 1.0)*sin(8.0*x); */ /* return 1.0/(square(x-1.0) + 1.0)*sin(8.0*x) + x*x/100.0; */ } /* takes a step for the test function; max distance: step_size. * the new point is put in x_p and returned. */ void test_step_1D(const gsl_rng * r, Element *x_p, double step_size) { double old_x = x_p->D1; double new_x; new_x = gsl_rng_uniform(r); new_x = new_x*2*step_size; new_x = new_x - step_size + old_x; x_p->D1 = new_x; } /* simple routine to print out a position value */ void print_pos_1D(Element x) { printf("%12g", x.D1); } /* a metric for the 2D space */ double distance_1D(Element x, Element y) { return fabs(y.D1 - x.D1); } /* a 2-D function to be minimized */ double test_E_2D(Element x) { double old_x = x.D2[0], old_y = x.D2[1]; return exp(-square(old_x-1) - square(old_y - 0.8))*sin(8*old_x + 8 * old_y); } /* takes a step for the test function; max distance: step_size. the new point is put in x_p and returned. */ void test_step_2D(const gsl_rng * r, Element *x_p, double step_size) { double old_x = x_p->D2[0], old_y = x_p->D2[1], new_x, new_y; new_x = gsl_rng_uniform(r); new_x = new_x*2*step_size; new_x = new_x - step_size + old_x; new_y = gsl_rng_uniform(r); new_y = new_y*2*step_size; new_y = new_y - step_size + old_y; x_p->D2[0] = new_x; x_p->D2[1] = new_y; } /* simple routine to print out a position value */ void print_pos_2D(Element x) { printf("%g::%g", x.D2[0], x.D2[1]); } /* a metric for the 2D space */ double distance_2D(Element x, Element y) { return sqrt(square(y.D2[0]-x.D2[0]) + square(y.D2[1]-x.D2[1])); } /**********************************************/ /************ 3-dimensional search ************/ /**********************************************/ /* a 3-D function to be minimized */ double test_E_3D(Element x) { return exp(-square(x.D3[0]-1) - square(x.D3[1] - 0.8) - square(x.D3[2] - 0.8)) * sin(8*x.D3[0] + 8*x.D3[1] + 8*x.D3[2]) + (square(x.D3[0]) + square(x.D3[1]) + square(x.D3[2]))/10000.0; } /* takes a step for the test function; max distance: step_size. * the new point is put in x_p and returned. */ void test_step_3D(const gsl_rng * r, Element *x_p, double step_size) { double old_x = x_p->D3[0], old_y = x_p->D3[1], old_z = x_p->D3[2]; double new_x, new_y, new_z; new_x = gsl_rng_uniform(r); new_x = new_x*2*step_size; new_x = new_x - step_size + old_x; new_y = gsl_rng_uniform(r); new_y = new_y*2*step_size; new_y = new_y - step_size + old_y; new_z = gsl_rng_uniform(r); new_z = new_z*2*step_size; new_z = new_z - step_size + old_z; x_p->D3[0] = new_x; x_p->D3[1] = new_y; x_p->D3[2] = new_z; } /* simple routine to print out a position value */ void print_pos_3D(Element x) { printf("%g::%g::%g", x.D3[0], x.D3[1], x.D3[2]); } /* a metric for the 2D space */ double distance_3D(Element x, Element y) { return sqrt(square(y.D3[0]-x.D3[0]) + square(y.D3[1]-x.D3[1]) + square(y.D3[2]-x.D3[2])); } /* now some functions to test in one dimension */ double E1(void *xp) { double x = * ((double *) xp); return exp(-square(x-1))*sin(8*x) - exp(-square(x-1000))*0.89; /* return exp(-square(x-1))*sin(8*x); */ } double M1(void *xp, void *yp) { double x = *((double *) xp); double y = *((double *) yp); return fabs(x - y); } void S1(const gsl_rng * r, void *xp, double step_size) { double old_x = *((double *) xp); double new_x; new_x = gsl_rng_uniform(r)*2*step_size - step_size + old_x; /* new_x = new_x*2*step_size; */ /* new_x = new_x - step_size + old_x; */ memcpy(xp, &new_x, sizeof(new_x)); } void P1(void *xp) { printf(" %12g ", *((double *) xp)); }
{ "alphanum_fraction": 0.6309697856, "avg_line_length": 26.2236421725, "ext": "c", "hexsha": "5d41d18bde720d7d4a7e12a014e92f51e0a341b5", "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/siman/siman_test.c", "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/siman/siman_test.c", "max_line_length": 86, "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/siman/siman_test.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": 2851, "size": 8208 }
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2018 Couchbase, 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. */ #pragma once #include "engine_error.h" #include "types.h" #include <gsl/gsl> namespace cb { namespace audit { namespace document { enum class Operation; } } // namespace audit } // namespace cb struct ServerDocumentIface { virtual ~ServerDocumentIface() = default; /** * This callback is called from the underlying engine right before * it is linked into the list of available documents (it is currently * not visible to anyone). The engine should have validated all * properties set in the document by the client and the core, and * assigned a new CAS number for the document (and sequence number if * the underlying engine use those). * * The callback may at this time do post processing of the document * content (it is allowed to modify the content data, but not * reallocate or change the size of the data in any way). * * Given that the engine MAY HOLD LOCKS when calling this function * the core is *NOT* allowed to acquire *ANY* locks (except for doing * some sort of memory allocation for a temporary buffer). * * @param cookie The cookie provided to the engine for the storage * command which may (which may hold more context) * @param info the items underlying data * @return ENGINE_SUCCESS means that the underlying engine should * proceed to link the item. All other * error codes means that the engine should * *NOT* link the item */ virtual ENGINE_ERROR_CODE pre_link(gsl::not_null<const void*> cookie, item_info& info) = 0; /** * This callback is called from the underlying engine right before * a particular document expires. The callback is responsible examining * the value and possibly returning a new and modified value. * * @param itm_info info pertaining to the item that is to be expired. * @return std::string empty if the value required no modification, not * empty then the string contains the modified value. When not empty * the datatype of the new value is datatype xattr only. * * @throws std::bad_alloc in case of memory allocation failure */ virtual std::string pre_expiry(const item_info& itm_info) = 0; /** * Add an entry to the audit trail for access to the document specified * in the key for this cookie. * * @param cookie The cookie representing the operation * @param operation The type of access for the operation */ virtual void audit_document_access( gsl::not_null<const void*> cookie, cb::audit::document::Operation operation) = 0; };
{ "alphanum_fraction": 0.6627372053, "avg_line_length": 39.5227272727, "ext": "h", "hexsha": "d6ea0c7208fa1f3c304a500243ce2b008586588a", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-04-06T09:20:15.000Z", "max_forks_repo_forks_event_min_datetime": "2019-10-11T14:00:49.000Z", "max_forks_repo_head_hexsha": "40256dca6bf77fb4bcc18e8ef7d9b8f991bf4e45", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "paolococchi/kv_engine", "max_forks_repo_path": "include/memcached/server_document_iface.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "40256dca6bf77fb4bcc18e8ef7d9b8f991bf4e45", "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": "paolococchi/kv_engine", "max_issues_repo_path": "include/memcached/server_document_iface.h", "max_line_length": 80, "max_stars_count": 1, "max_stars_repo_head_hexsha": "33fb1ab2c9787f55555e5f7edea38807b3dbc371", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "hrajput89/kv_engine", "max_stars_repo_path": "include/memcached/server_document_iface.h", "max_stars_repo_stars_event_max_datetime": "2019-06-13T07:33:09.000Z", "max_stars_repo_stars_event_min_datetime": "2019-06-13T07:33:09.000Z", "num_tokens": 758, "size": 3478 }
#include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <assert.h> #include <gsl/gsl_vector.h> #define MAX(A,B) (((A)>(B))?(A):(B)) void reoshift(gsl_vector *v, int h) { if ( h > 0 ) { gsl_vector *temp = gsl_vector_alloc(v->size); gsl_vector_view p = gsl_vector_subvector(v, 0, v->size - h); gsl_vector_view p1 = gsl_vector_subvector(temp, h, v->size - h); gsl_vector_memcpy(&p1.vector, &p.vector); p = gsl_vector_subvector(temp, 0, h); gsl_vector_set_zero(&p.vector); gsl_vector_memcpy(v, temp); gsl_vector_free(temp); } } gsl_vector *poly_long_div(gsl_vector *n, gsl_vector *d, gsl_vector **r) { gsl_vector *nt = NULL, *dt = NULL, *rt = NULL, *d2 = NULL, *q = NULL; int gn, gt, gd; if ( (n->size >= d->size) && (d->size > 0) && (n->size > 0) ) { nt = gsl_vector_alloc(n->size); assert(nt != NULL); dt = gsl_vector_alloc(n->size); assert(dt != NULL); rt = gsl_vector_alloc(n->size); assert(rt != NULL); d2 = gsl_vector_alloc(n->size); assert(d2 != NULL); gsl_vector_memcpy(nt, n); gsl_vector_set_zero(dt); gsl_vector_set_zero(rt); gsl_vector_view p = gsl_vector_subvector(dt, 0, d->size); gsl_vector_memcpy(&p.vector, d); gsl_vector_memcpy(d2, dt); gn = n->size - 1; gd = d->size - 1; gt = 0; while( gsl_vector_get(d, gd) == 0 ) gd--; while ( gn >= gd ) { reoshift(dt, gn-gd); double v = gsl_vector_get(nt, gn)/gsl_vector_get(dt, gn); gsl_vector_set(rt, gn-gd, v); gsl_vector_scale(dt, v); gsl_vector_sub(nt, dt); gt = MAX(gt, gn-gd); while( (gn>=0) && (gsl_vector_get(nt, gn) == 0.0) ) gn--; gsl_vector_memcpy(dt, d2); } q = gsl_vector_alloc(gt+1); assert(q != NULL); p = gsl_vector_subvector(rt, 0, gt+1); gsl_vector_memcpy(q, &p.vector); if ( r != NULL ) { if ( (gn+1) > 0 ) { *r = gsl_vector_alloc(gn+1); assert( *r != NULL ); p = gsl_vector_subvector(nt, 0, gn+1); gsl_vector_memcpy(*r, &p.vector); } else { *r = gsl_vector_alloc(1); assert( *r != NULL ); gsl_vector_set_zero(*r); } } gsl_vector_free(nt); gsl_vector_free(dt); gsl_vector_free(rt); gsl_vector_free(d2); return q; } else { q = gsl_vector_alloc(1); assert( q != NULL ); gsl_vector_set_zero(q); if ( r != NULL ) { *r = gsl_vector_alloc(n->size); assert( *r != NULL ); gsl_vector_memcpy(*r, n); } return q; } } void poly_print(gsl_vector *p) { int i; for(i=p->size-1; i >= 0; i--) { if ( i > 0 ) printf("%lfx^%d + ", gsl_vector_get(p, i), i); else printf("%lf\n", gsl_vector_get(p, i)); } } gsl_vector *create_poly(int d, ...) { va_list al; int i; gsl_vector *r = NULL; va_start(al, d); r = gsl_vector_alloc(d); assert( r != NULL ); for(i=0; i < d; i++) gsl_vector_set(r, i, va_arg(al, double)); return r; }
{ "alphanum_fraction": 0.5849187132, "avg_line_length": 26.7685185185, "ext": "c", "hexsha": "9ecd573fae548736443921b67d25613f7addf351", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_path": "lang/C/polynomial-long-division-1.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "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": "ethansaxenian/RosettaDecode", "max_issues_repo_path": "lang/C/polynomial-long-division-1.c", "max_line_length": 71, "max_stars_count": 2, "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_path": "lang/C/polynomial-long-division-1.c", "max_stars_repo_stars_event_max_datetime": "2017-06-26T18:52:29.000Z", "max_stars_repo_stars_event_min_datetime": "2017-06-10T14:21:53.000Z", "num_tokens": 938, "size": 2891 }
//This computes "the" DCT (discrete cosine transformation) along dim of matrix X. //This uses a CBLAS matrix multiplication by the DCT-II matrix. //For complex input X, the output Y is complex, and the DCT is just the DCT of the //real and imaginary parts separately (following Octave convention). #include <stdio.h> #include <stdlib.h> #include <math.h> #include <cblas.h> #ifndef M_PI #define M_PI 3.14159265358979323846 #endif #ifdef __cplusplus namespace codee { extern "C" { #endif int dct_cblas_s (float *Y, const float *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const size_t ndct, const int sc); int dct_cblas_d (double *Y, const double *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const size_t ndct, const int sc); int dct_cblas_c (float *Y, const float *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const size_t ndct, const int sc); int dct_cblas_z (double *Y, const double *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const size_t ndct, const int sc); int dct_cblas_s (float *Y, const float *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const size_t ndct, const int sc) { if (dim>3u) { fprintf(stderr,"error in dct_cblas_s: dim must be in [0 3]\n"); return 1; } const size_t N = R*C*S*H; const size_t Lx = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H; if (ndct<Lx) { fprintf(stderr,"error in dct_cblas_s: ndct must be >= Lx (length of vecs in X)\n"); return 1; } if (ndct==0u || N==0u) {} else if (ndct==1u) { for (size_t n=N; n>0u; --n, ++X, ++Y) { *Y = *X; } } else { //Scaling const float s = sc ? 2.0f/sqrtf((float)(2u*ndct)) : 2.0f; const float dcsc = sc ? 1.0f/sqrtf((float)ndct) : 2.0f; //Initialize DCT-II matrix const size_t LN = Lx * ndct; const float P_N = (float)(M_PI/(double)ndct); float *DCT; DCT = (float *)aligned_alloc(sizeof(float),LN*sizeof(float)); if (!DCT) { fprintf(stderr,"error in dct_cblas_s: problem with aligned_alloc. "); perror("aligned_alloc"); return 1; } for (size_t l=0u; l<Lx; ++l, ++DCT) { *DCT = dcsc; } for (size_t n=1u; n<ndct; ++n) { for (size_t l=0u; l<Lx; ++l, ++DCT) { *DCT = s * cosf(P_N*(0.5f+(float)l)*(float)n); } } DCT -= LN; if (Lx==N) { cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)ndct,(int)Lx,1.0f,DCT,(int)Lx,X,1,0.0f,Y,1); } else { const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u); const size_t B = (iscolmajor && dim==0u) ? C*S*H : K; const size_t V = N/Lx, G = V/B; if (K==1u && (G==1u || B==1u)) { cblas_sgemm(CblasColMajor,CblasTrans,CblasNoTrans,(int)ndct,(int)V,(int)Lx,1.0f,DCT,(int)Lx,X,(int)Lx,0.0f,Y,(int)ndct); } else { for (size_t g=G; g>0u; --g, X+=B*(Lx-1u), Y+=B*(ndct-1u)) { for (size_t b=B; b>0u; --b, ++X, ++Y) { cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)ndct,(int)Lx,1.0f,DCT,(int)Lx,X,(int)K,0.0f,Y,(int)K); } } } } free(DCT); } return 0; } int dct_cblas_d (double *Y, const double *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const size_t ndct, const int sc) { if (dim>3u) { fprintf(stderr,"error in dct_cblas_d: dim must be in [0 3]\n"); return 1; } const size_t N = R*C*S*H; const size_t Lx = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H; if (ndct<Lx) { fprintf(stderr,"error in dct_cblas_d: ndct must be >= Lx (length of vecs in X)\n"); return 1; } if (ndct==0u || N==0u) {} else if (ndct==1u) { for (size_t n=N; n>0u; --n, ++X, ++Y) { *Y = *X; } } else { //Scaling const double s = sc ? 2.0/sqrt((double)(2u*ndct)) : 2.0; const double dcsc = sc ? 1.0/sqrt((double)ndct) : 2.0; //Initialize DCT-II matrix const size_t LN = Lx * ndct; const double P_N = M_PI/(double)ndct; double *DCT; DCT = (double *)aligned_alloc(sizeof(double),LN*sizeof(double)); if (!DCT) { fprintf(stderr,"error in dct_cblas_d: problem with aligned_alloc. "); perror("aligned_alloc"); return 1; } for (size_t l=0u; l<Lx; ++l, ++DCT) { *DCT = dcsc; } for (size_t n=1u; n<ndct; ++n) { for (size_t l=0u; l<Lx; ++l, ++DCT) { *DCT = s * cos(P_N*(0.5+(double)l)*(double)n); } } DCT -= LN; if (Lx==N) { cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)ndct,(int)Lx,1.0,DCT,(int)Lx,X,1,0.0,Y,1); } else { const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u); const size_t B = (iscolmajor && dim==0u) ? C*S*H : K; const size_t V = N/Lx, G = V/B; if (K==1u && (G==1u || B==1u)) { cblas_dgemm(CblasColMajor,CblasTrans,CblasNoTrans,(int)ndct,(int)V,(int)Lx,1.0,DCT,(int)Lx,X,(int)Lx,0.0,Y,(int)ndct); } else { for (size_t g=G; g>0u; --g, X+=B*(Lx-1u), Y+=B*(ndct-1u)) { for (size_t b=B; b>0u; --b, ++X, ++Y) { cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)ndct,(int)Lx,1.0,DCT,(int)Lx,X,(int)K,0.0,Y,(int)K); } } } } free(DCT); } return 0; } int dct_cblas_c (float *Y, const float *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const size_t ndct, const int sc) { if (dim>3u) { fprintf(stderr,"error in dct_cblas_c: dim must be in [0 3]\n"); return 1; } const size_t N = R*C*S*H; const size_t Lx = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H; if (ndct<Lx) { fprintf(stderr,"error in dct_cblas_c: ndct must be >= Lx (length of vecs in X)\n"); return 1; } if (ndct==0u || N==0u) {} else if (ndct==1u) { for (size_t n=2u*N; n>0u; --n, ++X, ++Y) { *Y = *X; } } else { //Scaling const float s = sc ? 2.0f/sqrtf((float)(2u*ndct)) : 2.0f; const float dcsc = sc ? 1.0f/sqrtf((float)ndct) : 2.0f; //Initialize DCT-II matrix const size_t LN = Lx * ndct; const float P_N = (float)(M_PI/(double)ndct); float *DCT; DCT = (float *)aligned_alloc(sizeof(float),LN*sizeof(float)); if (!DCT) { fprintf(stderr,"error in dct_cblas_c: problem with aligned_alloc. "); perror("aligned_alloc"); return 1; } for (size_t l=0u; l<Lx; ++l, ++DCT) { *DCT = dcsc; } for (size_t n=1u; n<ndct; ++n) { for (size_t l=0u; l<Lx; ++l, ++DCT) { *DCT = s * cosf(P_N*(0.5f+(float)l)*(float)n); } } DCT -= LN; if (Lx==N) { cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)ndct,(int)Lx,1.0f,DCT,(int)Lx,X,2,0.0f,Y,2); cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)ndct,(int)Lx,1.0f,DCT,(int)Lx,X+1,2,0.0f,Y+1,2); } else { const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u); const size_t B = (iscolmajor && dim==0u) ? C*S*H : K; const size_t V = N/Lx, G = V/B; if (K==1u && (G==1u || B==1u)) { for (size_t v=0u; v<V; ++v, X+=2u*Lx, Y+=2u*ndct) { cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)ndct,(int)Lx,1.0f,DCT,(int)Lx,X,2,0.0f,Y,2); cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)ndct,(int)Lx,1.0f,DCT,(int)Lx,X+1,2,0.0f,Y+1,2); } } else { for (size_t g=G; g>0u; --g, X+=2u*B*(Lx-1u), Y+=2u*B*(ndct-1u)) { for (size_t b=B; b>0u; --b, ++X, ++Y) { cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)ndct,(int)Lx,1.0f,DCT,(int)Lx,X,2*(int)K,0.0f,Y,2*(int)K); ++X; ++Y; cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)ndct,(int)Lx,1.0f,DCT,(int)Lx,X,2*(int)K,0.0f,Y,2*(int)K); } } } } free(DCT); } return 0; } int dct_cblas_z (double *Y, const double *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const size_t ndct, const int sc) { if (dim>3u) { fprintf(stderr,"error in dct_cblas_z: dim must be in [0 3]\n"); return 1; } const size_t N = R*C*S*H; const size_t Lx = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H; if (ndct<Lx) { fprintf(stderr,"error in dct_cblas_z: ndct must be >= Lx (length of vecs in X)\n"); return 1; } if (ndct==0u || N==0u) {} else if (ndct==1u) { for (size_t n=2u*N; n>0u; --n, ++X, ++Y) { *Y = *X; } } else { //Scaling const double s = sc ? 2.0/sqrt((double)(2u*ndct)) : 2.0; const double dcsc = sc ? 1.0/sqrt((double)ndct) : 2.0; //Initialize DCT-II matrix const size_t LN = Lx * ndct; const double P_N = M_PI/(double)ndct; double *DCT; DCT = (double *)aligned_alloc(sizeof(double),LN*sizeof(double)); if (!DCT) { fprintf(stderr,"error in dct_cblas_z: problem with aligned_alloc. "); perror("aligned_alloc"); return 1; } for (size_t l=0u; l<Lx; ++l, ++DCT) { *DCT = dcsc; } for (size_t n=1u; n<ndct; ++n) { for (size_t l=0u; l<Lx; ++l, ++DCT) { *DCT = s * cos(P_N*(0.5+(double)l)*(double)n); } } DCT -= LN; if (Lx==N) { cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)ndct,(int)Lx,1.0,DCT,(int)Lx,X,2,0.0,Y,2); cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)ndct,(int)Lx,1.0,DCT,(int)Lx,X+1,2,0.0,Y+1,2); } else { const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u); const size_t B = (iscolmajor && dim==0u) ? C*S*H : K; const size_t V = N/Lx, G = V/B; if (K==1u && (G==1u || B==1u)) { for (size_t v=0u; v<V; ++v, X+=2u*Lx, Y+=2u*ndct) { cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)ndct,(int)Lx,1.0,DCT,(int)Lx,X,2,0.0,Y,2); cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)ndct,(int)Lx,1.0,DCT,(int)Lx,X+1,2,0.0,Y+1,2); } } else { for (size_t g=G; g>0u; --g, X+=2u*B*(Lx-1u), Y+=2u*B*(ndct-1u)) { for (size_t b=B; b>0u; --b, ++X, ++Y) { cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)ndct,(int)Lx,1.0,DCT,(int)Lx,X,2*(int)K,0.0,Y,2*(int)K); ++X; ++Y; cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)ndct,(int)Lx,1.0,DCT,(int)Lx,X,2*(int)K,0.0,Y,2*(int)K); } } } } free(DCT); } return 0; } #ifdef __cplusplus } } #endif
{ "alphanum_fraction": 0.5003298697, "avg_line_length": 38.7412140575, "ext": "c", "hexsha": "018e2ed9b377bf67558d01e88aaae3eb5e868aa7", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-10-05T13:50:32.000Z", "max_forks_repo_forks_event_min_datetime": "2021-10-05T13:50:32.000Z", "max_forks_repo_head_hexsha": "28880ede8ca715c2a5a9b596742070f9bda9830e", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "erikedwards4/dsp", "max_forks_repo_path": "c/dct.cblas.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "28880ede8ca715c2a5a9b596742070f9bda9830e", "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/dsp", "max_issues_repo_path": "c/dct.cblas.c", "max_line_length": 182, "max_stars_count": 1, "max_stars_repo_head_hexsha": "28880ede8ca715c2a5a9b596742070f9bda9830e", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "erikedwards4/dsp", "max_stars_repo_path": "c/dct.cblas.c", "max_stars_repo_stars_event_max_datetime": "2020-08-26T09:22:40.000Z", "max_stars_repo_stars_event_min_datetime": "2020-08-26T09:22:40.000Z", "num_tokens": 4362, "size": 12126 }
/* matrix/gsl_matrix_ushort.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000 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 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_MATRIX_USHORT_H__ #define __GSL_MATRIX_USHORT_H__ #include <stdlib.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_vector_ushort.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 size1; size_t size2; size_t tda; unsigned short * data; gsl_block_ushort * block; int owner; } gsl_matrix_ushort; typedef struct { gsl_matrix_ushort matrix; } _gsl_matrix_ushort_view; typedef _gsl_matrix_ushort_view gsl_matrix_ushort_view; typedef struct { gsl_matrix_ushort matrix; } _gsl_matrix_ushort_const_view; typedef const _gsl_matrix_ushort_const_view gsl_matrix_ushort_const_view; /* Allocation */ gsl_matrix_ushort * gsl_matrix_ushort_alloc (const size_t n1, const size_t n2); gsl_matrix_ushort * gsl_matrix_ushort_calloc (const size_t n1, const size_t n2); gsl_matrix_ushort * gsl_matrix_ushort_alloc_from_block (gsl_block_ushort * b, const size_t offset, const size_t n1, const size_t n2, const size_t d2); gsl_matrix_ushort * gsl_matrix_ushort_alloc_from_matrix (gsl_matrix_ushort * m, const size_t k1, const size_t k2, const size_t n1, const size_t n2); gsl_vector_ushort * gsl_vector_ushort_alloc_row_from_matrix (gsl_matrix_ushort * m, const size_t i); gsl_vector_ushort * gsl_vector_ushort_alloc_col_from_matrix (gsl_matrix_ushort * m, const size_t j); void gsl_matrix_ushort_free (gsl_matrix_ushort * m); /* Views */ _gsl_matrix_ushort_view gsl_matrix_ushort_submatrix (gsl_matrix_ushort * m, const size_t i, const size_t j, const size_t n1, const size_t n2); _gsl_vector_ushort_view gsl_matrix_ushort_row (gsl_matrix_ushort * m, const size_t i); _gsl_vector_ushort_view gsl_matrix_ushort_column (gsl_matrix_ushort * m, const size_t j); _gsl_vector_ushort_view gsl_matrix_ushort_diagonal (gsl_matrix_ushort * m); _gsl_vector_ushort_view gsl_matrix_ushort_subdiagonal (gsl_matrix_ushort * m, const size_t k); _gsl_vector_ushort_view gsl_matrix_ushort_superdiagonal (gsl_matrix_ushort * m, const size_t k); _gsl_matrix_ushort_view gsl_matrix_ushort_view_array (unsigned short * base, const size_t n1, const size_t n2); _gsl_matrix_ushort_view gsl_matrix_ushort_view_array_with_tda (unsigned short * base, const size_t n1, const size_t n2, const size_t tda); _gsl_matrix_ushort_view gsl_matrix_ushort_view_vector (gsl_vector_ushort * v, const size_t n1, const size_t n2); _gsl_matrix_ushort_view gsl_matrix_ushort_view_vector_with_tda (gsl_vector_ushort * v, const size_t n1, const size_t n2, const size_t tda); _gsl_matrix_ushort_const_view gsl_matrix_ushort_const_submatrix (const gsl_matrix_ushort * m, const size_t i, const size_t j, const size_t n1, const size_t n2); _gsl_vector_ushort_const_view gsl_matrix_ushort_const_row (const gsl_matrix_ushort * m, const size_t i); _gsl_vector_ushort_const_view gsl_matrix_ushort_const_column (const gsl_matrix_ushort * m, const size_t j); _gsl_vector_ushort_const_view gsl_matrix_ushort_const_diagonal (const gsl_matrix_ushort * m); _gsl_vector_ushort_const_view gsl_matrix_ushort_const_subdiagonal (const gsl_matrix_ushort * m, const size_t k); _gsl_vector_ushort_const_view gsl_matrix_ushort_const_superdiagonal (const gsl_matrix_ushort * m, const size_t k); _gsl_matrix_ushort_const_view gsl_matrix_ushort_const_view_array (const unsigned short * base, const size_t n1, const size_t n2); _gsl_matrix_ushort_const_view gsl_matrix_ushort_const_view_array_with_tda (const unsigned short * base, const size_t n1, const size_t n2, const size_t tda); _gsl_matrix_ushort_const_view gsl_matrix_ushort_const_view_vector (const gsl_vector_ushort * v, const size_t n1, const size_t n2); _gsl_matrix_ushort_const_view gsl_matrix_ushort_const_view_vector_with_tda (const gsl_vector_ushort * v, const size_t n1, const size_t n2, const size_t tda); /* Operations */ unsigned short gsl_matrix_ushort_get(const gsl_matrix_ushort * m, const size_t i, const size_t j); void gsl_matrix_ushort_set(gsl_matrix_ushort * m, const size_t i, const size_t j, const unsigned short x); unsigned short * gsl_matrix_ushort_ptr(gsl_matrix_ushort * m, const size_t i, const size_t j); const unsigned short * gsl_matrix_ushort_const_ptr(const gsl_matrix_ushort * m, const size_t i, const size_t j); void gsl_matrix_ushort_set_zero (gsl_matrix_ushort * m); void gsl_matrix_ushort_set_identity (gsl_matrix_ushort * m); void gsl_matrix_ushort_set_all (gsl_matrix_ushort * m, unsigned short x); int gsl_matrix_ushort_fread (FILE * stream, gsl_matrix_ushort * m) ; int gsl_matrix_ushort_fwrite (FILE * stream, const gsl_matrix_ushort * m) ; int gsl_matrix_ushort_fscanf (FILE * stream, gsl_matrix_ushort * m); int gsl_matrix_ushort_fprintf (FILE * stream, const gsl_matrix_ushort * m, const char * format); int gsl_matrix_ushort_memcpy(gsl_matrix_ushort * dest, const gsl_matrix_ushort * src); int gsl_matrix_ushort_swap(gsl_matrix_ushort * m1, const gsl_matrix_ushort * m2); int gsl_matrix_ushort_swap_rows(gsl_matrix_ushort * m, const size_t i, const size_t j); int gsl_matrix_ushort_swap_columns(gsl_matrix_ushort * m, const size_t i, const size_t j); int gsl_matrix_ushort_swap_rowcol(gsl_matrix_ushort * m, const size_t i, const size_t j); int gsl_matrix_ushort_transpose (gsl_matrix_ushort * m); int gsl_matrix_ushort_transpose_memcpy (gsl_matrix_ushort * dest, const gsl_matrix_ushort * src); unsigned short gsl_matrix_ushort_max (const gsl_matrix_ushort * m); unsigned short gsl_matrix_ushort_min (const gsl_matrix_ushort * m); void gsl_matrix_ushort_minmax (const gsl_matrix_ushort * m, unsigned short * min_out, unsigned short * max_out); void gsl_matrix_ushort_max_index (const gsl_matrix_ushort * m, size_t * imax, size_t *jmax); void gsl_matrix_ushort_min_index (const gsl_matrix_ushort * m, size_t * imin, size_t *jmin); void gsl_matrix_ushort_minmax_index (const gsl_matrix_ushort * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax); int gsl_matrix_ushort_isnull (const gsl_matrix_ushort * m); int gsl_matrix_ushort_add (gsl_matrix_ushort * a, const gsl_matrix_ushort * b); int gsl_matrix_ushort_sub (gsl_matrix_ushort * a, const gsl_matrix_ushort * b); int gsl_matrix_ushort_mul_elements (gsl_matrix_ushort * a, const gsl_matrix_ushort * b); int gsl_matrix_ushort_div_elements (gsl_matrix_ushort * a, const gsl_matrix_ushort * b); int gsl_matrix_ushort_scale (gsl_matrix_ushort * a, const double x); int gsl_matrix_ushort_add_constant (gsl_matrix_ushort * a, const double x); /***********************************************************************/ /* The functions below are obsolete */ /***********************************************************************/ int gsl_matrix_ushort_get_row(gsl_vector_ushort * v, const gsl_matrix_ushort * m, const size_t i); int gsl_matrix_ushort_get_col(gsl_vector_ushort * v, const gsl_matrix_ushort * m, const size_t j); int gsl_matrix_ushort_set_row(gsl_matrix_ushort * m, const size_t i, const gsl_vector_ushort * v); int gsl_matrix_ushort_set_col(gsl_matrix_ushort * m, const size_t j, const gsl_vector_ushort * v); extern int gsl_check_range ; /* inline functions if you are using GCC */ #ifdef HAVE_INLINE extern inline unsigned short gsl_matrix_ushort_get(const gsl_matrix_ushort * m, const size_t i, const size_t j) { #ifndef GSL_RANGE_CHECK_OFF if (i >= m->size1) { GSL_ERROR_VAL("first index out of range", GSL_EINVAL, 0) ; } else if (j >= m->size2) { GSL_ERROR_VAL("second index out of range", GSL_EINVAL, 0) ; } #endif return m->data[i * m->tda + j] ; } extern inline void gsl_matrix_ushort_set(gsl_matrix_ushort * m, const size_t i, const size_t j, const unsigned short x) { #ifndef GSL_RANGE_CHECK_OFF if (i >= m->size1) { GSL_ERROR_VOID("first index out of range", GSL_EINVAL) ; } else if (j >= m->size2) { GSL_ERROR_VOID("second index out of range", GSL_EINVAL) ; } #endif m->data[i * m->tda + j] = x ; } extern inline unsigned short * gsl_matrix_ushort_ptr(gsl_matrix_ushort * m, const size_t i, const size_t j) { #ifndef GSL_RANGE_CHECK_OFF if (i >= m->size1) { GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ; } else if (j >= m->size2) { GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ; } #endif return (unsigned short *) (m->data + (i * m->tda + j)) ; } extern inline const unsigned short * gsl_matrix_ushort_const_ptr(const gsl_matrix_ushort * m, const size_t i, const size_t j) { #ifndef GSL_RANGE_CHECK_OFF if (i >= m->size1) { GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ; } else if (j >= m->size2) { GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ; } #endif return (const unsigned short *) (m->data + (i * m->tda + j)) ; } #endif __END_DECLS #endif /* __GSL_MATRIX_USHORT_H__ */
{ "alphanum_fraction": 0.6706197058, "avg_line_length": 35.4905063291, "ext": "h", "hexsha": "c5baa9812af5019d4edb36919cff05365623d93a", "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/matrix/gsl_matrix_ushort.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/matrix/gsl_matrix_ushort.h", "max_line_length": 126, "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/matrix/gsl_matrix_ushort.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": 2771, "size": 11215 }
/* randist/test.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, 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. */ #include <config.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_test.h> #include <gsl/gsl_ieee_utils.h> #define N 100000 void testMoments (double (*f) (void), const char *name, double a, double b, double p); void testPDF (double (*f) (void), double (*pdf)(double), const char *name); void testDiscretePDF (double (*f) (void), double (*pdf)(unsigned int), const char *name); void test_shuffle (void); void test_choose (void); double test_beta (void); double test_beta_pdf (double x); double test_bernoulli (void); double test_bernoulli_pdf (unsigned int n); double test_binomial (void); double test_binomial_pdf (unsigned int n); double test_binomial_large (void); double test_binomial_large_pdf (unsigned int n); double test_cauchy (void); double test_cauchy_pdf (double x); double test_chisq (void); double test_chisq_pdf (double x); double test_discrete1 (void); double test_discrete1_pdf (unsigned int n); double test_discrete2 (void); double test_discrete2_pdf (unsigned int n); double test_erlang (void); double test_erlang_pdf (double x); double test_exponential (void); double test_exponential_pdf (double x); double test_exppow0 (void); double test_exppow0_pdf (double x); double test_exppow1 (void); double test_exppow1_pdf (double x); double test_exppow1a (void); double test_exppow1a_pdf (double x); double test_exppow2 (void); double test_exppow2_pdf (double x); double test_exppow2a (void); double test_exppow2a_pdf (double x); double test_fdist (void); double test_fdist_pdf (double x); double test_flat (void); double test_flat_pdf (double x); double test_gamma (void); double test_gamma_pdf (double x); double test_gamma1 (void); double test_gamma1_pdf (double x); double test_gamma_int (void); double test_gamma_int_pdf (double x); double test_gamma_large (void); double test_gamma_large_pdf (double x); double test_gaussian (void); double test_gaussian_pdf (double x); double test_gaussian_ratio_method (void); double test_gaussian_ratio_method_pdf (double x); double test_gaussian_tail (void); double test_gaussian_tail_pdf (double x); double test_gaussian_tail1 (void); double test_gaussian_tail1_pdf (double x); double test_gaussian_tail2 (void); double test_gaussian_tail2_pdf (double x); double test_ugaussian (void); double test_ugaussian_pdf (double x); double test_ugaussian_ratio_method (void); double test_ugaussian_ratio_method_pdf (double x); double test_ugaussian_tail (void); double test_ugaussian_tail_pdf (double x); double test_bivariate_gaussian1 (void); double test_bivariate_gaussian1_pdf (double x); double test_bivariate_gaussian2 (void); double test_bivariate_gaussian2_pdf (double x); double test_bivariate_gaussian3 (void); double test_bivariate_gaussian3_pdf (double x); double test_bivariate_gaussian4 (void); double test_bivariate_gaussian4_pdf (double x); double test_gumbel1 (void); double test_gumbel1_pdf (double x); double test_gumbel2 (void); double test_gumbel2_pdf (double x); double test_geometric (void); double test_geometric_pdf (unsigned int x); double test_geometric1 (void); double test_geometric1_pdf (unsigned int x); double test_hypergeometric1 (void); double test_hypergeometric1_pdf (unsigned int x); double test_hypergeometric2 (void); double test_hypergeometric2_pdf (unsigned int x); double test_hypergeometric3 (void); double test_hypergeometric3_pdf (unsigned int x); double test_hypergeometric4 (void); double test_hypergeometric4_pdf (unsigned int x); double test_hypergeometric5 (void); double test_hypergeometric5_pdf (unsigned int x); double test_hypergeometric6 (void); double test_hypergeometric6_pdf (unsigned int x); double test_landau (void); double test_landau_pdf (double x); double test_levy1 (void); double test_levy1_pdf (double x); double test_levy2 (void); double test_levy2_pdf (double x); double test_levy1a (void); double test_levy1a_pdf (double x); double test_levy2a (void); double test_levy2a_pdf (double x); double test_levy_skew1 (void); double test_levy_skew1_pdf (double x); double test_levy_skew2 (void); double test_levy_skew2_pdf (double x); double test_levy_skew1a (void); double test_levy_skew1a_pdf (double x); double test_levy_skew2a (void); double test_levy_skew2a_pdf (double x); double test_levy_skew1b (void); double test_levy_skew1b_pdf (double x); double test_levy_skew2b (void); double test_levy_skew2b_pdf (double x); double test_logistic (void); double test_logistic_pdf (double x); double test_lognormal (void); double test_lognormal_pdf (double x); double test_logarithmic (void); double test_logarithmic_pdf (unsigned int n); double test_negative_binomial (void); double test_negative_binomial_pdf (unsigned int n); double test_pascal (void); double test_pascal_pdf (unsigned int n); double test_pareto (void); double test_pareto_pdf (double x); double test_poisson (void); double test_poisson_pdf (unsigned int x); double test_poisson_large (void); double test_poisson_large_pdf (unsigned int x); double test_dir2d (void); double test_dir2d_pdf (double x); double test_dir2d_trig_method (void); double test_dir2d_trig_method_pdf (double x); double test_dir3dxy (void); double test_dir3dxy_pdf (double x); double test_dir3dyz (void); double test_dir3dyz_pdf (double x); double test_dir3dzx (void); double test_dir3dzx_pdf (double x); double test_rayleigh (void); double test_rayleigh_pdf (double x); double test_rayleigh_tail (void); double test_rayleigh_tail_pdf (double x); double test_tdist1 (void); double test_tdist1_pdf (double x); double test_tdist2 (void); double test_tdist2_pdf (double x); double test_laplace (void); double test_laplace_pdf (double x); double test_weibull (void); double test_weibull_pdf (double x); double test_weibull1 (void); double test_weibull1_pdf (double x); gsl_rng *r_global; int main (void) { gsl_ieee_env_setup (); gsl_rng_env_setup() ; r_global = gsl_rng_alloc (gsl_rng_default); #define FUNC(x) test_ ## x, "test gsl_ran_" #x #define FUNC2(x) test_ ## x, test_ ## x ## _pdf, "test gsl_ran_" #x test_shuffle() ; test_choose() ; testMoments (FUNC (ugaussian), 0.0, 100.0, 0.5); testMoments (FUNC (ugaussian), -1.0, 1.0, 0.6826895); testMoments (FUNC (ugaussian), 3.0, 3.5, 0.0011172689); testMoments (FUNC (ugaussian_tail), 3.0, 3.5, 0.0011172689/0.0013498981); testMoments (FUNC (exponential), 0.0, 1.0, 1- exp(-0.5)); testMoments (FUNC (cauchy), 0.0, 10000.0, 0.5); testMoments (FUNC (discrete1), -0.5, 0.5, 0.59 ); testMoments (FUNC (discrete1), 0.5, 1.5, 0.40 ); testMoments (FUNC (discrete1), 1.5, 3.5, 0.01 ); testPDF (FUNC2(beta)); testPDF (FUNC2(cauchy)); testPDF (FUNC2(chisq)); testPDF (FUNC2(erlang)); testPDF (FUNC2(exponential)); testPDF (FUNC2(exppow0)); testPDF (FUNC2(exppow1)); testPDF (FUNC2(exppow1a)); testPDF (FUNC2(exppow2)); testPDF (FUNC2(exppow2a)); testPDF (FUNC2(fdist)); testPDF (FUNC2(flat)); testPDF (FUNC2(gamma)); testPDF (FUNC2(gamma1)); testPDF (FUNC2(gamma_int)); testPDF (FUNC2(gamma_large)); testPDF (FUNC2(gaussian)); testPDF (FUNC2(gaussian_ratio_method)); testPDF (FUNC2(ugaussian)); testPDF (FUNC2(ugaussian_ratio_method)); testPDF (FUNC2(gaussian_tail)); testPDF (FUNC2(gaussian_tail1)); testPDF (FUNC2(gaussian_tail2)); testPDF (FUNC2(ugaussian_tail)); testPDF (FUNC2(bivariate_gaussian1)); testPDF (FUNC2(bivariate_gaussian2)); testPDF (FUNC2(bivariate_gaussian3)); testPDF (FUNC2(bivariate_gaussian4)); testPDF (FUNC2(gumbel1)); testPDF (FUNC2(gumbel2)); testPDF (FUNC2(landau)); testPDF (FUNC2(levy1)); testPDF (FUNC2(levy2)); testPDF (FUNC2(levy1a)); testPDF (FUNC2(levy2a)); testPDF (FUNC2(levy_skew1)); testPDF (FUNC2(levy_skew2)); testPDF (FUNC2(levy_skew1a)); testPDF (FUNC2(levy_skew2a)); testPDF (FUNC2(levy_skew1b)); testPDF (FUNC2(levy_skew2b)); testPDF (FUNC2(logistic)); testPDF (FUNC2(lognormal)); testPDF (FUNC2(pareto)); testPDF (FUNC2(rayleigh)); testPDF (FUNC2(rayleigh_tail)); testPDF (FUNC2(tdist1)); testPDF (FUNC2(tdist2)); testPDF (FUNC2(laplace)); testPDF (FUNC2(weibull)); testPDF (FUNC2(weibull1)); testPDF (FUNC2(dir2d)); testPDF (FUNC2(dir2d_trig_method)); testPDF (FUNC2(dir3dxy)); testPDF (FUNC2(dir3dyz)); testPDF (FUNC2(dir3dzx)); testDiscretePDF (FUNC2(discrete1)); testDiscretePDF (FUNC2(discrete2)); testDiscretePDF (FUNC2(poisson)); testDiscretePDF (FUNC2(poisson_large)); testDiscretePDF (FUNC2(bernoulli)); testDiscretePDF (FUNC2(binomial)); testDiscretePDF (FUNC2(binomial_large)); testDiscretePDF (FUNC2(geometric)); testDiscretePDF (FUNC2(geometric1)); testDiscretePDF (FUNC2(hypergeometric1)); testDiscretePDF (FUNC2(hypergeometric2)); testDiscretePDF (FUNC2(hypergeometric3)); testDiscretePDF (FUNC2(hypergeometric4)); testDiscretePDF (FUNC2(hypergeometric5)); testDiscretePDF (FUNC2(hypergeometric6)); testDiscretePDF (FUNC2(logarithmic)); testDiscretePDF (FUNC2(negative_binomial)); testDiscretePDF (FUNC2(pascal)); exit (gsl_test_summary()); } void test_shuffle (void) { double count[10][10] ; int x[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} ; int i, j, status = 0; for (i = 0; i < 10; i++) { for (j = 0; j < 10; j++) { count[i][j] = 0 ; } } for (i = 0 ; i < N; i++) { for (j = 0; j < 10; j++) x[j] = j ; gsl_ran_shuffle (r_global, x, 10, sizeof(int)) ; for (j = 0; j < 10; j++) count[x[j]][j] ++ ; } for (i = 0; i < 10; i++) { for (j = 0; j < 10; j++) { double expected = N / 10.0 ; double d = fabs(count[i][j] - expected); double sigma = d / sqrt(expected) ; if (sigma > 5 && d > 1) { status = 1 ; gsl_test (status, "gsl_ran_shuffle %d,%d (%g observed vs %g expected)", i, j, count[i][j]/N, 0.1) ; } } } gsl_test (status, "gsl_ran_shuffle on {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}") ; } void test_choose (void) { double count[10] ; int x[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} ; int y[3] = {0, 1, 2} ; int i, j, status = 0; for (i = 0; i < 10; i++) { count[i] = 0 ; } for (i = 0 ; i < N; i++) { for (j = 0; j < 10; j++) x[j] = j ; gsl_ran_choose (r_global, y, 3, x, 10, sizeof(int)) ; for (j = 0; j < 3; j++) count[y[j]]++ ; } for (i = 0; i < 10; i++) { double expected = 3.0 * N / 10.0 ; double d = fabs(count[i] - expected); double sigma = d / sqrt(expected) ; if (sigma > 5 && d > 1) { status = 1 ; gsl_test (status, "gsl_ran_choose %d (%g observed vs %g expected)", i, count[i]/N, 0.1) ; } } gsl_test (status, "gsl_ran_choose (3) on {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}") ; } void testMoments (double (*f) (void), const char *name, double a, double b, double p) { int i; double count = 0, expected, sigma; int status; for (i = 0; i < N; i++) { double r = f (); if (r < b && r > a) count++; } expected = p * N; sigma = fabs (count - expected) / sqrt (expected); status = (sigma > 3); gsl_test (status, "%s [%g,%g] (%g observed vs %g expected)", name, a, b, count / N, p); } #define BINS 100 void testPDF (double (*f) (void), double (*pdf)(double), const char *name) { double count[BINS], p[BINS]; double a = -5.0, b = +5.0 ; double dx = (b - a) / BINS ; int i,j,status = 0, status_i =0 ; for (i = 0; i < BINS; i++) count[i] = 0 ; for (i = 0; i < N; i++) { double r = f (); if (r < b && r > a) { j = (int)((r - a)/dx) ; count[j]++; } } for (i = 0; i < BINS; i++) { /* Compute an approximation to the integral of p(x) from x to x+dx using Simpson's rule */ double x = a + i * dx ; #define STEPS 100 double sum = 0 ; if (fabs(x) < 1e-10) /* hit the origin exactly */ x = 0.0 ; for (j = 1; j < STEPS; j++) sum += pdf(x + j * dx / STEPS) ; p[i] = 0.5 * (pdf(x) + 2*sum + pdf(x + dx - 1e-7)) * dx / STEPS ; } for (i = 0; i < BINS; i++) { double x = a + i * dx ; double d = fabs(count[i] - N*p[i]) ; if (p[i] != 0) { double s = d / sqrt(N*p[i]) ; status_i = (s > 5) && (d > 1) ; } else { status_i = (count[i] != 0) ; } status |= status_i ; if (status_i) gsl_test (status_i, "%s [%g,%g) (%g/%d=%g observed vs %g expected)", name, x, x+dx, count[i],N,count[i]/N, p[i]) ; } if (status == 0) gsl_test (status, "%s, sampling against pdf over range [%g,%g) ", name, a, b) ; } void testDiscretePDF (double (*f) (void), double (*pdf)(unsigned int), const char *name) { double count[BINS], p[BINS]; unsigned int i ; int status = 0, status_i =0 ; for (i = 0; i < BINS; i++) count[i] = 0 ; for (i = 0; i < N; i++) { int r = (int)(f ()); if (r>= 0 && r < BINS) count[r]++; } for (i = 0; i < BINS; i++) p[i] = pdf(i) ; for (i = 0; i < BINS; i++) { double d = fabs(count[i] - N*p[i]) ; if (p[i] != 0) { double s = d/sqrt(N*p[i]) ; status_i = (s > 5) && (d > 1); } else { status_i = (count[i] != 0) ; } status |= status_i ; if (status_i) gsl_test (status_i, "%s i=%d (%g observed vs %g expected)", name, i, count[i]/N, p[i]) ; } if (status == 0) gsl_test (status, "%s, sampling against pdf over range [%d,%d) ", name, 0, BINS) ; } double test_beta (void) { return gsl_ran_beta (r_global, 2.0, 3.0); } double test_beta_pdf (double x) { return gsl_ran_beta_pdf (x, 2.0, 3.0); } double test_bernoulli (void) { return gsl_ran_bernoulli (r_global, 0.3); } double test_bernoulli_pdf (unsigned int n) { return gsl_ran_bernoulli_pdf (n, 0.3); } double test_binomial (void) { return gsl_ran_binomial (r_global, 0.3, 5); } double test_binomial_pdf (unsigned int n) { return gsl_ran_binomial_pdf (n, 0.3, 5); } double test_binomial_large (void) { return gsl_ran_binomial (r_global, 0.3, 55); } double test_binomial_large_pdf (unsigned int n) { return gsl_ran_binomial_pdf (n, 0.3, 55); } double test_cauchy (void) { return gsl_ran_cauchy (r_global, 2.0); } double test_cauchy_pdf (double x) { return gsl_ran_cauchy_pdf (x, 2.0); } double test_chisq (void) { return gsl_ran_chisq (r_global, 13.0); } double test_chisq_pdf (double x) { return gsl_ran_chisq_pdf (x, 13.0); } double test_dir2d (void) { double x=0, y=0, theta; gsl_ran_dir_2d (r_global, &x, &y); theta = atan2(x,y); return theta; } double test_dir2d_pdf (double x) { if (x > -M_PI && x <= M_PI) { return 1 / (2 * M_PI) ; } else { return 0 ; } } double test_dir2d_trig_method (void) { double x=0, y=0, theta; gsl_ran_dir_2d_trig_method (r_global, &x, &y); theta = atan2(x,y); return theta; } double test_dir2d_trig_method_pdf (double x) { if (x > -M_PI && x <= M_PI) { return 1 / (2 * M_PI) ; } else { return 0 ; } } double test_dir3dxy (void) { double x=0, y=0, z=0, theta; gsl_ran_dir_3d (r_global, &x, &y, &z); theta = atan2(x,y); return theta; } double test_dir3dxy_pdf (double x) { if (x > -M_PI && x <= M_PI) { return 1 / (2 * M_PI) ; } else { return 0 ; } } double test_dir3dyz (void) { double x=0, y=0, z=0, theta; gsl_ran_dir_3d (r_global, &x, &y, &z); theta = atan2(y,z); return theta; } double test_dir3dyz_pdf (double x) { if (x > -M_PI && x <= M_PI) { return 1 / (2 * M_PI) ; } else { return 0 ; } } double test_dir3dzx (void) { double x=0, y=0, z=0, theta; gsl_ran_dir_3d (r_global, &x, &y, &z); theta = atan2(z,x); return theta; } double test_dir3dzx_pdf (double x) { if (x > -M_PI && x <= M_PI) { return 1 / (2 * M_PI) ; } else { return 0 ; } } static gsl_ran_discrete_t *g1 = NULL; static gsl_ran_discrete_t *g2 = NULL; double test_discrete1 (void) { static double P[3]={0.59, 0.4, 0.01}; if (g1==NULL) { g1 = gsl_ran_discrete_preproc(3,P); } return gsl_ran_discrete(r_global,g1); } double test_discrete1_pdf (unsigned int n) { return gsl_ran_discrete_pdf((size_t)n,g1); } double test_discrete2 (void) { static double P[10]={ 1, 9, 3, 4, 5, 8, 6, 7, 2, 0 }; if (g2==NULL) { g2 = gsl_ran_discrete_preproc(10,P); } return gsl_ran_discrete(r_global,g2); } double test_discrete2_pdf (unsigned int n) { return gsl_ran_discrete_pdf((size_t)n,g2); } double test_erlang (void) { return gsl_ran_erlang (r_global, 3.0, 4.0); } double test_erlang_pdf (double x) { return gsl_ran_erlang_pdf (x, 3.0, 4.0); } double test_exponential (void) { return gsl_ran_exponential (r_global, 2.0); } double test_exponential_pdf (double x) { return gsl_ran_exponential_pdf (x, 2.0); } double test_exppow0 (void) { return gsl_ran_exppow (r_global, 3.7, 0.3); } double test_exppow0_pdf (double x) { return gsl_ran_exppow_pdf (x, 3.7, 0.3); } double test_exppow1 (void) { return gsl_ran_exppow (r_global, 3.7, 1.0); } double test_exppow1_pdf (double x) { return gsl_ran_exppow_pdf (x, 3.7, 1.0); } double test_exppow1a (void) { return gsl_ran_exppow (r_global, 3.7, 1.9); } double test_exppow1a_pdf (double x) { return gsl_ran_exppow_pdf (x, 3.7, 1.9); } double test_exppow2 (void) { return gsl_ran_exppow (r_global, 3.7, 2.0); } double test_exppow2_pdf (double x) { return gsl_ran_exppow_pdf (x, 3.7, 2.0); } double test_exppow2a (void) { return gsl_ran_exppow (r_global, 3.7, 7.5); } double test_exppow2a_pdf (double x) { return gsl_ran_exppow_pdf (x, 3.7, 7.5); } double test_fdist (void) { return gsl_ran_fdist (r_global, 3.0, 4.0); } double test_fdist_pdf (double x) { return gsl_ran_fdist_pdf (x, 3.0, 4.0); } double test_flat (void) { return gsl_ran_flat (r_global, 3.0, 4.0); } double test_flat_pdf (double x) { return gsl_ran_flat_pdf (x, 3.0, 4.0); } double test_gamma (void) { return gsl_ran_gamma (r_global, 2.5, 2.17); } double test_gamma_pdf (double x) { return gsl_ran_gamma_pdf (x, 2.5, 2.17); } double test_gamma1 (void) { return gsl_ran_gamma (r_global, 1.0, 2.17); } double test_gamma1_pdf (double x) { return gsl_ran_gamma_pdf (x, 1.0, 2.17); } double test_gamma_int (void) { return gsl_ran_gamma (r_global, 10.0, 2.17); } double test_gamma_int_pdf (double x) { return gsl_ran_gamma_pdf (x, 10.0, 2.17); } double test_gamma_large (void) { return gsl_ran_gamma (r_global, 20.0, 2.17); } double test_gamma_large_pdf (double x) { return gsl_ran_gamma_pdf (x, 20.0, 2.17); } double test_gaussian (void) { return gsl_ran_gaussian (r_global, 3.0); } double test_gaussian_pdf (double x) { return gsl_ran_gaussian_pdf (x, 3.0); } double test_gaussian_ratio_method (void) { return gsl_ran_gaussian_ratio_method (r_global, 3.0); } double test_gaussian_ratio_method_pdf (double x) { return gsl_ran_gaussian_pdf (x, 3.0); } double test_gaussian_tail (void) { return gsl_ran_gaussian_tail (r_global, 1.7, 0.25); } double test_gaussian_tail_pdf (double x) { return gsl_ran_gaussian_tail_pdf (x, 1.7, 0.25) ; } double test_gaussian_tail1 (void) { return gsl_ran_gaussian_tail (r_global, -1.7, 5.0); } double test_gaussian_tail1_pdf (double x) { return gsl_ran_gaussian_tail_pdf (x, -1.7, 5.0) ; } double test_gaussian_tail2 (void) { return gsl_ran_gaussian_tail (r_global, 0.1, 2.0); } double test_gaussian_tail2_pdf (double x) { return gsl_ran_gaussian_tail_pdf (x, 0.1, 2.0) ; } double test_ugaussian (void) { return gsl_ran_ugaussian (r_global); } double test_ugaussian_pdf (double x) { return gsl_ran_ugaussian_pdf (x); } double test_ugaussian_ratio_method (void) { return gsl_ran_ugaussian_ratio_method (r_global); } double test_ugaussian_ratio_method_pdf (double x) { return gsl_ran_ugaussian_pdf (x); } double test_ugaussian_tail (void) { return gsl_ran_ugaussian_tail (r_global, 3.0); } double test_ugaussian_tail_pdf (double x) { return gsl_ran_ugaussian_tail_pdf (x, 3.0) ; } double test_bivariate_gaussian1 (void) { double x = 0, y = 0; gsl_ran_bivariate_gaussian (r_global, 3.0, 2.0, 0.3, &x, &y); return x ; } double test_bivariate_gaussian1_pdf (double x) { return gsl_ran_gaussian_pdf (x, 3.0); } double test_bivariate_gaussian2 (void) { double x = 0, y = 0; gsl_ran_bivariate_gaussian (r_global, 3.0, 2.0, 0.3, &x, &y); return y ; } double test_bivariate_gaussian2_pdf (double y) { int i, n = 10 ; double sum = 0 ; double a = -10, b = 10, dx = (b - a)/n ; for (i = 0; i < n ; i++) { double x = a + i * dx ; sum += gsl_ran_bivariate_gaussian_pdf (x, y, 3.0, 2.0, 0.3) * dx ; } return sum ; } double test_bivariate_gaussian3 (void) { double x = 0, y = 0; gsl_ran_bivariate_gaussian (r_global, 3.0, 2.0, 0.3, &x, &y); return x + y ; } double test_bivariate_gaussian3_pdf (double x) { double sx = 3.0, sy = 2.0, r = 0.3; double su = (sx+r*sy) ; double sv = sy*sqrt(1-r*r) ; double sigma = sqrt(su*su + sv*sv) ; return gsl_ran_gaussian_pdf (x, sigma); } double test_bivariate_gaussian4 (void) { double x = 0, y = 0; gsl_ran_bivariate_gaussian (r_global, 3.0, 2.0, -0.5, &x, &y); return x + y ; } double test_bivariate_gaussian4_pdf (double x) { double sx = 3.0, sy = 2.0, r = -0.5; double su = (sx+r*sy) ; double sv = sy*sqrt(1-r*r) ; double sigma = sqrt(su*su + sv*sv) ; return gsl_ran_gaussian_pdf (x, sigma); } double test_geometric (void) { return gsl_ran_geometric (r_global, 0.5); } double test_geometric_pdf (unsigned int n) { return gsl_ran_geometric_pdf (n, 0.5); } double test_geometric1 (void) { return gsl_ran_geometric (r_global, 1.0); } double test_geometric1_pdf (unsigned int n) { return gsl_ran_geometric_pdf (n, 1.0); } double test_hypergeometric1 (void) { return gsl_ran_hypergeometric (r_global, 5, 7, 4); } double test_hypergeometric1_pdf (unsigned int n) { return gsl_ran_hypergeometric_pdf (n, 5, 7, 4); } double test_hypergeometric2 (void) { return gsl_ran_hypergeometric (r_global, 5, 7, 11); } double test_hypergeometric2_pdf (unsigned int n) { return gsl_ran_hypergeometric_pdf (n, 5, 7, 11); } double test_hypergeometric3 (void) { return gsl_ran_hypergeometric (r_global, 5, 7, 1); } double test_hypergeometric3_pdf (unsigned int n) { return gsl_ran_hypergeometric_pdf (n, 5, 7, 1); } double test_hypergeometric4 (void) { return gsl_ran_hypergeometric (r_global, 5, 7, 20); } double test_hypergeometric4_pdf (unsigned int n) { return gsl_ran_hypergeometric_pdf (n, 5, 7, 20); } double test_hypergeometric5 (void) { return gsl_ran_hypergeometric (r_global, 2, 7, 5); } double test_hypergeometric5_pdf (unsigned int n) { return gsl_ran_hypergeometric_pdf (n, 2, 7, 5); } double test_hypergeometric6 (void) { return gsl_ran_hypergeometric (r_global, 2, 10, 3); } double test_hypergeometric6_pdf (unsigned int n) { return gsl_ran_hypergeometric_pdf (n, 2, 10, 3); } double test_gumbel1 (void) { return gsl_ran_gumbel1 (r_global, 3.12, 4.56); } double test_gumbel1_pdf (double x) { return gsl_ran_gumbel1_pdf (x, 3.12, 4.56); } double test_gumbel2 (void) { return gsl_ran_gumbel2 (r_global, 3.12, 4.56); } double test_gumbel2_pdf (double x) { return gsl_ran_gumbel2_pdf (x, 3.12, 4.56); } double test_landau (void) { return gsl_ran_landau (r_global); } double test_landau_pdf (double x) { return gsl_ran_landau_pdf (x); } double test_levy1 (void) { return gsl_ran_levy (r_global, 5.0, 1.0); } double test_levy1_pdf (double x) { return gsl_ran_cauchy_pdf (x, 5.0); } double test_levy2 (void) { return gsl_ran_levy (r_global, 5.0, 2.0); } double test_levy2_pdf (double x) { return gsl_ran_gaussian_pdf (x, sqrt(2.0) * 5.0 ); } double test_levy1a (void) { return gsl_ran_levy (r_global, 5.0, 1.01); } double test_levy1a_pdf (double x) { return gsl_ran_cauchy_pdf (x, 5.0); } double test_levy2a (void) { return gsl_ran_levy (r_global, 5.0, 1.99); } double test_levy2a_pdf (double x) { return gsl_ran_gaussian_pdf (x, sqrt(2.0) * 5.0 ); } double test_levy_skew1 (void) { return gsl_ran_levy_skew (r_global, 5.0, 1.0, 0.0); } double test_levy_skew1_pdf (double x) { return gsl_ran_cauchy_pdf (x, 5.0); } double test_levy_skew2 (void) { return gsl_ran_levy_skew (r_global, 5.0, 2.0, 0.0); } double test_levy_skew2_pdf (double x) { return gsl_ran_gaussian_pdf (x, sqrt(2.0) * 5.0 ); } double test_levy_skew1a (void) { return gsl_ran_levy_skew (r_global, 5.0, 1.01, 0.0); } double test_levy_skew1a_pdf (double x) { return gsl_ran_cauchy_pdf (x, 5.0); } double test_levy_skew2a (void) { return gsl_ran_levy_skew (r_global, 5.0, 1.99, 0.0); } double test_levy_skew2a_pdf (double x) { return gsl_ran_gaussian_pdf (x, sqrt(2.0) * 5.0 ); } double test_levy_skew1b (void) { return gsl_ran_levy_skew (r_global, 5.0, 1.01, 0.001); } double test_levy_skew1b_pdf (double x) { return gsl_ran_cauchy_pdf (x, 5.0); } double test_levy_skew2b (void) { return gsl_ran_levy_skew (r_global, 5.0, 1.99, 0.001); } double test_levy_skew2b_pdf (double x) { return gsl_ran_gaussian_pdf (x, sqrt(2.0) * 5.0 ); } double test_logistic (void) { return gsl_ran_logistic (r_global, 3.1); } double test_logistic_pdf (double x) { return gsl_ran_logistic_pdf (x, 3.1); } double test_logarithmic (void) { return gsl_ran_logarithmic (r_global, 0.4); } double test_logarithmic_pdf (unsigned int n) { return gsl_ran_logarithmic_pdf (n, 0.4); } double test_lognormal (void) { return gsl_ran_lognormal (r_global, 2.7, 1.3); } double test_lognormal_pdf (double x) { return gsl_ran_lognormal_pdf (x, 2.7, 1.3); } double test_negative_binomial (void) { return gsl_ran_negative_binomial (r_global, 0.3, 20.0); } double test_negative_binomial_pdf (unsigned int n) { return gsl_ran_negative_binomial_pdf (n, 0.3, 20.0); } double test_pascal (void) { return gsl_ran_pascal (r_global, 0.8, 3); } double test_pascal_pdf (unsigned int n) { return gsl_ran_pascal_pdf (n, 0.8, 3); } double test_pareto (void) { return gsl_ran_pareto (r_global, 1.9, 2.75); } double test_pareto_pdf (double x) { return gsl_ran_pareto_pdf (x, 1.9, 2.75); } double test_rayleigh (void) { return gsl_ran_rayleigh (r_global, 1.9); } double test_rayleigh_pdf (double x) { return gsl_ran_rayleigh_pdf (x, 1.9); } double test_rayleigh_tail (void) { return gsl_ran_rayleigh_tail (r_global, 2.7, 1.9); } double test_rayleigh_tail_pdf (double x) { return gsl_ran_rayleigh_tail_pdf (x, 2.7, 1.9); } double test_poisson (void) { return gsl_ran_poisson (r_global, 5.0); } double test_poisson_pdf (unsigned int n) { return gsl_ran_poisson_pdf (n, 5.0); } double test_poisson_large (void) { return gsl_ran_poisson (r_global, 30.0); } double test_poisson_large_pdf (unsigned int n) { return gsl_ran_poisson_pdf (n, 30.0); } double test_tdist1 (void) { return gsl_ran_tdist (r_global, 1.75); } double test_tdist1_pdf (double x) { return gsl_ran_tdist_pdf (x, 1.75); } double test_tdist2 (void) { return gsl_ran_tdist (r_global, 12.75); } double test_tdist2_pdf (double x) { return gsl_ran_tdist_pdf (x, 12.75); } double test_laplace (void) { return gsl_ran_laplace (r_global, 2.75); } double test_laplace_pdf (double x) { return gsl_ran_laplace_pdf (x, 2.75); } double test_weibull (void) { return gsl_ran_weibull (r_global, 3.14, 2.75); } double test_weibull_pdf (double x) { return gsl_ran_weibull_pdf (x, 3.14, 2.75); } double test_weibull1 (void) { return gsl_ran_weibull (r_global, 2.97, 1.0); } double test_weibull1_pdf (double x) { return gsl_ran_weibull_pdf (x, 2.97, 1.0); }
{ "alphanum_fraction": 0.6768290554, "avg_line_length": 18.8760711931, "ext": "c", "hexsha": "8c2cfb066077c1c76d3ad1f6e95722cd24ed2547", "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/randist/test.c", "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/randist/test.c", "max_line_length": 83, "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/randist/test.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": 10245, "size": 28635 }
#pragma once #include "../utils/utils.h" #include <gsl/gsl> namespace Halley { class Compression { public: static Bytes deflate(const Bytes& bytes); static Bytes deflate(gsl::span<const gsl::byte> bytes); static Bytes inflate(const Bytes& bytes); static Bytes inflate(gsl::span<const gsl::byte> bytes); static std::shared_ptr<const char> inflateToSharedPtr(gsl::span<const gsl::byte> bytes, size_t& outSize); static unsigned char* inflateRaw(gsl::span<const gsl::byte> bytes, size_t& outSize); }; }
{ "alphanum_fraction": 0.7300970874, "avg_line_length": 32.1875, "ext": "h", "hexsha": "1611de7c8c5cf14cfc90f03344a9adc937bc58b6", "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/file/compression.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/file/compression.h", "max_line_length": 107, "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/file/compression.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 129, "size": 515 }
/** * @file blas_mangle.h * @brief Macros to "de-mangle" BLAS routines and includes and allow generic calls to them in the code. * @author Moritz Kreutzer <moritz.kreutzer@fau.de> */ #ifndef GHOST_BLAS_MANGLE_H #define GHOST_BLAS_MANGLE_H #include <strings.h> #ifdef GHOST_HAVE_MKL #include <mkl_cblas.h> #elif defined(GHOST_HAVE_GSL) #include <gsl_cblas.h> #else #include <cblas.h> #endif #define blas_order(order) order==GHOST_DENSEMAT_COLMAJOR?CblasColMajor:CblasRowMajor #define blas_trans(trans) trans[0]=='N'?CblasNoTrans:(trans[0]=='C'?CblasConjTrans:CblasTrans) #define sgemm(order,transa,transb,m,n,k,alpha,a,lda,b,ldb,beta,c,ldc) \ cblas_sgemm(blas_order(order),blas_trans(transa),blas_trans(transb),*m,*n,*k,*alpha,a,*lda,b,*ldb,*beta,c,*ldc) #define dgemm(order,transa,transb,m,n,k,alpha,a,lda,b,ldb,beta,c,ldc) \ cblas_dgemm(blas_order(order),blas_trans(transa),blas_trans(transb),*m,*n,*k,*alpha,a,*lda,b,*ldb,*beta,c,*ldc) #define cgemm(order,transa,transb,m,n,k,alpha,a,lda,b,ldb,beta,c,ldc) \ cblas_cgemm(blas_order(order),blas_trans(transa),blas_trans(transb),*m,*n,*k,alpha,a,*lda,b,*ldb,beta,c,*ldc) #define zgemm(order,transa,transb,m,n,k,alpha,a,lda,b,ldb,beta,c,ldc) \ cblas_zgemm(blas_order(order),blas_trans(transa),blas_trans(transb),*m,*n,*k,alpha,a,*lda,b,*ldb,beta,c,*ldc) #endif
{ "alphanum_fraction": 0.7391304348, "avg_line_length": 41.6875, "ext": "h", "hexsha": "28d9e2bd45cacf3e5987aaf57997c7f0253c4ccf", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2017-12-19T19:38:16.000Z", "max_forks_repo_forks_event_min_datetime": "2016-12-14T15:20:12.000Z", "max_forks_repo_head_hexsha": "22a004dbbfb604d7b04b0bde813c8100d403cfcc", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "RRZE-HPC/GHOST", "max_forks_repo_path": "include/ghost/blas_mangle.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "22a004dbbfb604d7b04b0bde813c8100d403cfcc", "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": "RRZE-HPC/GHOST", "max_issues_repo_path": "include/ghost/blas_mangle.h", "max_line_length": 115, "max_stars_count": 10, "max_stars_repo_head_hexsha": "22a004dbbfb604d7b04b0bde813c8100d403cfcc", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "RRZE-HPC/GHOST", "max_stars_repo_path": "include/ghost/blas_mangle.h", "max_stars_repo_stars_event_max_datetime": "2021-07-13T14:15:27.000Z", "max_stars_repo_stars_event_min_datetime": "2017-12-31T00:20:11.000Z", "num_tokens": 456, "size": 1334 }
#ifndef BFM_FRANCIS_H #define BFM_FRANCIS_H #include <cstdlib> #include <string> #include <cmath> #include <iostream> #include <sstream> #include <stdexcept> #include <fstream> #include <complex> #include <algorithm> #include "UTSolve.h" #include "Householder.h" #include <util/time_cps.h> //#define USE_LAPACK //#define USE_EIGEN #ifdef USE_LAPACK #warning "Using LAPACK in Lanczos" #define lapack_complex_float std::complex<float> #define lapack_complex_double std::complex<double> #include <lapacke.h> #endif #ifdef USE_EIGEN #warning "Using EIGEN package in Lanczos" #include <Eigen/Dense> #endif namespace BFM_Krylov{ // template <class T> int SymmEigensystem(Matrix<T > &Ain, std::vector<T> &evals, std::vector<std::vector<T> > &evecs, double small); // template <class T> int Eigensystem(Matrix<T > &Ain, std::vector<T> &evals, std::vector<std::vector<T> > &evecs, double small); /** Find the eigenvalues of an upper hessenberg matrix using the Francis QR algorithm. H = x x x x x x x x x x x x x x x x x x 0 x x x x x x x x 0 0 x x x x x x x 0 0 0 x x x x x x 0 0 0 0 x x x x x 0 0 0 0 0 x x x x 0 0 0 0 0 0 x x x 0 0 0 0 0 0 0 x x Factorization is P T P^H where T is upper triangular (mod cc blocks) and P is orthagonal/unitary. **/ template <class T> int QReigensystem(Matrix<T> &Hin, std::vector<T> &evals, std::vector<std::vector<T> > &evecs, double small){ Matrix<T > H(Hin.dim); H = Hin; ///I don't want to modify the input but matricies must be passed by reference for(int i=0;i<evecs.size();i++){evals[i] = 0;for(int j=0;j<evecs[i].size();j++){evecs[i][j] = 0;}} int N = H.dim; int M = N; T s,t,x=0,y=0,z=0; T u,d; T apd,amd,bc; std::vector<T > p(N,0); T nrm = H.Norm(); ///Matrix Norm int n, m; int e = 0; int it = 0; int tot_it = 0; int l = 0; int r = 0; Matrix<T > P(N); P.Unity(); std::vector<int> trows(N,0); /// Check if the matrix is really hessenberg, if not abort double sth = 0; for(int j=0;j<N;j++){for(int i=j+2;i<N;i++){sth = abs(H(i,j)); if(sth > small){ std::cout << "Non hessenberg H = " << sth << " > " << small << std::endl; exit(1); } }} /** Check for convergence x x x x x 0 x x x x 0 0 x x x 0 0 x x x 0 0 0 0 x for this matrix l = 4 **/ do{ do{ l = H.Chop_subdiag(nrm,e,small); r = 0; ///May have converged on more than one eval ///Single eval if(l == N-1){ evals[e] = H(l,l); N--; e++; r++; it = 0; } ///Double eval if(l == N-2){ trows[l+1] = 1; ///Needed for UTSolve apd = H(l,l) + H(l+1,l+1); amd = H(l,l) - H(l+1,l+1); bc = (T)4.0*H(l+1,l)*H(l,l+1); evals[e] = (T)0.5*( apd + sqrt(amd*amd + bc) ); evals[e+1] = (T)0.5*( apd - sqrt(amd*amd + bc) ); N-=2; e+=2; r++; it = 0; } }while(r>0); if(N ==0){break;} std::vector<T > ck(3), v(3); for(int m = N-3; m >= l; m--){ ///Starting vector essentially random shift. if(it%10 == 0 && N >= 3 && it > 0){ s = (T)1.618033989*( abs( H(N-1,N-2) ) + abs( H(N-2,N-3) ) ); t = (T)0.618033989*( abs( H(N-1,N-2) ) + abs( H(N-2,N-3) ) ); x = H(m,m)*H(m,m) + H(m,m+1)*H(m+1,m) - s*H(m,m) + t; y = H(m+1,m)*(H(m,m) + H(m+1,m+1) - s); z = H(m+1,m)*H(m+2,m+1); } ///Starting vector implicit Q theorem else{ s = (H(N-2,N-2) + H(N-1,N-1)); t = (H(N-2,N-2)*H(N-1,N-1) - H(N-2,N-1)*H(N-1,N-2)); x = H(m,m)*H(m,m) + H(m,m+1)*H(m+1,m) - s*H(m,m) + t; y = H(m+1,m)*(H(m,m) + H(m+1,m+1) - s); z = H(m+1,m)*H(m+2,m+1); } ck[0] = x; ck[1] = y; ck[2] = z; if(m == l) break; /** Some stupid thing from numerical recipies, seems to work**/ u=abs(H(m,m-1))*(abs(y)+abs(z)); d=abs(x)*(abs(H(m-1,m-1))+abs(H(m,m))+abs(H(m+1,m+1))); if ((T)abs(u+d) == (T)abs(d) ){l = m; break;} //if (u < small){l = m; break;} } if(it > 100000){ std::cout << "QReigensystem: bugger it got stuck after 100000 iterations" << std::endl; std::cout << "got " << e << " evals " << l << " " << N << std::endl; exit(1); } normalize(ck); ///Normalization cancels in PHP anyway T beta; Householder_vector<T >(ck, 0, 2, v, beta); Householder_mult<T >(H,v,beta,0,l,l+2,0); Householder_mult<T >(H,v,beta,0,l,l+2,1); ///Accumulate eigenvector Householder_mult<T >(P,v,beta,0,l,l+2,1); int sw = 0; ///Are we on the last row? for(int k=l;k<N-2;k++){ x = H(k+1,k); y = H(k+2,k); z = (T)0.0; if(k+3 <= N-1){z = H(k+3,k);} else{sw = 1; v[2] = (T)0.0;} ck[0] = x; ck[1] = y; ck[2] = z; normalize(ck); Householder_vector<T >(ck, 0, 2-sw, v, beta); Householder_mult<T >(H,v, beta,0,k+1,k+3-sw,0); Householder_mult<T >(H,v, beta,0,k+1,k+3-sw,1); ///Accumulate eigenvector Householder_mult<T >(P,v, beta,0,k+1,k+3-sw,1); } it++; tot_it++; }while(N > 1); N = evals.size(); ///Annoying - UT solves in reverse order; std::vector<T> tmp(N);for(int i=0;i<N;i++){tmp[i] = evals[N-i-1];} evals = tmp; UTeigenvectors(H, trows, evals, evecs); for(int i=0;i<evals.size();i++){evecs[i] = P*evecs[i]; normalize(evecs[i]);} return tot_it; } /** turn a matrix A = x x x x x x x x x x x x x x x x x x x x x x x x x into x x x x x x x x x x 0 x x x x 0 0 x x x 0 0 0 x x with householder rotations Slow. */ template <class T> void Hess(Matrix<T > &A, Matrix<T> &Q, int start){ int N = A.dim; //Matrix Size std::vector<T > p(N,0); for(int k=start;k<N-2;k++){ std::vector<T > ck(N-k-1), v(N-k-1); for(int i=k+1;i<N;i++){ck[i-k-1] = A(i,k);} ///kth column normalize(ck); ///Normalization cancels in PHP anyway T beta; Householder_vector<T >(ck, 0, ck.size()-1, v, beta); ///Householder vector Householder_mult<T>(A,v,beta,start,k+1,N-1,0); ///A -> PA Householder_mult<T >(A,v,beta,start,k+1,N-1,1); ///PA -> PAP^H ///Accumulate eigenvector Householder_mult<T >(Q,v,beta,start,k+1,N-1,1); ///Q -> QP^H } } ///Tridiagonalize a matrix template <class T> void Tri(Matrix<T > &A, Matrix<T> &Q, int start){ int N = A.dim; //Matrix Size Hess(A,Q,start); } ///Tridiagonalize a matrix template <class T> void ForceTridiagonal(Matrix<T > &A){ int N = A.dim; //Matrix Size for(int l=0;l<N-2;l++){ for(int k=l+2;k<N;k++){ A(0,l,k); A(0,k,l); } } } /** Find the eigenvalues of an upper Hessenberg matrix using the Wilkinson QR algorithm. H = x x 0 0 0 0 x x x 0 0 0 0 x x x 0 0 0 0 x x x 0 0 0 0 x x x 0 0 0 0 x x Factorization is P T P^H where T is upper triangular (mod cc blocks) and P is orthagonal/unitary. **/ //Rudy's original version with modifications passed down the ages..... template <class T> int basic_Wilkinson(Matrix<T> &Hin, std::vector<T> &evals, std::vector<std::vector<T> > &evecs, double small) { return basic_Wilkinson(Hin, evals, evecs, small, small); } template <class T> int basic_Wilkinson(Matrix<T> &Hin, std::vector<T> &evals, std::vector<std::vector<T> > &evecs, double small, double tol) { Matrix<T> H(Hin.dim); H = Hin; ///I don't want to modify the input but matricies must be passed by reference (CK: I don't think the author really understands why we usually pass by reference!) //Scale a matrix by its "norm" //double Hnorm = abs( Hin.LargestDiag() ); H = H*(1.0/Hnorm); double Hnorm = abs(Hin.Norm()); H = H * (1.0 / Hnorm); for(int i = 0; i < evecs.size(); ++i){ evals[i] = 0; for(int j = 0; j < evecs[i].size(); ++j) evecs[i][j] = 0; } int N = H.dim; int M = N; T s, t, x = 0, y = 0, z = 0; T u, d; T apd, amd, bc; std::vector<T> p(N, 0); T nrm = H.Norm(); ///Matrix Norm int n, m; int e = 0; int it = 0; int tot_it = 0; int l = 0; int r = 0; Matrix<T> P(N); P.Unity(); std::vector<int> trows(N, 0); /// Check if the matrix is really symm tridiag double sth = 0; for(int j = 0; j < N; ++j){ for(int i = j + 2; i < N; ++i){ if(abs(H(i, j)) > tol || abs(H(j, i)) > tol){ QDPIO::cout << "Non Tridiagonal H(" << i << ","<< j << ") = |" << Real( real( H(j,i) ) ) << "| > " << tol << std::endl; QDPIO::cout << "Warning tridiagonalize and call again" << std::endl; exit(1); } } } do{ do{ //Jasper //Check if the subdiagonal term is small enough (<small) //if true then it is converged. //check start from H.dim - e - 1 //How to deal with more than 2 are converged? //What if Chop_symm_subdiag return something int the middle? //-------------- l = H.Chop_symm_subdiag(nrm, e, small); r = 0; ///May have converged on more than one eval //Jasper //In this case // x x 0 0 0 0 // x x x 0 0 0 // 0 x x x 0 0 // 0 0 x x x 0 // 0 0 0 x x 0 // 0 0 0 0 0 x <- l //-------------- ///Single eval if(l == N - 1){ evals[e] = H(l, l); N--; e++; r++; it = 0; } //Jasper // x x 0 0 0 0 // x x x 0 0 0 // 0 x x x 0 0 // 0 0 x x 0 0 // 0 0 0 0 x x <- l // 0 0 0 0 x x //-------------- ///Double eval if(l == N - 2){ trows[l + 1] = 1; ///Needed for UTSolve apd = H(l, l) + H(l + 1, l + 1); amd = H(l, l) - H(l + 1, l + 1); bc = (T) 4.0 * H(l + 1, l) * H(l, l + 1); evals[e] = (T) 0.5 * (apd + sqrt(amd * amd + bc)); evals[e + 1] = (T) 0.5 * (apd - sqrt(amd * amd + bc)); N -= 2; e += 2; r++; it = 0; } }while(r > 0); //Jasper //Already converged //-------------- if(N == 0) break; std::vector<T> ck(2), v(2); for(int m = N - 3; m >= l; m--){ ///Starting vector essentially random shift. if(it%10 == 0 && N >= 3 && it > 0){ t = abs(H(N - 1, N - 2)) + abs(H(N - 2, N - 3)); x = H(m, m) - t; z = H(m + 1, m); } ///Starting vector implicit Q theorem else{ d = (H(N - 2, N - 2) - H(N - 1, N - 1)) * (T) 0.5; t = H(N - 1, N - 1) - H(N - 1, N - 2) * H(N - 1, N - 2) / (d + sign(d) * sqrt(d * d + H(N - 1, N - 2) * H(N - 1, N - 2))); x = H(m, m) - t; z = H(m + 1, m); } //Jasper //why it is here???? //----------------------- if(m == l) break; u = abs(H(m, m - 1)) * (abs(y) + abs(z)); d = abs(x) * (abs(H(m - 1, m - 1)) + abs(H(m, m)) + abs(H(m + 1, m + 1))); if ((T)abs(u + d) == (T)abs(d)){ l = m; break; } } //Jasper if(it > 1000000){ QDPIO::cout << "Wilkinson: bugger it got stuck after 100000 iterations" << std::endl; QDPIO::cout << "got " << e << " evals " << l << " " << N << std::endl; exit(1); } T s, c; Givens_calc<T>(x, z, c, s); Givens_mult<T>(H, l, l + 1, c, -s, 0); Givens_mult<T>(H, l, l + 1, c, s, 1); Givens_mult<T>(P, l, l + 1, c, s, 1); for(int k = l; k < N - 2; ++k){ x = H(k + 1,k); z = H(k + 2,k); Givens_calc<T>(x, z, c, s); Givens_mult<T>(H, k + 1, k + 2, c, -s, 0); Givens_mult<T>(H, k + 1, k + 2, c, s, 1); Givens_mult<T>(P, k + 1, k + 2, c, s, 1); } it++; tot_it++; }while(N > 1); N = evals.size(); ///Annoying - UT solves in reverse order; std::vector<T> tmp(N); for(int i = 0; i < N; ++i) tmp[i] = evals[N-i-1]; evals = tmp; UTeigenvectors(H, trows, evals, evecs); for(int i = 0; i < evals.size(); ++i){ evecs[i] = P * evecs[i]; normalize(evecs[i]); evals[i] = evals[i] * Hnorm; } return tot_it; } //An implementation using the Eigen package courtesy of Luchang #ifdef USE_EIGEN template <class T> int eigen_Wilkinson(Matrix<T> &Ain, std::vector<T> &evals, std::vector<std::vector<T> > &evecs, double small){ using namespace Eigen; const int size = Ain.dim; evals.resize(size); evecs.resize(size); for (int i = 0; i < size; i++) { evecs[i].resize(size); } MatrixXd A(size, size); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { A(i, j) = 0; } } for (int i = 0; i < size; i++) { for (int j = std::max(0, i-1); j <= std::min(size-1, i+1); j++) { A(i, j) = Ain(i, j); } } SelfAdjointEigenSolver<MatrixXd> eigensolver(A); for (int i = 0; i < size; i++) { evals[i] = eigensolver.eigenvalues()(i); } for (int i = 0; i < size; i++) { std::vector<T>& vec = evecs[i]; for (int j = 0; j < size; j++) { vec[j] = eigensolver.eigenvectors()(j, i); } } return 0; } #endif //An implementation using the LAPACK package courtesy of Luchang #ifdef USE_LAPACK template <class T> int lapackcj_Wilkinson(Matrix<T> &AH, vector<T> &tevals, vector<vector<T> > &tevecs, double small) { double time = -cps::dclock(); const int size = AH.dim; tevals.resize(size); tevecs.resize(size); int NN = tevals.size(); for(int i=0;i<NN;i++) tevecs[i].resize(NN); double evals_tmp[NN]; double evec_tmp[NN][NN]; memset(evec_tmp[0],0,sizeof(double)*NN*NN); double AA[NN][NN]; // double ZZ[NN][NN]; double DD[NN]; double EE[NN]; memset(AA, 0, sizeof(double)*NN*NN); // memset(ZZ, 0, sizeof(double)*NN*NN); for (int i = 0; i< NN; i++) for (int j = i - 1; j <= i + 1; j++) if ( j < NN && j >= 0 ) { AA[i][j] = AH(i,j); if (i==j) DD[i] = AA[i][j]; if (i==j) evals_tmp[i] = AA[i][j]; if (j==(i-1)) EE[j] = AA[i][j]; // if (i<20 && j<20) QDPIO:: cout << "AA["<<i<<"]["<<j<<"]="<<AA[i][j]<<endl; } int evals_found; int lwork = ( (18*NN) > (1+4*NN+NN*NN)? (18*NN):(1+4*NN+NN*NN)) ; int liwork = 3+NN*10 ; int iwork[liwork]; double work[lwork]; int isuppz[2*NN]; char jobz = 'V'; // calculate evals & evecs char range = 'I'; // calculate all evals // char range = 'A'; // calculate all evals char uplo = 'U'; // refer to upper half of original matrix char compz = 'I'; // Compute eigenvectors of tridiagonal matrix int ifail[NN]; int info; // dsyevx(&jobz, &range, &uplo, NN, // AA, NN, // 0, 0, 0, 0, // these four are ignored if second parameteris 'A' // 0, // tolerance // &evals_found, evals_tmp, evec_tmp, NN, // work, lwork, iwork, // ifail, info); int total = QMP_get_number_of_nodes(); int node = QMP_get_node_number(); int interval = (NN/total)+1; double vl = 0.0, vu = 0.0; int il = interval*node+1 , iu = interval*(node+1); if (iu > NN) iu=NN; double tol = 0.0; if (0) { memset(evals_tmp,0,sizeof(double)*NN); if ( il <= NN){ printf("total=%d node=%d il=%d iu=%d\n",total,node,il,iu); LAPACK_dsyevx(&jobz, &range, &uplo, &NN, (double*)AA, &NN, &vl, &vu, &il, &iu, // these four are ignored if second parameteris 'A' &tol, // tolerance &evals_found, evals_tmp, (double*)evec_tmp, &NN, work, &lwork, iwork, ifail, &info); for (int i = iu-1; i>= il-1; i--){ printf("node=%d evals_found=%d evals_tmp[%d] = %g\n",node,evals_found, i - (il-1),evals_tmp[i - (il-1)]); evals_tmp[i] = evals_tmp[i - (il-1)]; if (il>1) evals_tmp[i-(il-1)]=0.; for (int j = 0; j< NN; j++){ evec_tmp[i][j] = evec_tmp[i - (il-1)][j]; if (il>1) evec_tmp[i-(il-1)][j]=0.; } } } { QMP_sum_double_array(evals_tmp,NN); QMP_sum_double_array((double *)evec_tmp,NN*NN); } } else if (1) { memset(evals_tmp,0,sizeof(double)*NN); if ( il <= NN){ printf("total=%d node=%d il=%d iu=%d\n",total,node,il,iu); LAPACK_dstegr(&jobz, &range, &NN, (double*)DD, (double*)EE, &vl, &vu, &il, &iu, // these four are ignored if second parameteris 'A' &tol, // tolerance &evals_found, evals_tmp, (double*)evec_tmp, &NN, isuppz, work, &lwork, iwork, &liwork, &info); for (int i = iu-1; i>= il-1; i--){ printf("node=%d evals_found=%d evals_tmp[%d] = %g\n",node,evals_found, i - (il-1),evals_tmp[i - (il-1)]); evals_tmp[i] = evals_tmp[i - (il-1)]; if (il>1) evals_tmp[i-(il-1)]=0.; for (int j = 0; j< NN; j++){ evec_tmp[i][j] = evec_tmp[i - (il-1)][j]; if (il>1) evec_tmp[i-(il-1)][j]=0.; } } } { QMP_sum_double_array(evals_tmp,NN); QMP_sum_double_array((double *)evec_tmp,NN*NN); } } else if(0) { LAPACK_dsteqr(&compz, &NN, (double*)evals_tmp, (double*)EE, (double*)evec_tmp, &NN, work, &info); } else { LAPACK_dstedc(&compz, &NN, (double*)evals_tmp, (double*)EE, (double*)evec_tmp, &NN, work, &lwork, iwork, &liwork, &info); } for(int i=0;i<NN;i++){ for(int j=0;j<NN;j++) tevecs[i][j]=evec_tmp[i][j]; tevals[i]=evals_tmp[i]; } cps::print_time("lapackcj_Wilkinson","run time",time+cps::dclock()); } #endif template <class T> int Wilkinson(Matrix<T> &Ain, std::vector<T> &evals, std::vector<std::vector<T> > &evecs, double small){ #ifdef USE_LAPACK return lapackcj_Wilkinson(Ain, evals, evecs, small); #elif USE_EIGEN return eigen_Wilkinson(Ain, evals, evecs, small); #else return basic_Wilkinson(Ain, evals, evecs, small); #endif } ///Solve a symmetric eigensystem, not necessarily in tridiagonal form //Rudy's original implementation template <class T> int basic_SymmEigensystem(Matrix<T > &Ain, std::vector<T> &evals, std::vector<std::vector<T> > &evecs, double small){ int N = Ain.dim; Matrix<T > A(N); A = Ain; Matrix<T > Q(N);Q.Unity(); Tri(A,Q,0); int it = basic_Wilkinson<T>(A, evals, evecs, small); for(int k=0;k<N;k++){evecs[k] = Q*evecs[k];} return it; } //I guess Luchang wrote this.... #ifdef USE_EIGEN template <class T> int eigen_SymmEigensystem(Matrix<T> &Ain, std::vector<T> &evals, std::vector<std::vector<T> > &evecs, double small){ using namespace Eigen; const int size = Ain.dim; evals.resize(size); evecs.resize(size); for (int i = 0; i < size; i++) { evecs[i].resize(size); } MatrixXd A(size, size); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { A(i, j) = Ain(i, j); } } SelfAdjointEigenSolver<MatrixXd> eigensolver(A); for (int i = 0; i < size; i++) { evals[i] = eigensolver.eigenvalues()(i); } for (int i = 0; i < size; i++) { std::vector<T>& vec = evecs[i]; for (int j = 0; j < size; j++) { vec[j] = eigensolver.eigenvectors()(j, i); } } return 0; } #endif template <class T> int SymmEigensystem(Matrix<T> &Ain, std::vector<T> &evals, std::vector<std::vector<T> > &evecs, double small){ #ifdef USE_EIGEN return eigen_SymmEigensystem(Ain, evals, evecs, small); #else return basic_SymmEigensystem(Ain, evals, evecs, small); #endif } ///Solve a general eigensystem, not necessarily in tridiagonal form template <class T> int Eigensystem(Matrix<T > &Ain, std::vector<T> &evals, std::vector<std::vector<T> > &evecs, double small){ int N = Ain.dim; Matrix<T > A(N); A = Ain; Matrix<T > Q(N);Q.Unity(); Hess(A,Q,0); int it = QReigensystem<T>(A, evals, evecs, small); for(int k=0;k<N;k++){evecs[k] = Q*evecs[k];} return it; } } #endif
{ "alphanum_fraction": 0.5230313553, "avg_line_length": 27.2729805014, "ext": "h", "hexsha": "3df90f865d8fe7e3a4d87230ffd55ca74190f661", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-12-02T20:41:09.000Z", "max_forks_repo_forks_event_min_datetime": "2020-03-16T05:55:57.000Z", "max_forks_repo_head_hexsha": "329cd411d01dce8e3409335f55e478dac3c3bca4", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "RBC-UKQCD/CPS", "max_forks_repo_path": "cps_pp/include/alg/eigen/Francis.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "329cd411d01dce8e3409335f55e478dac3c3bca4", "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": "RBC-UKQCD/CPS", "max_issues_repo_path": "cps_pp/include/alg/eigen/Francis.h", "max_line_length": 174, "max_stars_count": 7, "max_stars_repo_head_hexsha": "329cd411d01dce8e3409335f55e478dac3c3bca4", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "RBC-UKQCD/CPS", "max_stars_repo_path": "cps_pp/include/alg/eigen/Francis.h", "max_stars_repo_stars_event_max_datetime": "2021-12-02T20:41:00.000Z", "max_stars_repo_stars_event_min_datetime": "2017-06-24T02:20:36.000Z", "num_tokens": 7635, "size": 19582 }
/* * 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 std_9154454e_8e1d_4505_9034_5c7a71b77dd0_h #define std_9154454e_8e1d_4505_9034_5c7a71b77dd0_h #include <xutility> #include <algorithm> #include <memory> #include <list> #include <vector> #include <deque> #include <queue> #include <map> #include <set> #include <stack> #include <unordered_map> #include <unordered_set> #include <comip.h> #include <gslib/type.h> #include <gslib/string.h> __gslib_begin__ class string; /* used for base type delegate */ template<class _inner> struct base_delegator { _inner _puppet; base_delegator() {} base_delegator(const _inner& i): _puppet(i) {} operator _inner() const { return _puppet; } _inner& operator=(const _inner& i) { return _puppet = i; } }; template<class _inner> struct base_ptr_delegator { _inner* _puppet; base_ptr_delegator() { _puppet = 0; } base_ptr_delegator(_inner* ptr) { _puppet = ptr; } operator _inner*() { return _puppet; } operator const _inner*() const { return _puppet; } _inner* operator=(_inner* ptr) { return _puppet = ptr; } }; #if defined(_MSC_VER) && (_MSC_VER < 1910) /* the same as the default std version */ inline size_t hash_bytes(const byte str[], int size) { size_t val = 2166136261U; size_t first = 0; size_t last = (size_t)size; size_t stride = 1 + last / 10; for( ; first < last; first += stride) val = 16777619U * val ^ (size_t)str[first]; return val; } #elif defined(_MSC_VER) && (_MSC_VER < 1916) inline size_t hash_bytes(const byte str[], int size) { return std::_Hash_bytes(str, size); } #else inline size_t hash_bytes(const byte str[], int size) { return std::_Fnv1a_append_bytes(std::_FNV_offset_basis, str, size); } #endif #ifdef _UNICODE inline size_t string_hash(const string& str) { return hash_bytes((const byte*)str.c_str(), str.size() * sizeof(wchar)); } #else inline size_t string_hash(const string& str) { return hash_bytes((const byte*)str.c_str(), str.size()); } #endif #if defined(_MSC_VER) && (_MSC_VER <= 1600) class hasher { public: hasher() { _val = 2166136261u; } size_t add_bytes(const byte* str, int len) { size_t first = 0u; size_t last = (size_t)len; size_t stride = 1 + last / 10; for(; first < last; first += stride) _val = 16777619u * _val ^ (size_t)str[first]; return _val; } size_t get_value() const { return _val; } private: size_t _val; }; #elif defined(_MSC_VER) && (_MSC_VER < 1916) class hasher: public std::_Fnv1a_hasher { public: size_t add_bytes(const byte* first, int len) { return _Add_bytes(first, first + len); } size_t get_value() const { return _Val; } }; #else class hasher { public: hasher() { _val = std::_FNV_offset_basis; } size_t add_bytes(const byte* first, int len) { return std::_Fnv1a_append_bytes(_val, first, len); } size_t get_value() const { return _val; } private: size_t _val; }; #endif /* switch to namespace tr1 and replace the hash for string */ __gslib_end__ namespace std { template<> class hash<gs::string> #if defined(_MSC_VER) && (_MSC_VER < 1914) : public unary_function<gs::string, size_t> #endif { public: size_t operator()(const gs::string& kval) const { return string_hash(kval); } }; }; __gslib_begin__ /* wrappers for all kinds of vessels */ template<class _ty> using list = std::list<_ty>; template<class _ty> using vector = std::vector<_ty>; template<class _ty> using queue = std::queue<_ty>; template<class _ty> using deque = std::deque<_ty>; template<class _ty> using stack = std::stack<_ty>; template<class _kty, class _ty, class _pr = std::less<_kty> > using map = std::map<_kty, _ty, _pr>; template<class _ty, class _pr = std::less<_ty> > using set = std::set<_ty, _pr>; template<class _kty, class _ty, class _pr = std::less<_kty> > using multimap = std::multimap<_kty, _ty, _pr>; template<class _ty, class _pr = std::less<_ty> > using multiset = std::multiset<_ty, _pr>; template<class _kty, class _ty, class _hs = std::hash<_kty>, class _eq = std::equal_to<_kty> > using unordered_map = std::unordered_map<_kty, _ty, _hs, _eq>; template<class _kty, class _hs = std::hash<_kty>, class _equ = std::equal_to<_kty> > using unordered_set = std::unordered_set<_kty, _hs, _equ>; template<class _kty, class _ty, class _hs = std::hash<_kty> > using unordered_multimap = std::unordered_multimap<_kty, _ty, _hs>; template<class _kty, class _hs, class _equ> using unordered_multiset = std::unordered_multiset<_kty, _hs, _equ>; template<class _cls> class com_ptr { public: typedef _cls* ptr_type; typedef com_ptr<_cls> myref; public: com_ptr() { _ptr = nullptr; } ~com_ptr() { if(_ptr) { _ptr->Release(); _ptr = nullptr; } } com_ptr(_cls* p) { _ptr = p; if(_ptr) _ptr->AddRef(); } com_ptr(const myref& p) { _ptr = p.get(); if(_ptr) _ptr->AddRef(); } void attach(_cls* p) { if(_ptr) _ptr->Release(); _ptr = p; } _cls* detach() { _cls* p = _ptr; _ptr = nullptr; return p; } void clear() { if(_ptr) { _ptr->Release(); _ptr = nullptr; } } _cls* operator=(_cls* p) { if(p) p->AddRef(); if(_ptr) _ptr->Release(); return _ptr = p; } _cls* operator=(const myref& p) { if(p._ptr) p._ptr->AddRef(); if(_ptr) _ptr->Release(); return _ptr = p._ptr; } _cls** operator&() { assert(!_ptr); return &_ptr; } _cls* get() const { return _ptr; } _cls* operator->() const { return _ptr; } bool operator!() const { return !_ptr; } bool operator == (_cls* p) const { return _ptr == p; } bool operator != (_cls* p) const { return _ptr != p; } private: _cls* _ptr; }; __gslib_end__ #endif
{ "alphanum_fraction": 0.6189032428, "avg_line_length": 26.6175438596, "ext": "h", "hexsha": "d08cd2747c4c780759d186c246adce11b06c8e9d", "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/std.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/std.h", "max_line_length": 122, "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/std.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": 2089, "size": 7586 }
/* blas/gsl_blas.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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* * Author: G. Jungman */ #ifndef __GSL_BLAS_H__ #define __GSL_BLAS_H__ #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas_types.h> #include <gsl/gsl_types.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 /* ======================================================================== * Level 1 * ======================================================================== */ GSL_EXPORT int gsl_blas_sdsdot (float alpha, const gsl_vector_float * X, const gsl_vector_float * Y, float * result ); GSL_EXPORT int gsl_blas_dsdot (const gsl_vector_float * X, const gsl_vector_float * Y, double * result ); GSL_EXPORT int gsl_blas_sdot (const gsl_vector_float * X, const gsl_vector_float * Y, float * result ); GSL_EXPORT int gsl_blas_ddot (const gsl_vector * X, const gsl_vector * Y, double * result ); GSL_EXPORT int gsl_blas_cdotu (const gsl_vector_complex_float * X, const gsl_vector_complex_float * Y, gsl_complex_float * dotu); GSL_EXPORT int gsl_blas_cdotc (const gsl_vector_complex_float * X, const gsl_vector_complex_float * Y, gsl_complex_float * dotc); GSL_EXPORT int gsl_blas_zdotu (const gsl_vector_complex * X, const gsl_vector_complex * Y, gsl_complex * dotu); GSL_EXPORT int gsl_blas_zdotc (const gsl_vector_complex * X, const gsl_vector_complex * Y, gsl_complex * dotc); GSL_EXPORT float gsl_blas_snrm2 (const gsl_vector_float * X); GSL_EXPORT float gsl_blas_sasum (const gsl_vector_float * X); GSL_EXPORT double gsl_blas_dnrm2 (const gsl_vector * X); GSL_EXPORT double gsl_blas_dasum (const gsl_vector * X); GSL_EXPORT float gsl_blas_scnrm2 (const gsl_vector_complex_float * X); GSL_EXPORT float gsl_blas_scasum (const gsl_vector_complex_float * X); GSL_EXPORT double gsl_blas_dznrm2 (const gsl_vector_complex * X); GSL_EXPORT double gsl_blas_dzasum (const gsl_vector_complex * X); GSL_EXPORT CBLAS_INDEX_t gsl_blas_isamax (const gsl_vector_float * X); GSL_EXPORT CBLAS_INDEX_t gsl_blas_idamax (const gsl_vector * X); GSL_EXPORT CBLAS_INDEX_t gsl_blas_icamax (const gsl_vector_complex_float * X); GSL_EXPORT CBLAS_INDEX_t gsl_blas_izamax (const gsl_vector_complex * X); GSL_EXPORT int gsl_blas_sswap (gsl_vector_float * X, gsl_vector_float * Y); GSL_EXPORT int gsl_blas_scopy (const gsl_vector_float * X, gsl_vector_float * Y); GSL_EXPORT int gsl_blas_saxpy (float alpha, const gsl_vector_float * X, gsl_vector_float * Y); GSL_EXPORT int gsl_blas_dswap (gsl_vector * X, gsl_vector * Y); GSL_EXPORT int gsl_blas_dcopy (const gsl_vector * X, gsl_vector * Y); GSL_EXPORT int gsl_blas_daxpy (double alpha, const gsl_vector * X, gsl_vector * Y); GSL_EXPORT int gsl_blas_cswap (gsl_vector_complex_float * X, gsl_vector_complex_float * Y); GSL_EXPORT int gsl_blas_ccopy (const gsl_vector_complex_float * X, gsl_vector_complex_float * Y); GSL_EXPORT int gsl_blas_caxpy (const gsl_complex_float alpha, const gsl_vector_complex_float * X, gsl_vector_complex_float * Y); GSL_EXPORT int gsl_blas_zswap (gsl_vector_complex * X, gsl_vector_complex * Y); GSL_EXPORT int gsl_blas_zcopy (const gsl_vector_complex * X, gsl_vector_complex * Y); GSL_EXPORT int gsl_blas_zaxpy (const gsl_complex alpha, const gsl_vector_complex * X, gsl_vector_complex * Y); GSL_EXPORT int gsl_blas_srotg (float a[], float b[], float c[], float s[]); GSL_EXPORT int gsl_blas_srotmg (float d1[], float d2[], float b1[], float b2, float P[]); GSL_EXPORT int gsl_blas_srot (gsl_vector_float * X, gsl_vector_float * Y, float c, float s); GSL_EXPORT int gsl_blas_srotm (gsl_vector_float * X, gsl_vector_float * Y, const float P[]); GSL_EXPORT int gsl_blas_drotg (double a[], double b[], double c[], double s[]); GSL_EXPORT int gsl_blas_drotmg (double d1[], double d2[], double b1[], double b2, double P[]); GSL_EXPORT int gsl_blas_drot (gsl_vector * X, gsl_vector * Y, const double c, const double s); GSL_EXPORT int gsl_blas_drotm (gsl_vector * X, gsl_vector * Y, const double P[]); GSL_EXPORT void gsl_blas_sscal (float alpha, gsl_vector_float * X); GSL_EXPORT void gsl_blas_dscal (double alpha, gsl_vector * X); GSL_EXPORT void gsl_blas_cscal (const gsl_complex_float alpha, gsl_vector_complex_float * X); GSL_EXPORT void gsl_blas_zscal (const gsl_complex alpha, gsl_vector_complex * X); GSL_EXPORT void gsl_blas_csscal (float alpha, gsl_vector_complex_float * X); GSL_EXPORT void gsl_blas_zdscal (double alpha, gsl_vector_complex * X); /* =========================================================================== * Level 2 * =========================================================================== */ /* * Routines with standard 4 prefixes (S, D, C, Z) */ GSL_EXPORT int gsl_blas_sgemv (CBLAS_TRANSPOSE_t TransA, float alpha, const gsl_matrix_float * A, const gsl_vector_float * X, float beta, gsl_vector_float * Y); GSL_EXPORT int gsl_blas_strmv (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag, const gsl_matrix_float * A, gsl_vector_float * X); GSL_EXPORT int gsl_blas_strsv (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag, const gsl_matrix_float * A, gsl_vector_float * X); GSL_EXPORT int gsl_blas_dgemv (CBLAS_TRANSPOSE_t TransA, double alpha, const gsl_matrix * A, const gsl_vector * X, double beta, gsl_vector * Y); GSL_EXPORT int gsl_blas_dtrmv (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag, const gsl_matrix * A, gsl_vector * X); GSL_EXPORT int gsl_blas_dtrsv (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag, const gsl_matrix * A, gsl_vector * X); GSL_EXPORT int gsl_blas_cgemv (CBLAS_TRANSPOSE_t TransA, const gsl_complex_float alpha, const gsl_matrix_complex_float * A, const gsl_vector_complex_float * X, const gsl_complex_float beta, gsl_vector_complex_float * Y); GSL_EXPORT int gsl_blas_ctrmv (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag, const gsl_matrix_complex_float * A, gsl_vector_complex_float * X); GSL_EXPORT int gsl_blas_ctrsv (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag, const gsl_matrix_complex_float * A, gsl_vector_complex_float * X); GSL_EXPORT int gsl_blas_zgemv (CBLAS_TRANSPOSE_t TransA, const gsl_complex alpha, const gsl_matrix_complex * A, const gsl_vector_complex * X, const gsl_complex beta, gsl_vector_complex * Y); GSL_EXPORT int gsl_blas_ztrmv (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag, const gsl_matrix_complex * A, gsl_vector_complex * X); GSL_EXPORT int gsl_blas_ztrsv (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag, const gsl_matrix_complex * A, gsl_vector_complex *X); /* * Routines with S and D prefixes only */ GSL_EXPORT int gsl_blas_ssymv (CBLAS_UPLO_t Uplo, float alpha, const gsl_matrix_float * A, const gsl_vector_float * X, float beta, gsl_vector_float * Y); GSL_EXPORT int gsl_blas_sger (float alpha, const gsl_vector_float * X, const gsl_vector_float * Y, gsl_matrix_float * A); GSL_EXPORT int gsl_blas_ssyr (CBLAS_UPLO_t Uplo, float alpha, const gsl_vector_float * X, gsl_matrix_float * A); GSL_EXPORT int gsl_blas_ssyr2 (CBLAS_UPLO_t Uplo, float alpha, const gsl_vector_float * X, const gsl_vector_float * Y, gsl_matrix_float * A); GSL_EXPORT int gsl_blas_dsymv (CBLAS_UPLO_t Uplo, double alpha, const gsl_matrix * A, const gsl_vector * X, double beta, gsl_vector * Y); GSL_EXPORT int gsl_blas_dger (double alpha, const gsl_vector * X, const gsl_vector * Y, gsl_matrix * A); GSL_EXPORT int gsl_blas_dsyr (CBLAS_UPLO_t Uplo, double alpha, const gsl_vector * X, gsl_matrix * A); GSL_EXPORT int gsl_blas_dsyr2 (CBLAS_UPLO_t Uplo, double alpha, const gsl_vector * X, const gsl_vector * Y, gsl_matrix * A); /* * Routines with C and Z prefixes only */ GSL_EXPORT int gsl_blas_chemv (CBLAS_UPLO_t Uplo, const gsl_complex_float alpha, const gsl_matrix_complex_float * A, const gsl_vector_complex_float * X, const gsl_complex_float beta, gsl_vector_complex_float * Y); GSL_EXPORT int gsl_blas_cgeru (const gsl_complex_float alpha, const gsl_vector_complex_float * X, const gsl_vector_complex_float * Y, gsl_matrix_complex_float * A); GSL_EXPORT int gsl_blas_cgerc (const gsl_complex_float alpha, const gsl_vector_complex_float * X, const gsl_vector_complex_float * Y, gsl_matrix_complex_float * A); GSL_EXPORT int gsl_blas_cher (CBLAS_UPLO_t Uplo, float alpha, const gsl_vector_complex_float * X, gsl_matrix_complex_float * A); GSL_EXPORT int gsl_blas_cher2 (CBLAS_UPLO_t Uplo, const gsl_complex_float alpha, const gsl_vector_complex_float * X, const gsl_vector_complex_float * Y, gsl_matrix_complex_float * A); GSL_EXPORT int gsl_blas_zhemv (CBLAS_UPLO_t Uplo, const gsl_complex alpha, const gsl_matrix_complex * A, const gsl_vector_complex * X, const gsl_complex beta, gsl_vector_complex * Y); GSL_EXPORT int gsl_blas_zgeru (const gsl_complex alpha, const gsl_vector_complex * X, const gsl_vector_complex * Y, gsl_matrix_complex * A); GSL_EXPORT int gsl_blas_zgerc (const gsl_complex alpha, const gsl_vector_complex * X, const gsl_vector_complex * Y, gsl_matrix_complex * A); GSL_EXPORT int gsl_blas_zher (CBLAS_UPLO_t Uplo, double alpha, const gsl_vector_complex * X, gsl_matrix_complex * A); GSL_EXPORT int gsl_blas_zher2 (CBLAS_UPLO_t Uplo, const gsl_complex alpha, const gsl_vector_complex * X, const gsl_vector_complex * Y, gsl_matrix_complex * A); /* * =========================================================================== * Prototypes for level 3 BLAS * =========================================================================== */ /* * Routines with standard 4 prefixes (S, D, C, Z) */ GSL_EXPORT int gsl_blas_sgemm (CBLAS_TRANSPOSE_t TransA, CBLAS_TRANSPOSE_t TransB, float alpha, const gsl_matrix_float * A, const gsl_matrix_float * B, float beta, gsl_matrix_float * C); GSL_EXPORT int gsl_blas_ssymm (CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo, float alpha, const gsl_matrix_float * A, const gsl_matrix_float * B, float beta, gsl_matrix_float * C); GSL_EXPORT int gsl_blas_ssyrk (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t Trans, float alpha, const gsl_matrix_float * A, float beta, gsl_matrix_float * C); GSL_EXPORT int gsl_blas_ssyr2k (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t Trans, float alpha, const gsl_matrix_float * A, const gsl_matrix_float * B, float beta, gsl_matrix_float * C); GSL_EXPORT int gsl_blas_strmm (CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag, float alpha, const gsl_matrix_float * A, gsl_matrix_float * B); GSL_EXPORT int gsl_blas_strsm (CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag, float alpha, const gsl_matrix_float * A, gsl_matrix_float * B); GSL_EXPORT int gsl_blas_dgemm (CBLAS_TRANSPOSE_t TransA, CBLAS_TRANSPOSE_t TransB, double alpha, const gsl_matrix * A, const gsl_matrix * B, double beta, gsl_matrix * C); GSL_EXPORT int gsl_blas_dsymm (CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo, double alpha, const gsl_matrix * A, const gsl_matrix * B, double beta, gsl_matrix * C); GSL_EXPORT int gsl_blas_dsyrk (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t Trans, double alpha, const gsl_matrix * A, double beta, gsl_matrix * C); GSL_EXPORT int gsl_blas_dsyr2k (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t Trans, double alpha, const gsl_matrix * A, const gsl_matrix * B, double beta, gsl_matrix * C); GSL_EXPORT int gsl_blas_dtrmm (CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag, double alpha, const gsl_matrix * A, gsl_matrix * B); GSL_EXPORT int gsl_blas_dtrsm (CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag, double alpha, const gsl_matrix * A, gsl_matrix * B); GSL_EXPORT int gsl_blas_cgemm (CBLAS_TRANSPOSE_t TransA, CBLAS_TRANSPOSE_t TransB, const gsl_complex_float alpha, const gsl_matrix_complex_float * A, const gsl_matrix_complex_float * B, const gsl_complex_float beta, gsl_matrix_complex_float * C); GSL_EXPORT int gsl_blas_csymm (CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo, const gsl_complex_float alpha, const gsl_matrix_complex_float * A, const gsl_matrix_complex_float * B, const gsl_complex_float beta, gsl_matrix_complex_float * C); GSL_EXPORT int gsl_blas_csyrk (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t Trans, const gsl_complex_float alpha, const gsl_matrix_complex_float * A, const gsl_complex_float beta, gsl_matrix_complex_float * C); GSL_EXPORT int gsl_blas_csyr2k (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t Trans, const gsl_complex_float alpha, const gsl_matrix_complex_float * A, const gsl_matrix_complex_float * B, const gsl_complex_float beta, gsl_matrix_complex_float * C); GSL_EXPORT int gsl_blas_ctrmm (CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag, const gsl_complex_float alpha, const gsl_matrix_complex_float * A, gsl_matrix_complex_float * B); GSL_EXPORT int gsl_blas_ctrsm (CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag, const gsl_complex_float alpha, const gsl_matrix_complex_float * A, gsl_matrix_complex_float * B); GSL_EXPORT int gsl_blas_zgemm (CBLAS_TRANSPOSE_t TransA, CBLAS_TRANSPOSE_t TransB, const gsl_complex alpha, const gsl_matrix_complex * A, const gsl_matrix_complex * B, const gsl_complex beta, gsl_matrix_complex * C); GSL_EXPORT int gsl_blas_zsymm (CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo, const gsl_complex alpha, const gsl_matrix_complex * A, const gsl_matrix_complex * B, const gsl_complex beta, gsl_matrix_complex * C); GSL_EXPORT int gsl_blas_zsyrk (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t Trans, const gsl_complex alpha, const gsl_matrix_complex * A, const gsl_complex beta, gsl_matrix_complex * C); GSL_EXPORT int gsl_blas_zsyr2k (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t Trans, const gsl_complex alpha, const gsl_matrix_complex * A, const gsl_matrix_complex * B, const gsl_complex beta, gsl_matrix_complex *C); GSL_EXPORT int gsl_blas_ztrmm (CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag, const gsl_complex alpha, const gsl_matrix_complex * A, gsl_matrix_complex * B); GSL_EXPORT int gsl_blas_ztrsm (CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag, const gsl_complex alpha, const gsl_matrix_complex * A, gsl_matrix_complex * B); /* * Routines with prefixes C and Z only */ GSL_EXPORT int gsl_blas_chemm (CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo, const gsl_complex_float alpha, const gsl_matrix_complex_float * A, const gsl_matrix_complex_float * B, const gsl_complex_float beta, gsl_matrix_complex_float * C); GSL_EXPORT int gsl_blas_cherk (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t Trans, float alpha, const gsl_matrix_complex_float * A, float beta, gsl_matrix_complex_float * C); GSL_EXPORT int gsl_blas_cher2k (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t Trans, const gsl_complex_float alpha, const gsl_matrix_complex_float * A, const gsl_matrix_complex_float * B, float beta, gsl_matrix_complex_float * C); GSL_EXPORT int gsl_blas_zhemm (CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo, const gsl_complex alpha, const gsl_matrix_complex * A, const gsl_matrix_complex * B, const gsl_complex beta, gsl_matrix_complex * C); GSL_EXPORT int gsl_blas_zherk (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t Trans, double alpha, const gsl_matrix_complex * A, double beta, gsl_matrix_complex * C); GSL_EXPORT int gsl_blas_zher2k (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t Trans, const gsl_complex alpha, const gsl_matrix_complex * A, const gsl_matrix_complex * B, double beta, gsl_matrix_complex * C); __END_DECLS #endif /* __GSL_BLAS_H__ */
{ "alphanum_fraction": 0.4772061585, "avg_line_length": 44.0894039735, "ext": "h", "hexsha": "3c83815ffa1584a5958435e1074817b6307000c6", "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": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "dynaryu/vaws", "max_forks_repo_path": "src/core/gsl/include/gsl/gsl_blas.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "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": "dynaryu/vaws", "max_issues_repo_path": "src/core/gsl/include/gsl/gsl_blas.h", "max_line_length": 94, "max_stars_count": null, "max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "dynaryu/vaws", "max_stars_repo_path": "src/core/gsl/include/gsl/gsl_blas.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 5012, "size": 26630 }
//This does CELL (~soma) stage of GRU (gated recurrent unit) model. //This requires each neuron to have 3 input time series, X, Xr, Xz, //where X is the usual input and Xr, Xz the inputs for the reset and update gates, //stacked into X = [X; Xr; Xz] for dim=0, or X = [X Xr Xz] for dim=1. //For dim=0, R[:,t] = sig{Xr[:,t] + Ur*Y[:,t-1]} \n"; // Z[:,t] = sig{Xz[:,t] + Uz*Y[:,t-1]} \n"; // H[:,t] = R[:,t].*Y[:,t-1] \n"; // Y[:,t] = Z[:,t].*Y[:,t-1] + (1-Z[:,t]).*tanh{X[:,t] + U*H[:,t]} \n"; //with sizes X, Xr, Xz: N x T \n"; // U, Ur, Uz: N x N \n"; // Y : N x T \n"; // //For dim=1, R[t,:] = sig{Xr[t,:] + Y[t-1,:]*Ur} \n"; // Z[t,:] = sig{Xz[t,:] + Y[t-1,:]*Uz} \n"; // H[t,:] = R[t,:].*Y[t-1,:] \n"; // Y[t,:] = Z[t,:].*Y[t-1,:] + (1-Z[t,:]).*tanh{X[t,:] + H[t,:]*U} \n"; //with sizes X, Xr, Xz: T x N \n"; // U, Ur, Uz: N x N \n"; // Y : T x N \n"; // //where sig is the logistic (sigmoid) nonlinearity = 1/(1+exp(-x)), //R is the reset gate, Z is the update gate, H is an intermediate (hidden) vector, //U, Ur, Uz are NxN matrices, and Y is the output. //Note that, the neurons of a layer are independent only if U, Ur, Uz are diagonal matrices. //This is only really a CELL (~soma) stage in that case. #include <stdio.h> #include <stdlib.h> #include <math.h> #include <cblas.h> #ifdef __cplusplus namespace codee { extern "C" { #endif int gru_s (float *Y, const float *X, const float *U, const float *Ur, const float *Uz, const size_t N, const size_t T, const char iscolmajor, const size_t dim); int gru_d (double *Y, const double *X, const double *U, const double *Ur, const double *Uz, const size_t N, const size_t T, const char iscolmajor, const size_t dim); int gru_inplace_s (float *X, const float *U, const float *Ur, const float *Uz, const size_t N, const size_t T, const char iscolmajor, const size_t dim); int gru_inplace_d (double *X, const double *U, const double *Ur, const double *Uz, const size_t N, const size_t T, const char iscolmajor, const size_t dim); int gru_s (float *Y, const float *X, const float *U, const float *Ur, const float *Uz, const size_t N, const size_t T, const char iscolmajor, const size_t dim) { const float o = 1.0f; const size_t N2 = 2*N, NT = N*T, NT2 = 2*N*T; size_t nT, tN, tN3; float *R, *Z, *H; if (!(R=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in gru_s: problem with malloc. "); perror("malloc"); return 1; } if (!(Z=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in gru_s: problem with malloc. "); perror("malloc"); return 1; } if (!(H=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in gru_s: problem with malloc. "); perror("malloc"); return 1; } if (dim==0u) { if (iscolmajor) { for (size_t n=0u; n<N; ++n) { //R[n] = 1.0f / (1.0f+expf(-X[N+n])); Z[n] = 1.0f / (1.0f+expf(-X[N2+n])); Y[n] = (1.0f-Z[n]) * tanhf(X[n]); } for (size_t t=1; t<T; ++t) { tN = t*N; tN3 = 3*tN; cblas_scopy((int)N,&X[tN3+N],1,R,1); cblas_scopy((int)N,&X[tN3+N2],1,Z,1); cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Ur,(int)N,&Y[tN-N],1,o,R,1); cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uz,(int)N,&Y[tN-N],1,o,Z,1); for (size_t n=0u; n<N; ++n) { //R[n] = 1.0f / (1.0f+expf(-R[n])); Z[n] = 1.0f / (1.0f+expf(-Z[n])); //H[n] = R[n] * Y[tN-N+n]; H[n] = Y[tN-N+n] / (1.0f+expf(-R[n])); } cblas_scopy((int)N,&X[tN3],1,&Y[tN],1); cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&Y[tN],1); for (size_t n=0u; n<N; ++n) { Y[tN+n] = Z[n]*Y[tN-N+n] + (1.0f-Z[n])*tanhf(Y[tN+n]); } } } else { for (size_t n=0u; n<N; ++n) { nT = n*T; Z[n] = 1.0f / (1.0f+expf(-X[NT2+nT])); Y[nT] = (1.0f-Z[n]) * tanhf(X[nT]); } for (size_t t=1; t<T; ++t) { cblas_scopy((int)N,&X[NT+t],(int)T,R,1); cblas_scopy((int)N,&X[NT2+t],(int)T,Z,1); cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Ur,(int)N,&Y[t-1],(int)T,o,R,1); cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Uz,(int)N,&Y[t-1],(int)T,o,Z,1); for (size_t n=0u; n<N; ++n) { Z[n] = 1.0f / (1.0f+expf(-Z[n])); H[n] = Y[t-1+n*T] / (1.0f+expf(-R[n])); } cblas_scopy((int)N,&X[t],(int)T,&Y[t],(int)T); cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&Y[t],(int)T); for (size_t n=0u; n<N; ++n) { nT = n*T; Y[t+nT] = Z[n]*Y[t-1+nT] + (1.0f-Z[n])*tanhf(Y[t+nT]); } } } } else if (dim==1u) { if (iscolmajor) { for (size_t n=0u; n<N; ++n) { nT = n*T; Z[n] = 1.0f / (1.0f+expf(-X[NT2+nT])); Y[nT] = (1.0f-Z[n]) * tanhf(X[nT]); } for (size_t t=1; t<T; ++t) { cblas_scopy((int)N,&X[NT+t],(int)T,R,1); cblas_scopy((int)N,&X[NT2+t],(int)T,Z,1); cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Ur,(int)N,&Y[t-1],(int)T,o,R,1); cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Uz,(int)N,&Y[t-1],(int)T,o,Z,1); for (size_t n=0u; n<N; ++n) { Z[n] = 1.0f / (1.0f+expf(-Z[n])); H[n] = Y[t-1+n*T] / (1.0f+expf(-R[n])); } cblas_scopy((int)N,&X[t],(int)T,&Y[t],(int)T); cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&Y[t],(int)T); for (size_t n=0u; n<N; ++n) { nT = n*T; Y[t+nT] = Z[n]*Y[t-1+nT] + (1.0f-Z[n])*tanhf(Y[t+nT]); } } } else { for (size_t n=0u; n<N; ++n) { Z[n] = 1.0f / (1.0f+expf(-X[N2+n])); Y[n] = (1.0f-Z[n]) * tanhf(X[n]); } for (size_t t=1; t<T; ++t) { tN = t*N; tN3 = 3*tN; cblas_scopy((int)N,&X[tN3+N],1,R,1); cblas_scopy((int)N,&X[tN3+N2],1,Z,1); cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Ur,(int)N,&Y[tN-N],1,o,R,1); cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uz,(int)N,&Y[tN-N],1,o,Z,1); for (size_t n=0u; n<N; ++n) { Z[n] = 1.0f / (1.0f+expf(-Z[n])); H[n] = Y[tN-N+n] / (1.0f+expf(-R[n])); } cblas_scopy((int)N,&X[tN3],1,&Y[tN],1); cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&Y[tN],1); for (size_t n=0u; n<N; ++n) { Y[tN+n] = Z[n]*Y[tN-N+n] + (1.0f-Z[n])*tanhf(Y[tN+n]); } } } } else { fprintf(stderr,"error in gru_s: dim must be 0 or 1.\n"); return 1; } return 0; } int gru_d (double *Y, const double *X, const double *U, const double *Ur, const double *Uz, const size_t N, const size_t T, const char iscolmajor, const size_t dim) { const double o = 1.0; const size_t N2 = 2*N, NT = N*T, NT2 = 2*N*T; size_t nT, tN, tN3; double *R, *Z, *H; if (!(R=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in gru_d: problem with malloc. "); perror("malloc"); return 1; } if (!(Z=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in gru_d: problem with malloc. "); perror("malloc"); return 1; } if (!(H=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in gru_d: problem with malloc. "); perror("malloc"); return 1; } if (dim==0u) { if (iscolmajor) { for (size_t n=0u; n<N; ++n) { Z[n] = 1.0 / (1.0+exp(-X[N2+n])); Y[n] = (1.0-Z[n]) * tanh(X[n]); } for (size_t t=1; t<T; ++t) { tN = t*N; tN3 = 3*tN; cblas_dcopy((int)N,&X[tN3+N],1,R,1); cblas_dcopy((int)N,&X[tN3+N2],1,Z,1); cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Ur,(int)N,&Y[tN-N],1,o,R,1); cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uz,(int)N,&Y[tN-N],1,o,Z,1); for (size_t n=0u; n<N; ++n) { Z[n] = 1.0 / (1.0+exp(-Z[n])); H[n] = Y[tN-N+n] / (1.0+exp(-R[n])); } cblas_dcopy((int)N,&X[tN3],1,&Y[tN],1); cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&Y[tN],1); for (size_t n=0u; n<N; ++n) { Y[tN+n] = Z[n]*Y[tN-N+n] + (1.0-Z[n])*tanh(Y[tN+n]); } } } else { for (size_t n=0u; n<N; ++n) { nT = n*T; Z[n] = 1.0 / (1.0+exp(-X[NT2+nT])); Y[nT] = (1.0-Z[n]) * tanh(X[nT]); } for (size_t t=1; t<T; ++t) { cblas_dcopy((int)N,&X[NT+t],(int)T,R,1); cblas_dcopy((int)N,&X[NT2+t],(int)T,Z,1); cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Ur,(int)N,&Y[t-1],(int)T,o,R,1); cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Uz,(int)N,&Y[t-1],(int)T,o,Z,1); for (size_t n=0u; n<N; ++n) { Z[n] = 1.0 / (1.0+exp(-Z[n])); H[n] = Y[t-1+n*T] / (1.0+exp(-R[n])); } cblas_dcopy((int)N,&X[t],(int)T,&Y[t],(int)T); cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&Y[t],(int)T); for (size_t n=0u; n<N; ++n) { nT = n*T; Y[t+nT] = Z[n]*Y[t-1+nT] + (1.0-Z[n])*tanh(Y[t+nT]); } } } } else if (dim==1u) { if (iscolmajor) { for (size_t n=0u; n<N; ++n) { nT = n*T; Z[n] = 1.0 / (1.0+exp(-X[NT2+nT])); Y[nT] = (1.0-Z[n]) * tanh(X[nT]); } for (size_t t=1; t<T; ++t) { cblas_dcopy((int)N,&X[NT+t],(int)T,R,1); cblas_dcopy((int)N,&X[NT2+t],(int)T,Z,1); cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Ur,(int)N,&Y[t-1],(int)T,o,R,1); cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Uz,(int)N,&Y[t-1],(int)T,o,Z,1); for (size_t n=0u; n<N; ++n) { Z[n] = 1.0 / (1.0+exp(-Z[n])); H[n] = Y[t-1+n*T] / (1.0+exp(-R[n])); } cblas_dcopy((int)N,&X[t],(int)T,&Y[t],(int)T); cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&Y[t],(int)T); for (size_t n=0u; n<N; ++n) { nT = n*T; Y[t+nT] = Z[n]*Y[t-1+nT] + (1.0-Z[n])*tanh(Y[t+nT]); } } } else { for (size_t n=0u; n<N; ++n) { Z[n] = 1.0 / (1.0+exp(-X[N2+n])); Y[n] = (1.0-Z[n]) * tanh(X[n]); } for (size_t t=1; t<T; ++t) { tN = t*N; tN3 = 3*tN; cblas_dcopy((int)N,&X[tN3+N],1,R,1); cblas_dcopy((int)N,&X[tN3+N2],1,Z,1); cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Ur,(int)N,&Y[tN-N],1,o,R,1); cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uz,(int)N,&Y[tN-N],1,o,Z,1); for (size_t n=0u; n<N; ++n) { Z[n] = 1.0 / (1.0+exp(-Z[n])); H[n] = Y[tN-N+n] / (1.0+exp(-R[n])); } cblas_dcopy((int)N,&X[tN3],1,&Y[tN],1); cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&Y[tN],1); for (size_t n=0u; n<N; ++n) { Y[tN+n] = Z[n]*Y[tN-N+n] + (1.0-Z[n])*tanh(Y[tN+n]); } } } } else { fprintf(stderr,"error in gru_d: dim must be 0 or 1.\n"); return 1; } return 0; } int gru_inplace_s (float *X, const float *U, const float *Ur, const float *Uz, const size_t N, const size_t T, const char iscolmajor, const size_t dim) { const float o = 1.0f; const size_t N2 = 2*N, N3 = 3*N, NT = N*T, NT2 = 2*N*T; size_t nT, tN, tN3; float *R, *Z, *H; if (!(R=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in gru_inplace_s: problem with malloc. "); perror("malloc"); return 1; } if (!(Z=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in gru_inplace_s: problem with malloc. "); perror("malloc"); return 1; } if (!(H=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in gru_inplace_s: problem with malloc. "); perror("malloc"); return 1; } //clock_gettime(CLOCK_REALTIME,&tic); if (dim==0u) { if (iscolmajor) { for (size_t n=0u; n<N; ++n) { Z[n] = 1.0f / (1.0f+expf(-X[N2+n])); X[n] = (1.0f-Z[n]) * tanhf(X[n]); } for (size_t t=1; t<T; ++t) { tN = t*N; tN3 = 3*tN; cblas_scopy((int)N,&X[tN3+N],1,R,1); cblas_scopy((int)N,&X[tN3+N2],1,Z,1); cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Ur,(int)N,&X[tN3-N3],1,o,R,1); cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uz,(int)N,&X[tN3-N3],1,o,Z,1); for (size_t n=0u; n<N; ++n) { Z[n] = 1.0f / (1.0f+expf(-Z[n])); H[n] = X[tN3-N3+n] / (1.0f+expf(-R[n])); } cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&X[tN3],1); for (size_t n=0u; n<N; ++n) { X[tN3+n] = Z[n]*X[tN-N3+n] + (1.0f-Z[n])*tanhf(X[tN3+n]); } } } else { for (size_t n=0u; n<N; ++n) { nT = n*T; Z[n] = 1.0f / (1.0f+expf(-X[NT2+nT])); X[nT] = (1.0f-Z[n]) * tanhf(X[nT]); } for (size_t t=1; t<T; ++t) { cblas_scopy((int)N,&X[NT+t],(int)T,R,1); cblas_scopy((int)N,&X[NT2+t],(int)T,Z,1); cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Ur,(int)N,&X[t-1],(int)T,o,R,1); cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Uz,(int)N,&X[t-1],(int)T,o,Z,1); for (size_t n=0u; n<N; ++n) { Z[n] = 1.0f / (1.0f+expf(-Z[n])); H[n] = X[t-1+n*T] / (1.0f+expf(-R[n])); } cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&X[t],(int)T); for (size_t n=0u; n<N; ++n) { nT = n*T; X[t+nT] = Z[n]*X[t-1+nT] + (1.0f-Z[n])*tanhf(X[t+nT]); } } } } else if (dim==1u) { if (iscolmajor) { for (size_t n=0u; n<N; ++n) { nT = n*T; Z[n] = 1.0f / (1.0f+expf(-X[NT2+nT])); X[nT] = (1.0f-Z[n]) * tanhf(X[nT]); } for (size_t t=1; t<T; ++t) { cblas_scopy((int)N,&X[NT+t],(int)T,R,1); cblas_scopy((int)N,&X[NT2+t],(int)T,Z,1); cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Ur,(int)N,&X[t-1],(int)T,o,R,1); cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Uz,(int)N,&X[t-1],(int)T,o,Z,1); for (size_t n=0u; n<N; ++n) { Z[n] = 1.0f / (1.0f+expf(-Z[n])); H[n] = X[t-1+n*T] / (1.0f+expf(-R[n])); } cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&X[t],(int)T); for (size_t n=0u; n<N; ++n) { nT = n*T; X[t+nT] = Z[n]*X[t-1+nT] + (1.0f-Z[n])*tanhf(X[t+nT]); } } } else { for (size_t n=0u; n<N; ++n) { Z[n] = 1.0f / (1.0f+expf(-X[N2+n])); X[n] = (1.0f-Z[n]) * tanhf(X[n]); } for (size_t t=1; t<T; ++t) { tN = t*N; tN3 = 3*tN; cblas_scopy((int)N,&X[tN3+N],1,R,1); cblas_scopy((int)N,&X[tN3+N2],1,Z,1); cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Ur,(int)N,&X[tN3-N3],1,o,R,1); cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uz,(int)N,&X[tN3-N3],1,o,Z,1); for (size_t n=0u; n<N; ++n) { Z[n] = 1.0f / (1.0f+expf(-Z[n])); H[n] = X[tN3-N3+n] / (1.0f+expf(-R[n])); } cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&X[tN3],1); for (size_t n=0u; n<N; ++n) { X[tN3+n] = Z[n]*X[tN-N3+n] + (1.0f-Z[n])*tanhf(X[tN3+n]); } } } } else { fprintf(stderr,"error in gru_inplace_s: dim must be 0 or 1.\n"); return 1; } return 0; } int gru_inplace_d (double *X, const double *U, const double *Ur, const double *Uz, const size_t N, const size_t T, const char iscolmajor, const size_t dim) { const double o = 1.0; const size_t N2 = 2*N, N3 = 3*N, NT = N*T, NT2 = 2*N*T; size_t nT, tN, tN3; double *R, *Z, *H; if (!(R=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in gru_inplace_d: problem with malloc. "); perror("malloc"); return 1; } if (!(Z=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in gru_inplace_d: problem with malloc. "); perror("malloc"); return 1; } if (!(H=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in gru_inplace_d: problem with malloc. "); perror("malloc"); return 1; } if (dim==0u) { if (iscolmajor) { for (size_t n=0u; n<N; ++n) { Z[n] = 1.0 / (1.0+exp(-X[N2+n])); X[n] = (1.0-Z[n]) * tanh(X[n]); } for (size_t t=1; t<T; ++t) { tN = t*N; tN3 = 3*tN; cblas_dcopy((int)N,&X[tN3+N],1,R,1); cblas_dcopy((int)N,&X[tN3+N2],1,Z,1); cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Ur,(int)N,&X[tN3-N3],1,o,R,1); cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uz,(int)N,&X[tN3-N3],1,o,Z,1); for (size_t n=0u; n<N; ++n) { Z[n] = 1.0 / (1.0+exp(-Z[n])); H[n] = X[tN3-N3+n] / (1.0+exp(-R[n])); } cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&X[tN3],1); for (size_t n=0u; n<N; ++n) { X[tN3+n] = Z[n]*X[tN-N3+n] + (1.0-Z[n])*tanh(X[tN3+n]); } } } else { for (size_t n=0u; n<N; ++n) { nT = n*T; Z[n] = 1.0 / (1.0+exp(-X[NT2+nT])); X[nT] = (1.0-Z[n]) * tanh(X[nT]); } for (size_t t=1; t<T; ++t) { cblas_dcopy((int)N,&X[NT+t],(int)T,R,1); cblas_dcopy((int)N,&X[NT2+t],(int)T,Z,1); cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Ur,(int)N,&X[t-1],(int)T,o,R,1); cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Uz,(int)N,&X[t-1],(int)T,o,Z,1); for (size_t n=0u; n<N; ++n) { Z[n] = 1.0 / (1.0+exp(-Z[n])); H[n] = X[t-1+n*T] / (1.0+exp(-R[n])); } cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&X[t],(int)T); for (size_t n=0u; n<N; ++n) { nT = n*T; X[t+nT] = Z[n]*X[t-1+nT] + (1.0-Z[n])*tanh(X[t+nT]); } } } } else if (dim==1u) { if (iscolmajor) { for (size_t n=0u; n<N; ++n) { nT = n*T; Z[n] = 1.0 / (1.0+exp(-X[NT2+nT])); X[nT] = (1.0-Z[n]) * tanh(X[nT]); } for (size_t t=1; t<T; ++t) { cblas_dcopy((int)N,&X[NT+t],(int)T,R,1); cblas_dcopy((int)N,&X[NT2+t],(int)T,Z,1); cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Ur,(int)N,&X[t-1],(int)T,o,R,1); cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Uz,(int)N,&X[t-1],(int)T,o,Z,1); for (size_t n=0u; n<N; ++n) { Z[n] = 1.0 / (1.0+exp(-Z[n])); H[n] = X[t-1+n*T] / (1.0+exp(-R[n])); } cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&X[t],(int)T); for (size_t n=0u; n<N; ++n) { nT = n*T; X[t+nT] = Z[n]*X[t-1+nT] + (1.0-Z[n])*tanh(X[t+nT]); } } } else { for (size_t n=0u; n<N; ++n) { Z[n] = 1.0 / (1.0+exp(-X[N2+n])); X[n] = (1.0-Z[n]) * tanh(X[n]); } for (size_t t=1; t<T; ++t) { tN = t*N; tN3 = 3*tN; cblas_dcopy((int)N,&X[tN3+N],1,R,1); cblas_dcopy((int)N,&X[tN3+N2],1,Z,1); cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Ur,(int)N,&X[tN3-N3],1,o,R,1); cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uz,(int)N,&X[tN3-N3],1,o,Z,1); for (size_t n=0u; n<N; ++n) { Z[n] = 1.0 / (1.0+exp(-Z[n])); H[n] = X[tN3-N3+n] / (1.0+exp(-R[n])); } cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&X[tN3],1); for (size_t n=0u; n<N; ++n) { X[tN3+n] = Z[n]*X[tN-N3+n] + (1.0-Z[n])*tanh(X[tN3+n]); } } } } else { fprintf(stderr,"error in gru_inplace_d: dim must be 0 or 1.\n"); return 1; } return 0; } #ifdef __cplusplus } } #endif
{ "alphanum_fraction": 0.4170506912, "avg_line_length": 40.7582608696, "ext": "c", "hexsha": "ba77a21032e4fee42d3358c707c133aa42a96f14", "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": "c4b8317a38a72a16fd0bf905791b6c19e49c0aa7", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "erikedwards4/nn", "max_forks_repo_path": "c/gru.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "c4b8317a38a72a16fd0bf905791b6c19e49c0aa7", "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/nn", "max_issues_repo_path": "c/gru.c", "max_line_length": 165, "max_stars_count": 1, "max_stars_repo_head_hexsha": "c4b8317a38a72a16fd0bf905791b6c19e49c0aa7", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "erikedwards4/nn", "max_stars_repo_path": "c/gru.c", "max_stars_repo_stars_event_max_datetime": "2020-08-26T09:28:40.000Z", "max_stars_repo_stars_event_min_datetime": "2020-08-26T09:28:40.000Z", "num_tokens": 8496, "size": 23436 }
/* randist/geometric.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 James Theiler, 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 <math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> /* Geometric distribution (bernoulli trial with probability p) prob(k) = p (1 - p)^(k-1) for n = 1, 2, 3, ... It gives the distribution of "waiting times" for an event that occurs with probability p. */ unsigned int gsl_ran_geometric (const gsl_rng * r, const double p) { double u = gsl_rng_uniform_pos (r); unsigned int k; if (p == 1) { k = 1; } else { k = log (u) / log (1 - p) + 1; } return k; } double gsl_ran_geometric_pdf (const unsigned int k, const double p) { if (k == 0) { return 0 ; } else if (k == 1) { return p ; } else { double P = p * pow (1 - p, k - 1.0); return P; } }
{ "alphanum_fraction": 0.6471674877, "avg_line_length": 23.8823529412, "ext": "c", "hexsha": "afce6b27b252de26c394dc7aa17adcadb2cc653c", "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/randist/geometric.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/randist/geometric.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/randist/geometric.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": 477, "size": 1624 }
#pragma once #include <gsl/gsl_vector.h> double vs_gsl_Gradient_ForwardDiff ( const gsl_vector * x, /**< [in] Point at which the gradient is to be evaluated */ void * data, /**< [in] Optional parameters passed directly to the function func_f */ double (*func_f)(const gsl_vector * x, void *data), /**< [in] User-supplied routine that returns the value of the function at x */ gsl_vector * J, /**< [out] Gradient vector (same length as x) */ double dh /**< [in] Increment in variable for numerical differentiation */ );
{ "alphanum_fraction": 0.6468531469, "avg_line_length": 47.6666666667, "ext": "h", "hexsha": "2903cae8fd976bd39e19cec3bc5bca2a0904b723", "lang": "C", "max_forks_count": 5, "max_forks_repo_forks_event_max_datetime": "2022-01-14T11:29:56.000Z", "max_forks_repo_forks_event_min_datetime": "2021-04-19T06:44:10.000Z", "max_forks_repo_head_hexsha": "ab5140a34ac6dc189f1c13f94a2a081d670da2bc", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "friedhelm-h/dvs_global_flow_skeleton", "max_forks_repo_path": "include/dvs_global_flow/numerical_deriv.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "ab5140a34ac6dc189f1c13f94a2a081d670da2bc", "max_issues_repo_issues_event_max_datetime": "2022-01-07T16:04:48.000Z", "max_issues_repo_issues_event_min_datetime": "2021-02-26T13:07:47.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "friedhelm-h/dvs_global_flow_skeleton", "max_issues_repo_path": "include/dvs_global_flow/numerical_deriv.h", "max_line_length": 134, "max_stars_count": 18, "max_stars_repo_head_hexsha": "ab5140a34ac6dc189f1c13f94a2a081d670da2bc", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "friedhelm-h/dvs_global_flow_skeleton", "max_stars_repo_path": "include/dvs_global_flow/numerical_deriv.h", "max_stars_repo_stars_event_max_datetime": "2022-03-19T15:59:06.000Z", "max_stars_repo_stars_event_min_datetime": "2020-12-27T02:06:30.000Z", "num_tokens": 134, "size": 572 }
#include <lapacke.h>
{ "alphanum_fraction": 0.75, "avg_line_length": 20, "ext": "h", "hexsha": "aad224189374ebe2dd7810a13075555f395ee7dc", "lang": "C", "max_forks_count": 13, "max_forks_repo_forks_event_max_datetime": "2022-03-29T07:25:21.000Z", "max_forks_repo_forks_event_min_datetime": "2019-08-03T05:29:38.000Z", "max_forks_repo_head_hexsha": "49c5f1ec9958a73afde90842c57995d8de9f57b7", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Max0u/NDArray", "max_forks_repo_path": "Sources/C/CLapack/lapacke.h", "max_issues_count": 14, "max_issues_repo_head_hexsha": "49c5f1ec9958a73afde90842c57995d8de9f57b7", "max_issues_repo_issues_event_max_datetime": "2020-04-22T03:44:41.000Z", "max_issues_repo_issues_event_min_datetime": "2019-08-02T06:07:39.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "Max0u/NDArray", "max_issues_repo_path": "Sources/C/CLapack/lapacke.h", "max_line_length": 20, "max_stars_count": 66, "max_stars_repo_head_hexsha": "49c5f1ec9958a73afde90842c57995d8de9f57b7", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Max0u/NDArray", "max_stars_repo_path": "Sources/C/CLapack/lapacke.h", "max_stars_repo_stars_event_max_datetime": "2021-12-22T04:55:11.000Z", "max_stars_repo_stars_event_min_datetime": "2019-08-02T01:36:02.000Z", "num_tokens": 7, "size": 20 }
/* statistics/gsl_statistics_char.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Jim Davies, 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. */ #ifndef __GSL_STATISTICS_CHAR_H__ #define __GSL_STATISTICS_CHAR_H__ #include <stddef.h> #include <gsl/gsl_types.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 GSL_EXPORT double gsl_stats_char_mean (const char data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_char_variance (const char data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_char_sd (const char data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_char_variance_with_fixed_mean (const char data[], const size_t stride, const size_t n, const double mean); GSL_EXPORT double gsl_stats_char_sd_with_fixed_mean (const char data[], const size_t stride, const size_t n, const double mean); GSL_EXPORT double gsl_stats_char_absdev (const char data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_char_skew (const char data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_char_kurtosis (const char data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_char_lag1_autocorrelation (const char data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_char_covariance (const char data1[], const size_t stride1,const char data2[], const size_t stride2, const size_t n); GSL_EXPORT double gsl_stats_char_variance_m (const char data[], const size_t stride, const size_t n, const double mean); GSL_EXPORT double gsl_stats_char_sd_m (const char data[], const size_t stride, const size_t n, const double mean); GSL_EXPORT double gsl_stats_char_absdev_m (const char data[], const size_t stride, const size_t n, const double mean); GSL_EXPORT double gsl_stats_char_skew_m_sd (const char data[], const size_t stride, const size_t n, const double mean, const double sd); GSL_EXPORT double gsl_stats_char_kurtosis_m_sd (const char data[], const size_t stride, const size_t n, const double mean, const double sd); GSL_EXPORT double gsl_stats_char_lag1_autocorrelation_m (const char data[], const size_t stride, const size_t n, const double mean); GSL_EXPORT double gsl_stats_char_covariance_m (const char data1[], const size_t stride1,const char data2[], const size_t stride2, const size_t n, const double mean1, const double mean2); GSL_EXPORT double gsl_stats_char_pvariance (const char data1[], const size_t stride1, const size_t n1, const char data2[], const size_t stride2, const size_t n2); GSL_EXPORT double gsl_stats_char_ttest (const char data1[], const size_t stride1, const size_t n1, const char data2[], const size_t stride2, const size_t n2); GSL_EXPORT char gsl_stats_char_max (const char data[], const size_t stride, const size_t n); GSL_EXPORT char gsl_stats_char_min (const char data[], const size_t stride, const size_t n); GSL_EXPORT void gsl_stats_char_minmax (char * min, char * max, const char data[], const size_t stride, const size_t n); GSL_EXPORT size_t gsl_stats_char_max_index (const char data[], const size_t stride, const size_t n); GSL_EXPORT size_t gsl_stats_char_min_index (const char data[], const size_t stride, const size_t n); GSL_EXPORT void gsl_stats_char_minmax_index (size_t * min_index, size_t * max_index, const char data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_char_median_from_sorted_data (const char sorted_data[], const size_t stride, const size_t n) ; GSL_EXPORT double gsl_stats_char_quantile_from_sorted_data (const char sorted_data[], const size_t stride, const size_t n, const double f) ; __END_DECLS #endif /* __GSL_STATISTICS_CHAR_H__ */
{ "alphanum_fraction": 0.7912063632, "avg_line_length": 58.7792207792, "ext": "h", "hexsha": "6bc8d9405e1dd7d52d5d0e538c5163f2b51ed44a", "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": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "dynaryu/vaws", "max_forks_repo_path": "src/core/gsl/include/gsl/gsl_statistics_char.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "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": "dynaryu/vaws", "max_issues_repo_path": "src/core/gsl/include/gsl/gsl_statistics_char.h", "max_line_length": 186, "max_stars_count": null, "max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "dynaryu/vaws", "max_stars_repo_path": "src/core/gsl/include/gsl/gsl_statistics_char.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1126, "size": 4526 }
/** * ex_gnuplot.h * * utility functions for plotting with gnuplot (v 4.6) * * - minimizes boilerplate needed to use * - popen -> process piping available, less temp files * - idea based on myexamples/gnuplot (syntax) and gnuplot_i by N. Devillard (pipes), except a bit simpler * * Aaro Salosensaari 2016 * * Original gnuplot_i was written by N. Devillard 1998 (version 2.10 2003) and is in public domain. */ #ifndef EX_GNUPLOT #define EX_GNUPLOT #include <stdarg.h> #include <stdio.h> #include <gsl/gsl_vector.h> #include "ex_util.h" #define GP_MAX_TMP_FILES 32 typedef struct { /* Pipe to gnuplot process */ FILE *gnucmd ; /* Number of currently active plots */ int nplots ; /* Pointer to table of names of temporary files */ char *tmp_filename_tbl[GP_MAX_TMP_FILES] ; /* Number of temporary files */ int ntmp ; } gnuplot_ctrl ; /** * Public interface function declarations */ gnuplot_ctrl *gnuplot_init(void); void gnuplot_close(gnuplot_ctrl *handle); /* * gnuplot_cmd * * This sends a string to an active gnuplot session, to be executed. * There is strictly no way to know if the command has been * successfully executed or not. * The command syntax is the same as printf. */ void gnuplot_cmd(gnuplot_ctrl *handle, char const *cmd, ...); /* * ex_plot_xf can plot a variable number n of x, f(x) plots. * * n: number of plots * xlow: * xhigh: * xstep: (self-evident) * f1: function to plot * title1: title * style1: gnuplot style spef * (repeat fi, titlei, stylei until i=n) */ void ex_plot_xf(gnuplot_ctrl *handle, const int n, double xlow, double xhigh, double xstep, db_fx f1, const char *title1, const char *style1, ...); /* * ex_plot_xys can plot a variable number n of x, y plots. * * n: number of plots * xdata: x points * ydata: y points * title1: title * style1: gnuplot style spef * (repeat xdatai, ydatai, titlei, stylei until i=n) */ void ex_plot_xys(gnuplot_ctrl *handle, const int n, gsl_vector *xdata1, gsl_vector *ydata1, const char *title1, const char *style1, ...); void gnuplot_xy(gnuplot_ctrl *handle, gsl_vector *xdata, gsl_vector *ydata, const char *title1, const char *style1); #endif /* ifndef EX_GNUPLOT */
{ "alphanum_fraction": 0.6975806452, "avg_line_length": 24, "ext": "h", "hexsha": "53374b58aa4e13606c7ec735ff962844b18d9143", "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": "17319213c85f65850c7b017bb4f3030d978ba936", "max_forks_repo_licenses": [ "Unlicense" ], "max_forks_repo_name": "aa-m-sa/ex_gnuplot_util", "max_forks_repo_path": "ex_gnuplot.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "17319213c85f65850c7b017bb4f3030d978ba936", "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": "aa-m-sa/ex_gnuplot_util", "max_issues_repo_path": "ex_gnuplot.h", "max_line_length": 147, "max_stars_count": 1, "max_stars_repo_head_hexsha": "17319213c85f65850c7b017bb4f3030d978ba936", "max_stars_repo_licenses": [ "Unlicense" ], "max_stars_repo_name": "aa-m-sa/ex_gnuplot_util", "max_stars_repo_path": "ex_gnuplot.h", "max_stars_repo_stars_event_max_datetime": "2017-10-15T03:41:21.000Z", "max_stars_repo_stars_event_min_datetime": "2017-10-15T03:41:21.000Z", "num_tokens": 663, "size": 2232 }
#include <stdlib.h> #include <stdio.h> #include <math.h> #include <fitsio.h> #include <gsl/gsl_statistics.h> #ifdef SPECTRIM #include "FBSpectrim.h" #else #include "fbus.h" #endif typedef struct _Box { double x; double y; double fwhm; double cenx; double ceny; double counts; double background; double noise; double sigmaxythresh; double sigmaxy; double sigmafwhmthresh; double sigmafwhm; int r; } Box; typedef struct _Back { double x; double y; double background; double sigma; int r; int width; } Back; Box box[4]; Back back; long nelements, naxes[2], fpixel; int boxsize = 13; double stardist(int i, int j) { return( sqrt( (box[i].cenx-box[j].cenx)*(box[i].cenx-box[j].cenx) + (box[i].ceny-box[j].ceny)*(box[i].ceny-box[j].ceny) ) ); } double seeing(double var, double d, double r) { double lambda; double b, K, seeing; lambda = 0.65e-6; b = r/d; /* pixel scale of 0.78 "/pixel, convert to rad */ var = var*pow(0.78/206265.0,2); K = 0.364*(1.0 - 0.532*pow(b, -1/3) - 0.024*pow(b, -7/3)); seeing = 206265.0*0.98*pow(d/lambda, 0.2)*pow(var/K, 0.6); return seeing; } double old_seeing(double var, double d, double r) { double lambda; double r0; lambda = 0.55e-6; /* pixel scale of 0.78 "/pixel, convert to rad */ var = var*pow(0.78/206265.0,2); r0 = pow(2.0*(lambda*lambda)*( ( 0.1790*pow(d, (-1.0/3.0)) - 0.0968*pow(r, (-1.0/3.0)) )/var ), 0.6); return 206265.0*0.98*lambda/r0; } int background(char *image) { int i, j, backpix; int low_y, up_y, low_x, up_x; double dist, sum, sumsq; backpix = 0; sum = 0.0; sumsq = 0.0; low_y = back.y - back.r - back.width; up_y = back.y + back.r + back.width; low_x = back.x - back.r - back.width; up_x = back.x + back.r + back.width; if (low_y < 0) { low_y = 0; } if (up_y >= 480) { up_y = 479; } if (low_x < 0) { low_x = 0; } if (up_x >= 640) { up_x = 639; } for (i=low_y; i<up_y; i++) { for (j=low_x; j<up_x; j++) { dist = sqrt(pow(back.x-j, 2) + pow(back.y-i, 2)); if (dist >= back.r && dist <= back.r+back.width) { sum += image[i*naxes[0]+j]; backpix++; } } } back.background = sum/backpix; for (i=low_y; i<up_y; i++) { for (j=low_x; j<up_x; j++) { dist = sqrt(pow(back.x-j, 2) + pow(back.y-i, 2)); if (dist >= back.r && dist <= back.r+back.width) { sumsq += (image[i*naxes[0]+j]-back.background)* (image[i*naxes[0]+j]-back.background); } } } back.sigma = sqrt(sumsq/backpix); return 1; } int centroid(char *image, int num) { int i, j; double sum = 0.0; double sumx = 0.0; double sumxx = 0.0; double sumy = 0.0; double sumyy = 0.0; double val = 0.0; double rmom; double dist; int low_y, up_y, low_x, up_x; int sourcepix = 0; low_y = box[num].y - box[num].r; up_y = box[num].y + box[num].r; low_x = box[num].x - box[num].r; up_x = box[num].x + box[num].r; if (low_y < 0) { low_y = 0; } if (up_y >= 480) { up_y = 479; } if (low_x < 0) { low_x = 0; } if (up_x >= 640) { up_x = 639; } for (i=low_y; i<up_y; i++) { for (j=low_x; j<up_x; j++) { dist = sqrt(pow(box[num].x-j, 2) + pow(box[num].y-i, 2)); if (dist <= box[num].r) { val = image[i*naxes[0]+j] - back.background; sum += val; sumx += val*j; sumxx += val*j*j; sumy += val*i; sumyy += val*i*i; sourcepix++; } } } if ( sum <= 0.0 ) { box[num].sigmaxy = -1.0; box[num].sigmafwhm = -1.0; box[num].cenx = 0.0; box[num].ceny = 0.0; box[num].fwhm = -1.0; } else { rmom = ( sumxx - sumx * sumx / sum + sumyy - sumy * sumy / sum ) / sum; if ( rmom <= 0 ) { box[num].fwhm = -1.0; } else { box[num].fwhm = sqrt(rmom) * 2.354 / sqrt(2.0); } box[num].counts = sum; box[num].cenx = sumx / sum; box[num].ceny = sumy / sum; box[num].x = box[num].cenx; box[num].y = box[num].ceny; box[num].sigmaxy= box[num].noise * sourcepix / box[num].counts / sqrt(6.0); box[num].sigmafwhm = box[num].noise * pow(sourcepix,1.5) / 10. / box[num].fwhm / box[num].counts * 2.354 * 2.354 / 2.0; } return 1; } int main() { char * buffer; fitsfile *fptr; int i, j, f, status, nimages, anynul, nboxes; char fitsfile[256]; char *froot; FILE *init, *out; float xx = 0.0, yy = 0.0, xsum = 0.0, ysum = 0.0; double dist01[900], dist02[900], dist03[900]; double dist12[900], dist13[900], dist23[900]; double sig01[900], sig02[900], sig03[900]; double sig12[900], sig13[900], sig23[900]; double mean01, mean02, mean03, mean12, mean13, mean23; double var01, var02, var03, var12, var13, var23, rad; double avesig01, avesig02, avesig03, avesig12, avesig13, avesig23; double d = 0.05; double r_01, r_02, r_03, r_12, r_13, r_23, seeing_ave; r_01 = 2.0*d; r_02 = 2.0*d; r_03 = 3.0*d; r_12 = 3.0*d; r_13 = 2.0*d; r_23 = 2.0*d; out = fopen("/dev/shm/video/seeing.dat", "a"); init = fopen("/dev/shm/video/init_cen_all", "r"); i = 0; while (fscanf(init, "%f %f\n", &xx, &yy) != EOF) { box[i].x = xx; box[i].cenx = xx; box[i].y = yy; box[i].ceny = yy; box[i].r = boxsize/2.0; i++; } fclose(init); back.r = 40; back.width = 5; status = 0; anynul = 0; naxes[0] = 640; naxes[1] = 480; fpixel = 1; nelements = naxes[0]*naxes[1]; /* init card */ if (FB_Init() == RET_ERROR) { printf("FlashBus failed init\n"); return(-1); } /* configure video capture */ FB_SetVideoConfig(TYPE_COMPOSITE, STANDARD_NTSC, 1, 0); /* set up offscreen video capture */ if (FB_VideoOffscreen(naxes[0], naxes[1], 8, TRUE) != RET_SUCCESS) { printf("Couldn't set offscreen capture\n"); return(-1); } /* allocate the buffer */ if (!(buffer = malloc(nelements*sizeof(char)))) { printf("Couldn't Allocate Image Buffer\n"); exit(-1); } FB_VideoLive(TRUE, ALIGN_ANY); FB_WaitVSync(12); nimages = 900; froot = "/dev/shm/video/seeing.fits"; for (f=0; f<nimages; f++) { FB_WaitVSync(1); FB_CopyVGARect(0, 0, naxes[0], naxes[1], buffer, -1, COPYDIR_FROMOFFSCREEN); xsum = 0.0; ysum = 0.0; for (i=0; i<4; i++) { xsum += box[i].cenx; ysum += box[i].ceny; } back.x = xsum/4.0; back.y = ysum/4.0; background(buffer); //printf("file: %s \t background = %f noise = %f\n", // fitsfile, back.background, back.sigma); for (i=0; i<4; i++) { box[i].noise = back.sigma; //box[i].r = boxsize/2.0; centroid(buffer, i); //box[i].r = boxsize/3.0; centroid(buffer, i); //box[i].r = boxsize/4.0; centroid(buffer, i); /* printf("\t star = %d, counts = %f, \n\t x = %f, y = %f, sigmaxy = %f\n", i, box[i].counts, box[i].cenx+1, box[i].ceny+1, box[i].sigmaxy); */ } dist01[f] = stardist(0, 1); sig01[f] = box[0].sigmaxy*box[0].sigmaxy + box[1].sigmaxy*box[1].sigmaxy; dist02[f] = stardist(0, 2); sig02[f] = box[0].sigmaxy*box[0].sigmaxy + box[2].sigmaxy*box[2].sigmaxy; dist03[f] = stardist(0, 3); sig03[f] = box[0].sigmaxy*box[0].sigmaxy + box[3].sigmaxy*box[3].sigmaxy; dist12[f] = stardist(1, 2); sig12[f] = box[1].sigmaxy*box[1].sigmaxy + box[2].sigmaxy*box[2].sigmaxy; dist13[f] = stardist(1, 3); sig13[f] = box[1].sigmaxy*box[1].sigmaxy + box[3].sigmaxy*box[3].sigmaxy; dist23[f] = stardist(2, 3); sig23[f] = box[3].sigmaxy*box[3].sigmaxy + box[2].sigmaxy*box[2].sigmaxy; } sprintf(fitsfile, "!%s", froot); fits_create_file(&fptr, fitsfile, &status); fits_create_img(fptr, BYTE_IMG, 2, naxes, &status); fits_write_img(fptr, TBYTE, fpixel, nelements, buffer, &status); fits_close_file(fptr, &status); fits_report_error(stderr, status); mean01 = gsl_stats_mean(dist01, 1, nimages); avesig01 = gsl_stats_mean(sig01, 1, nimages); printf("mean01 = %f, avesig01 = %f\n", mean01, avesig01); mean02 = gsl_stats_mean(dist02, 1, nimages); avesig02 = gsl_stats_mean(sig02, 1, nimages); printf("mean02 = %f, avesig02 = %f\n", mean02, avesig02); mean03 = gsl_stats_mean(dist03, 1, nimages); avesig03 = gsl_stats_mean(sig03, 1, nimages); printf("mean03 = %f, avesig03 = %f\n", mean03, avesig03); mean12 = gsl_stats_mean(dist12, 1, nimages); avesig12 = gsl_stats_mean(sig12, 1, nimages); printf("mean12 = %f, avesig12 = %f\n", mean12, avesig12); mean13 = gsl_stats_mean(dist13, 1, nimages); avesig13 = gsl_stats_mean(sig13, 1, nimages); printf("mean13 = %f, avesig13 = %f\n", mean13, avesig13); mean23 = gsl_stats_mean(dist23, 1, nimages); avesig23 = gsl_stats_mean(sig23, 1, nimages); printf("mean23 = %f, avesig23 = %f\n", mean23, avesig23); printf("\n"); var01 = gsl_stats_variance_m(dist01, 1, nimages, mean01); var01 = var01 - avesig01; printf("sigma01 = %f, seeing01 = %f\n", sqrt(var01), seeing(var01, d, r_01)); var02 = gsl_stats_variance_m(dist02, 1, nimages, mean02); var02 = var02 - avesig02; printf("sigma02 = %f, seeing02 = %f\n", sqrt(var02), seeing(var02, d, r_02)); var03 = gsl_stats_variance_m(dist03, 1, nimages, mean03); var03 = var03 - avesig03; printf("sigma03 = %f, seeing03 = %f\n", sqrt(var03), seeing(var03, d, r_03)); var12 = gsl_stats_variance_m(dist12, 1, nimages, mean12); var12 = var12 - avesig12; printf("sigma12 = %f, seeing12 = %f\n", sqrt(var12), seeing(var12, d, r_12)); var13 = gsl_stats_variance_m(dist13, 1, nimages, mean13); var13 = var13 - avesig13; printf("sigma13 = %f, seeing13 = %f\n", sqrt(var13), seeing(var13, d, r_13)); var23 = gsl_stats_variance_m(dist23, 1, nimages, mean23); var23 = var23 - avesig23; printf("sigma23 = %f, seeing23 = %f\n\n", sqrt(var23), seeing(var23, d, r_23)); seeing_ave = (seeing(var01, d, r_01) + seeing(var02, d, r_02) + seeing(var03, d, r_03) + seeing(var12, d, r_12) + seeing(var13, d, r_13) + seeing(var23, d, r_23))/6.0; printf("Ave. seeing = %4.2f\"\n", seeing_ave); fprintf(out, "%f %f %f %f %f %f %f\n", seeing(var01, d, r_01), seeing(var02, d, r_02), seeing(var03, d, r_03), seeing(var12, d, r_12), seeing(var13, d, r_13), seeing(var23, d, r_23), seeing_ave); init = fopen("/dev/shm/video/init_cen_all", "w"); for (i=0; i<4; i++) { fprintf(init, "%f %f\n", box[i].cenx, box[i].ceny); } fclose(init); return (status); }
{ "alphanum_fraction": 0.578049474, "avg_line_length": 24.3110599078, "ext": "c", "hexsha": "e06abefd7c949a3fc26c7b81a2f356a1754f8e01", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2017-12-01T13:02:36.000Z", "max_forks_repo_forks_event_min_datetime": "2015-07-29T15:16:35.000Z", "max_forks_repo_head_hexsha": "dde00a3bb6ca7c3d9b71e24f9363350a0e2a323f", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "marissakotze/timDIMM", "max_forks_repo_path": "src/measure_seeing_basic.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "dde00a3bb6ca7c3d9b71e24f9363350a0e2a323f", "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": "marissakotze/timDIMM", "max_issues_repo_path": "src/measure_seeing_basic.c", "max_line_length": 82, "max_stars_count": 1, "max_stars_repo_head_hexsha": "dde00a3bb6ca7c3d9b71e24f9363350a0e2a323f", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "marissakotze/timDIMM", "max_stars_repo_path": "src/measure_seeing_basic.c", "max_stars_repo_stars_event_max_datetime": "2021-06-06T15:26:36.000Z", "max_stars_repo_stars_event_min_datetime": "2021-06-06T15:26:36.000Z", "num_tokens": 4137, "size": 10551 }
#ifndef MESH_H #define MESH_H #define EIGEN_SUPERLU_SUPPORT #include <iostream> #include <iomanip> #include <cmath> #include <vector> #include <chrono> #include <armadillo> #include <petsc.h> #include "../TPLs/yaml-cpp/include/yaml-cpp/yaml.h" #include "../TPLs/eigen-git-mirror/Eigen/Eigen" #include "../TPLs/eigen-git-mirror/Eigen/IterativeLinearSolvers" #include "../TPLs/eigen-git-mirror/unsupported/Eigen/IterativeSolvers" #include "../TPLs/eigen-git-mirror/Eigen/SuperLUSupport" using namespace std; class WriteData; // forward declaration class qdCell { public: qdCell(); //number of ordinates on this quadrature level int cFIndex=0,nFIndex=0,sFIndex=0,eFIndex=0,wFIndex=0; int nCIndex=0,sCIndex=0,eCIndex=0,wCIndex=0; }; class quadLevel { public: quadLevel(vector< vector<double> > myQuad,\ vector<double> myAlpha,\ vector<double> myTau,\ int myStartIndex); //number of ordinates on this quadrature level int nOrd; //quadrature set vector< vector<double> > quad; //difference coefficients vector<double> alpha; //factor for linear interpolation of half angles vector<double> tau; //index of each ordinate in angular flux matrices vector<int> ordIdx; }; class Mesh { public: Mesh(YAML::Node * myInput); int n,nAngles,nR,nZ; int state = 1; double dz,dr,drCorner,dzCorner,Z,R,dt,T,totalWeight; bool verbose = false, petsc = false, verbose_keff_only = false; vector< vector<double> > quadSet; vector< vector<double> > alpha; vector< vector<double> > tau; vector< vector<double> > cellVol; vector< vector<double> > cellVSA; vector<double> dts; vector<double> ts; vector<bool> outputOnStep; arma::rowvec dzs,dzsCorner; arma::rowvec drs,drsCorner; arma::rowvec rEdge; arma::rowvec zEdge; arma::rowvec rCent; arma::rowvec zCent; arma::rowvec rCornerEdge; arma::rowvec zCornerEdge; arma::rowvec rCornerCent; arma::rowvec zCornerCent; arma::rowvec rVWCornerCent; vector<quadLevel> quadrature; vector<qdCell> qdCells; Eigen::MatrixXd volume; string outputDir = "mesh/"; WriteData * output; // Recirculation loop parameters double dzCornerRecirc,recircZ; int nZrecirc; arma::rowvec zCornerEdgeRecirc,dzsCornerRecirc; arma::rowvec zCornerCentRecirc; // Functions vector<int> getQDCellIndices(int iR, int iZ); vector<double> getGeoParams(int iR, int iZ); vector<double> getRecircGeoParams(int iR, int iZ); void advanceOneTimeStep(); void calcQuadSet(); void writeVars(); void printQuadSet(); void checkOptionalParams(); private: vector<double> mu; vector< vector<double> > ordinates; void calcMu(); void calcAlpha(); void calcTau(); void calcSpatialMesh(); void calcQDCellIndices(int nCornersR,int nCornersZ); void addLevels(); void calcNumAnglesTotalWeight(); void calcTimeMesh(); void calcRecircMesh(); int quad_index(int p,int q); int low_quad_index(int p,int q); int getQDCellIndex(int iR,int iZ); YAML::Node * input; }; typedef Eigen::Array<bool,Eigen::Dynamic,1> VectorXb; #endif
{ "alphanum_fraction": 0.6723352566, "avg_line_length": 26.5564516129, "ext": "h", "hexsha": "002e717da7d5648bdbb34454f9f3c51eabf52115", "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": "02485438a6b58a0210eb0b2da3db8a7a37b57bb9", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "khurrumsaleem/QuasiMolto", "max_forks_repo_path": "libs/Mesh.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "02485438a6b58a0210eb0b2da3db8a7a37b57bb9", "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": "khurrumsaleem/QuasiMolto", "max_issues_repo_path": "libs/Mesh.h", "max_line_length": 71, "max_stars_count": null, "max_stars_repo_head_hexsha": "02485438a6b58a0210eb0b2da3db8a7a37b57bb9", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "khurrumsaleem/QuasiMolto", "max_stars_repo_path": "libs/Mesh.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 904, "size": 3293 }
/* linalg/cod.c * * Copyright (C) 2016, 2017 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_permute_vector.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> /* * This module contains routines for factoring an M-by-N matrix A as: * * A P = Q R Z^T * * known as the Complete Orthogonal Decomposition, where: * * P is a N-by-N permutation matrix * Q is M-by-M orthogonal * R has an r-by-r upper triangular block * Z is N-by-N orthogonal * * When A is full rank, Z = I and this becomes the QR decomposition * with column pivoting. When A is rank deficient, then * * R = [ R11 0 ] where R11 is r-by-r and r = rank(A) * [ 0 0 ] */ static int cod_RZ(gsl_matrix * A, gsl_vector * tau); static double cod_householder_transform(double *alpha, gsl_vector * v); static int cod_householder_mh(const double tau, const gsl_vector * v, gsl_matrix * A, gsl_vector * work); static int cod_householder_hv(const double tau, const gsl_vector * v, gsl_vector * w); static int cod_householder_Zvec(const gsl_matrix * QRZT, const gsl_vector * tau_Z, const size_t rank, gsl_vector * v); static int cod_trireg_solve(const gsl_matrix * R, const double lambda, const gsl_vector * b, gsl_matrix * S, gsl_vector * x, gsl_vector * work); int gsl_linalg_COD_decomp_e(gsl_matrix * A, gsl_vector * tau_Q, gsl_vector * tau_Z, gsl_permutation * p, double tol, size_t * rank, gsl_vector * work) { const size_t M = A->size1; const size_t N = A->size2; if (tau_Q->size != GSL_MIN (M, N)) { GSL_ERROR ("size of tau_Q must be MIN(M,N)", GSL_EBADLEN); } else if (tau_Z->size != GSL_MIN (M, N)) { GSL_ERROR ("size of tau_Z must be MIN(M,N)", GSL_EBADLEN); } else if (p->size != N) { GSL_ERROR ("permutation size must be N", GSL_EBADLEN); } else if (work->size != N) { GSL_ERROR ("work size must be N", GSL_EBADLEN); } else { int status, signum; size_t r; /* decompose: A P = Q R */ status = gsl_linalg_QRPT_decomp(A, tau_Q, p, &signum, work); if (status) return status; /* estimate rank of A */ r = gsl_linalg_QRPT_rank(A, tol); if (r < N) { /* * matrix is rank-deficient, so that the R factor is * * R = [ R11 R12 ] =~ [ R11 R12 ] * [ 0 R22 ] [ 0 0 ] * * compute RZ decomposition of upper trapezoidal matrix * [ R11 R12 ] = [ R11~ 0 ] Z */ gsl_matrix_view R_upper = gsl_matrix_submatrix(A, 0, 0, r, N); gsl_vector_view t = gsl_vector_subvector(tau_Z, 0, r); cod_RZ(&R_upper.matrix, &t.vector); } *rank = r; return GSL_SUCCESS; } } int gsl_linalg_COD_decomp(gsl_matrix * A, gsl_vector * tau_Q, gsl_vector * tau_Z, gsl_permutation * p, size_t * rank, gsl_vector * work) { return gsl_linalg_COD_decomp_e(A, tau_Q, tau_Z, p, -1.0, rank, work); } /* gsl_linalg_COD_lssolve() Find the least squares solution to the overdetermined system min ||b - A x||^2 for M >= N using the COD factorization A P = Q R Z Inputs: QRZT - matrix A, in COD compressed format, M-by-N tau_Q - Householder scalars for Q, length min(M,N) tau_Z - Householder scalars for Z, length min(M,N) perm - permutation matrix rank - rank of A b - rhs vector, length M x - (output) solution vector, length N residual - (output) residual vector, b - A x, length M */ int gsl_linalg_COD_lssolve (const gsl_matrix * QRZT, const gsl_vector * tau_Q, const gsl_vector * tau_Z, const gsl_permutation * perm, const size_t rank, const gsl_vector * b, gsl_vector * x, gsl_vector * residual) { const size_t M = QRZT->size1; const size_t N = QRZT->size2; if (M < N) { GSL_ERROR ("QRZT matrix must have M>=N", GSL_EBADLEN); } else if (M != b->size) { GSL_ERROR ("matrix size must match b size", GSL_EBADLEN); } else if (rank > GSL_MIN (M, N)) { GSL_ERROR ("rank must be <= MIN(M,N)", GSL_EBADLEN); } else if (N != x->size) { GSL_ERROR ("matrix size must match solution size", GSL_EBADLEN); } else if (M != residual->size) { GSL_ERROR ("matrix size must match residual size", GSL_EBADLEN); } else { gsl_matrix_const_view R11 = gsl_matrix_const_submatrix (QRZT, 0, 0, rank, rank); gsl_vector_view QTb1 = gsl_vector_subvector(residual, 0, rank); gsl_vector_view x1 = gsl_vector_subvector(x, 0, rank); gsl_vector_set_zero(x); /* compute residual = Q^T b = [ c1 ; c2 ] */ gsl_vector_memcpy(residual, b); gsl_linalg_QR_QTvec (QRZT, tau_Q, residual); /* solve x1 := R11^{-1} (Q^T b)(1:r) */ gsl_vector_memcpy(&(x1.vector), &(QTb1.vector)); gsl_blas_dtrsv(CblasUpper, CblasNoTrans, CblasNonUnit, &(R11.matrix), &(x1.vector)); /* compute Z ( R11^{-1} x1; 0 ) */ cod_householder_Zvec(QRZT, tau_Z, rank, x); /* compute x = P Z^T ( R11^{-1} x1; 0 ) */ gsl_permute_vector_inverse(perm, x); /* compute residual = b - A x = Q (Q^T b - R [ R11^{-1} x1; 0 ]) = Q [ 0 ; c2 ] */ gsl_vector_set_zero(&(QTb1.vector)); gsl_linalg_QR_Qvec(QRZT, tau_Q, residual); return GSL_SUCCESS; } } /* gsl_linalg_COD_lssolve2() Find the least squares solution to the Tikhonov regularized system in standard form: min ||b - A x||^2 + lambda^2 ||x||^2 for M >= N using the COD factorization A P = Q R Z Inputs: lambda - parameter QRZT - matrix A, in COD compressed format, M-by-N tau_Q - Householder scalars for Q, length min(M,N) tau_Z - Householder scalars for Z, length min(M,N) perm - permutation matrix rank - rank of A b - rhs vector, length M x - (output) solution vector, length N residual - (output) residual vector, b - A x, length M S - workspace, rank-by-rank work - workspace, length rank */ int gsl_linalg_COD_lssolve2 (const double lambda, const gsl_matrix * QRZT, const gsl_vector * tau_Q, const gsl_vector * tau_Z, const gsl_permutation * perm, const size_t rank, const gsl_vector * b, gsl_vector * x, gsl_vector * residual, gsl_matrix * S, gsl_vector * work) { const size_t M = QRZT->size1; const size_t N = QRZT->size2; if (M < N) { GSL_ERROR ("QRZT matrix must have M>=N", GSL_EBADLEN); } else if (M != b->size) { GSL_ERROR ("matrix size must match b size", GSL_EBADLEN); } else if (rank > GSL_MIN (M, N)) { GSL_ERROR ("rank must be <= MIN(M,N)", GSL_EBADLEN); } else if (N != x->size) { GSL_ERROR ("matrix size must match solution size", GSL_EBADLEN); } else if (M != residual->size) { GSL_ERROR ("matrix size must match residual size", GSL_EBADLEN); } else if (S->size1 != rank || S->size2 != rank) { GSL_ERROR ("S must be rank-by-rank", GSL_EBADLEN); } else if (work->size != rank) { GSL_ERROR ("work must be length rank", GSL_EBADLEN); } else { gsl_matrix_const_view R11 = gsl_matrix_const_submatrix (QRZT, 0, 0, rank, rank); gsl_vector_view c1 = gsl_vector_subvector(residual, 0, rank); gsl_vector_view y1 = gsl_vector_subvector(x, 0, rank); gsl_vector_set_zero(x); /* compute residual = Q^T b = [ c1 ; c2 ]*/ gsl_vector_memcpy(residual, b); gsl_linalg_QR_QTvec (QRZT, tau_Q, residual); /* solve [ R11 ; lambda*I ] y1 = [ (Q^T b)(1:r) ; 0 ] */ cod_trireg_solve(&(R11.matrix), lambda, &(c1.vector), S, &(y1.vector), work); /* save y1 for later residual calculation */ gsl_vector_memcpy(work, &(y1.vector)); /* compute Z [ y1; 0 ] */ cod_householder_Zvec(QRZT, tau_Z, rank, x); /* compute x = P Z^T ( y1; 0 ) */ gsl_permute_vector_inverse(perm, x); /* compute residual = b - A x = Q (Q^T b - [ R11 y1; 0 ]) = Q [ c1 - R11*y1 ; c2 ] */ /* work = R11*y1 */ gsl_blas_dtrmv(CblasUpper, CblasNoTrans, CblasNonUnit, &(R11.matrix), work); gsl_vector_sub(&(c1.vector), work); gsl_linalg_QR_Qvec(QRZT, tau_Q, residual); return GSL_SUCCESS; } } /* gsl_linalg_COD_unpack() Unpack encoded COD decomposition into the matrices Q,R,Z,P Inputs: QRZT - encoded COD decomposition tau_Q - Householder scalars for Q tau_Z - Householder scalars for Z rank - rank of matrix (as determined from gsl_linalg_COD_decomp) Q - (output) M-by-M matrix Q R - (output) M-by-N matrix R Z - (output) N-by-N matrix Z */ int gsl_linalg_COD_unpack(const gsl_matrix * QRZT, const gsl_vector * tau_Q, const gsl_vector * tau_Z, const size_t rank, gsl_matrix * Q, gsl_matrix * R, gsl_matrix * Z) { const size_t M = QRZT->size1; const size_t N = QRZT->size2; if (tau_Q->size != GSL_MIN (M, N)) { GSL_ERROR ("size of tau_Q must be MIN(M,N)", GSL_EBADLEN); } else if (tau_Z->size != GSL_MIN (M, N)) { GSL_ERROR ("size of tau_Z must be MIN(M,N)", GSL_EBADLEN); } else if (rank > GSL_MIN (M, N)) { GSL_ERROR ("rank must be <= MIN(M,N)", GSL_EBADLEN); } else if (Q->size1 != M || Q->size2 != M) { GSL_ERROR ("Q must by M-by-M", GSL_EBADLEN); } else if (R->size1 != M || R->size2 != N) { GSL_ERROR ("R must by M-by-N", GSL_EBADLEN); } else if (Z->size1 != N || Z->size2 != N) { GSL_ERROR ("Z must by N-by-N", GSL_EBADLEN); } else { size_t i; gsl_matrix_view R11 = gsl_matrix_submatrix(R, 0, 0, rank, rank); gsl_matrix_const_view QRZT11 = gsl_matrix_const_submatrix(QRZT, 0, 0, rank, rank); /* form Q matrix */ gsl_matrix_set_identity(Q); for (i = GSL_MIN (M, N); i-- > 0;) { gsl_vector_const_view h = gsl_matrix_const_subcolumn (QRZT, i, i, M - i); gsl_matrix_view m = gsl_matrix_submatrix (Q, i, i, M - i, M - i); double ti = gsl_vector_get (tau_Q, i); gsl_linalg_householder_hm (ti, &h.vector, &m.matrix); } /* form Z matrix */ gsl_matrix_set_identity(Z); if (rank < N) { gsl_vector_view work = gsl_matrix_row(R, 0); /* temporary workspace, size N */ /* multiply I by Z from the right */ gsl_linalg_COD_matZ(QRZT, tau_Z, rank, Z, &work.vector); } /* copy rank-by-rank upper triangle of QRZT into R and zero the rest */ gsl_matrix_set_zero(R); gsl_matrix_tricpy('U', 1, &R11.matrix, &QRZT11.matrix); return GSL_SUCCESS; } } /* gsl_linalg_COD_matZ Multiply an M-by-N matrix A on the right by Z (N-by-N) Inputs: QRZT - encoded COD matrix tau_Z - Householder scalars for Z rank - matrix rank A - on input, M-by-N matrix on output, A * Z work - workspace of length M */ int gsl_linalg_COD_matZ(const gsl_matrix * QRZT, const gsl_vector * tau_Z, const size_t rank, gsl_matrix * A, gsl_vector * work) { const size_t M = A->size1; const size_t N = A->size2; if (tau_Z->size != GSL_MIN (QRZT->size1, QRZT->size2)) { GSL_ERROR("tau_Z must be GSL_MIN(M,N)", GSL_EBADLEN); } else if (QRZT->size2 != N) { GSL_ERROR("QRZT must have N columns", GSL_EBADLEN); } else if (work->size != M) { GSL_ERROR("workspace must be length M", GSL_EBADLEN); } else { /* if rank == N, then Z = I and there is nothing to do */ if (rank < N) { size_t i; for (i = rank; i > 0 && i--; ) { gsl_vector_const_view h = gsl_matrix_const_subrow (QRZT, i, rank, N - rank); gsl_matrix_view m = gsl_matrix_submatrix (A, 0, i, M, N - i); double ti = gsl_vector_get (tau_Z, i); cod_householder_mh (ti, &h.vector, &m.matrix, work); } } return GSL_SUCCESS; } } /********************************************* * INTERNAL ROUTINES * *********************************************/ /* cod_RZ() Perform RZ decomposition of an upper trapezoidal matrix, A = [ A11 A12 ] = [ R 0 ] Z where A is M-by-N with N >= M, A11 is M-by-M upper triangular, and A12 is M-by-(N-M). On output, Z is stored as Householder reflectors in the A12 portion of A, Z = Z(1) Z(2) ... Z(M) Inputs: A - M-by-N matrix with N >= M On input, upper trapezoidal matrix [ A11 A12 ] On output, A11 is overwritten by R (subdiagonal elements are not touched), and A12 is overwritten by Z in packed storage tau - (output) Householder scalars, size M */ static int cod_RZ(gsl_matrix * A, gsl_vector * tau) { const size_t M = A->size1; const size_t N = A->size2; if (tau->size != M) { GSL_ERROR("tau has wrong size", GSL_EBADLEN); } else if (N < M) { GSL_ERROR("N must be >= M", GSL_EINVAL); } else if (M == N) { /* quick return */ gsl_vector_set_all(tau, 0.0); return GSL_SUCCESS; } else { size_t k; for (k = M; k > 0 && k--; ) { double *alpha = gsl_matrix_ptr(A, k, k); gsl_vector_view z = gsl_matrix_subrow(A, k, M, N - M); double tauk; /* compute Householder reflection to zero [ A(k,k) A(k,M+1:N) ] */ tauk = cod_householder_transform(alpha, &z.vector); gsl_vector_set(tau, k, tauk); if ((tauk != 0) && (k > 0)) { gsl_vector_view w = gsl_vector_subvector(tau, 0, k); gsl_matrix_view B = gsl_matrix_submatrix(A, 0, k, k, N - k); cod_householder_mh(tauk, &z.vector, &B.matrix, &w.vector); } } return GSL_SUCCESS; } } static double cod_householder_transform(double *alpha, gsl_vector * v) { double beta, tau; double xnorm = gsl_blas_dnrm2(v); if (xnorm == 0) { return 0.0; /* tau = 0 */ } beta = - (*alpha >= 0.0 ? +1.0 : -1.0) * gsl_hypot(*alpha, xnorm); tau = (beta - *alpha) / beta; { double s = (*alpha - beta); if (fabs(s) > GSL_DBL_MIN) { gsl_blas_dscal (1.0 / s, v); } else { gsl_blas_dscal (GSL_DBL_EPSILON / s, v); gsl_blas_dscal (1.0 / GSL_DBL_EPSILON, v); } *alpha = beta; } return tau; } /* cod_householder_hv Apply Householder reflection H = (I - tau*v*v') to vector v from the left, w' = H * w Inputs: tau - Householder scalar v - Householder vector, size M w - on input, w vector, size M on output, H * w Notes: 1) Based on LAPACK routine DLARZ */ static int cod_householder_hv(const double tau, const gsl_vector * v, gsl_vector * w) { if (tau == 0) { return GSL_SUCCESS; /* H = I */ } else { const size_t M = w->size; const size_t L = v->size; double w0 = gsl_vector_get(w, 0); gsl_vector_view w1 = gsl_vector_subvector(w, M - L, L); double d1, d; /* d1 := v . w(M-L:M) */ gsl_blas_ddot(v, &w1.vector, &d1); /* d := w(1) + v . w(M-L:M) */ d = w0 + d1; /* w(1) = w(1) - tau * d */ gsl_vector_set(w, 0, w0 - tau * d); /* w(M-L:M) = w(M-L:M) - tau * d * v */ gsl_blas_daxpy(-tau * d, v, &w1.vector); return GSL_SUCCESS; } } /* cod_householder_mh Apply Householder reflection H = (I - tau*v*v') to matrix A from the right Inputs: tau - Householder scalar v - Householder vector, size N-M A - matrix, size M-by-N work - workspace, size M Notes: 1) Based on LAPACK routine DLARZ */ static int cod_householder_mh(const double tau, const gsl_vector * v, gsl_matrix * A, gsl_vector * work) { if (tau == 0) { return GSL_SUCCESS; /* H = I */ } else { const size_t M = A->size1; const size_t N = A->size2; const size_t L = v->size; gsl_vector_view A1 = gsl_matrix_subcolumn(A, 0, 0, M); gsl_matrix_view C = gsl_matrix_submatrix(A, 0, N - L, M, L); /* work(1:M) = A(1:M,1) */ gsl_vector_memcpy(work, &A1.vector); /* work(1:M) = work(1:M) + A(1:M,M+1:N) * v(1:N-M) */ gsl_blas_dgemv(CblasNoTrans, 1.0, &C.matrix, v, 1.0, work); /* A(1:M,1) = A(1:M,1) - tau * work(1:M) */ gsl_blas_daxpy(-tau, work, &A1.vector); /* A(1:M,M+1:N) = A(1:M,M+1:N) - tau * work(1:M) * v(1:N-M)' */ gsl_blas_dger(-tau, work, v, &C.matrix); return GSL_SUCCESS; } } /* cod_householder_Zvec Multiply a vector by Z Inputs: QRZT - encoded COD matrix tau_Z - Householder scalars for Z rank - matrix rank v - on input, vector of length N on output, Z^T * v */ static int cod_householder_Zvec(const gsl_matrix * QRZT, const gsl_vector * tau_Z, const size_t rank, gsl_vector * v) { const size_t M = QRZT->size1; const size_t N = QRZT->size2; if (tau_Z->size != GSL_MIN (M, N)) { GSL_ERROR("tau_Z must be GSL_MIN(M,N)", GSL_EBADLEN); } else if (v->size != N) { GSL_ERROR("v must be length N", GSL_EBADLEN); } else { if (rank < N) { size_t i; for (i = 0; i < rank; ++i) { gsl_vector_const_view h = gsl_matrix_const_subrow (QRZT, i, rank, N - rank); gsl_vector_view w = gsl_vector_subvector (v, i, N - i); double ti = gsl_vector_get (tau_Z, i); cod_householder_hv(ti, &h.vector, &w.vector); } } return GSL_SUCCESS; } } /* cod_trireg_solve() This function computes the solution to the least squares system [ R ] x = [ b ] [ lambda*I ] [ 0 ] where R is an N-by-N upper triangular matrix, lambda is a scalar parameter, and b is a vector of length N. This is done by computing the QR factorization [ R ] = W S^T [ lambda*I ] where S^T is upper triangular, and solving S^T x = W^T [ b ] [ 0 ] Inputs: R - full rank upper triangular matrix; the diagonal elements are modified but restored on output lambda - scalar parameter lambda b - right hand side vector b S - workspace, N-by-N x - (output) least squares solution of the system work - workspace of length N */ static int cod_trireg_solve (const gsl_matrix * R, const double lambda, const gsl_vector * b, gsl_matrix * S, gsl_vector * x, gsl_vector * work) { const size_t N = R->size2; gsl_vector_const_view diag = gsl_matrix_const_diagonal(R); size_t i, j, k; if (lambda <= 0.0) { GSL_ERROR("lambda must be positive", GSL_EINVAL); } /* copy R and b to preserve input and initialise S; store diag(R) in work */ gsl_matrix_transpose_tricpy('U', 0, S, R); gsl_vector_memcpy(work, &diag.vector); gsl_vector_memcpy(x, b); /* eliminate the diagonal matrix lambda*I using Givens rotations */ for (j = 0; j < N; j++) { double bj = 0.0; gsl_matrix_set (S, j, j, lambda); for (k = j + 1; k < N; k++) { gsl_matrix_set (S, k, k, 0.0); } /* the transformations to eliminate the row of lambda*I modify only a single element of b beyond the first n, which is initially zero */ for (k = j; k < N; k++) { /* determine a Givens rotation which eliminates the appropriate element in the current row of lambda*I */ double sine, cosine; double xk = gsl_vector_get (x, k); double rkk = gsl_vector_get (work, k); double skk = gsl_matrix_get (S, k, k); if (skk == 0) { continue; } if (fabs (rkk) < fabs (skk)) { double cotangent = rkk / skk; sine = 0.5 / sqrt (0.25 + 0.25 * cotangent * cotangent); cosine = sine * cotangent; } else { double tangent = skk / rkk; cosine = 0.5 / sqrt (0.25 + 0.25 * tangent * tangent); sine = cosine * tangent; } /* Compute the modified diagonal element of r and the modified element of [b,0] */ { double new_rkk = cosine * rkk + sine * skk; double new_xk = cosine * xk + sine * bj; bj = -sine * xk + cosine * bj; gsl_vector_set(work, k, new_rkk); gsl_matrix_set(S, k, k, new_rkk); gsl_vector_set(x, k, new_xk); } /* Accumulate the transformation in the row of s */ for (i = k + 1; i < N; i++) { double sik = gsl_matrix_get (S, i, k); double sii = gsl_matrix_get (S, i, i); double new_sik = cosine * sik + sine * sii; double new_sii = -sine * sik + cosine * sii; gsl_matrix_set(S, i, k, new_sik); gsl_matrix_set(S, i, i, new_sii); } } } /* solve: S^T x = rhs in place */ gsl_blas_dtrsv(CblasLower, CblasTrans, CblasNonUnit, S, x); return GSL_SUCCESS; }
{ "alphanum_fraction": 0.5670634216, "avg_line_length": 28.3220125786, "ext": "c", "hexsha": "53d12e81732c25357371464d363e3f921107a83f", "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/cod.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/cod.c", "max_line_length": 122, "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/cod.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": 6625, "size": 22516 }
#ifndef PROB_FUNCTIONS_H #define PROB_FUNCTIONS_H #include <gsl/gsl_vector.h> #include "data.h" double my_f (const gsl_vector *x, void *params); void my_df (const gsl_vector *x, void *params, gsl_vector *g); void my_fdf (const gsl_vector *x, void *params, double *f, gsl_vector *g); void gradientQ (Dataset *data, double *dQdAlpha, double *dQdBeta); double computeLikelihood (Dataset *data); double computeQ (Dataset *data); double logProbL (int l, int z, double alphaI, double betaJ); double prob(double alpha, double beta); void EStep (Dataset *data); void MStep (Dataset *data); #endif
{ "alphanum_fraction": 0.75, "avg_line_length": 31.1578947368, "ext": "h", "hexsha": "e18245749b4f616187bd8d88160de0e650f5278a", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2019-02-25T18:59:03.000Z", "max_forks_repo_forks_event_min_datetime": "2019-02-25T18:59:03.000Z", "max_forks_repo_head_hexsha": "03e0bfeda422975c118efe91fe31045f9c27f002", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "ShreyaR/WorkerPoolSelection", "max_forks_repo_path": "EM/prob_functions.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "03e0bfeda422975c118efe91fe31045f9c27f002", "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": "ShreyaR/WorkerPoolSelection", "max_issues_repo_path": "EM/prob_functions.h", "max_line_length": 74, "max_stars_count": null, "max_stars_repo_head_hexsha": "03e0bfeda422975c118efe91fe31045f9c27f002", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "ShreyaR/WorkerPoolSelection", "max_stars_repo_path": "EM/prob_functions.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 167, "size": 592 }
//This computes the IDFT (inverse discrete Fourier transformation) along dim of matrix X. //This uses a CBLAS matrix multiplication by the IDFT matrix. //The real-valued case is complicated (i.e., where only real part is output). //This will only exactly invert with DFT if the DFT output all F=ndft/2+1 positive freqs. //That is, use of this function to invert a specific DFT requires knowledge of how that DFT was run. //Profile note: I tried splitting the matrix multiply into two halves, //for positive and negative freqs, so that X would not need to be copied into Xc, //but it was definitely slower. #include <stdio.h> #include <stdlib.h> #include <math.h> #include <cblas.h> #ifndef M_PI #define M_PI 3.14159265358979323846 #endif #ifdef __cplusplus namespace codee { extern "C" { #endif int idft_cblas_s (float *Y, const float *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const size_t ndft, const int sc); int idft_cblas_d (double *Y, const double *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const size_t ndft, const int sc); int idft_cblas_c (float *Y, const float *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const size_t ndft, const int sc); int idft_cblas_z (double *Y, const double *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const size_t ndft, const int sc); int idft_cblas_s (float *Y, const float *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const size_t ndft, const int sc) { if (dim>3u) { fprintf(stderr,"error in idft_cblas_s: dim must be in [0 3]\n"); return 1; } const size_t N = R*C*S*H; const size_t Lx = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H; if (ndft<Lx) { fprintf(stderr,"error in idft_cblas_s: ndft must be >= Lx (length of vecs in X)\n"); return 1; } //Scaling const float s = sc ? 2.0f*sqrtf(0.5f*(float)ndft)/(float)ndft : 1.0f/(float)ndft; if (N==0u || ndft==0u) {} else if (ndft==1u) { for (size_t n=N; n>0u; --n, ++X, ++Y) { *Y = *X; } } else { //Init IDFT matrix const size_t NN = ndft * ndft; const float P2_N = (float)(2.0*M_PI/(double)ndft); float *IDFT; IDFT = (float *)aligned_alloc(sizeof(float),2u*NN*sizeof(float)); if (!IDFT) { fprintf(stderr,"error in idft_cblas_s: problem with aligned_alloc. "); perror("aligned_alloc"); return 1; } for (size_t l=0u; l<ndft; ++l) { *IDFT++ = s; *IDFT++ = 0.0f; } for (size_t n=1u; n<ndft; ++n) { for (size_t l=0u; l<ndft; ++l) { *IDFT++ = s * cosf(P2_N*(float)n*(float)l); *IDFT++ = s * sinf(P2_N*(float)n*(float)l); } } IDFT -= 2u*NN; //Init complex matrix multiply const float z[2] = {0.0f,0.0f}, o[2] = {1.0f,0.0f}; float *Xc, *Yc; Xc = (float *)aligned_alloc(sizeof(float),2u*ndft*sizeof(float)); Yc = (float *)aligned_alloc(sizeof(float),2u*ndft*sizeof(float)); if (!Xc) { fprintf(stderr,"error in idft_cblas_s: problem with aligned_alloc. "); perror("aligned_alloc"); return 1; } if (!Yc) { fprintf(stderr,"error in idft_cblas_s: problem with aligned_alloc. "); perror("aligned_alloc"); return 1; } for (size_t n=0u; n<2u*ndft; ++n, ++Xc) { *Xc = 0.0f; } Xc -= 2u*ndft; if (Lx==N) { //Copy into Xc for (size_t nf=Lx; nf>0u; --nf) { *Xc++ = *X++; *Xc++ = *X++; } if (ndft%2u==0u) { X -= 2; } for (size_t nf=ndft-ndft/2u; nf>1u; --nf) { X-=2; *Xc++ = *X; *Xc++ = -*(X+1); } Xc -= 2u*ndft; //Matrix multiply cblas_cgemv(CblasRowMajor,CblasNoTrans,(int)ndft,(int)ndft,o,IDFT,(int)ndft,Xc,1,z,Yc,1); //Output real part only cblas_scopy((int)ndft,Yc,2,Y,1); } else { const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u); const size_t B = (iscolmajor && dim==0u) ? C*S*H : K; const size_t V = N/Lx, G = V/B; if (K==1u && (G==1u || B==1u)) { for (size_t v=0u; v<V; ++v, Y+=ndft) { //Copy into Xc for (size_t nf=Lx; nf>0u; --nf) { *Xc++ = *X++; *Xc++ = *X++; } if (ndft%2u==0u) { X -= 2; } for (size_t nf=ndft-ndft/2u; nf>1u; --nf) { X-=2; *Xc++ = *X; *Xc++ = -*(X+1); } Xc -= 2u*ndft; X += 2u*(ndft-ndft/2u-ndft%2u); //Matrix multiply cblas_cgemv(CblasRowMajor,CblasNoTrans,(int)ndft,(int)ndft,o,IDFT,(int)ndft,Xc,1,z,Yc,1); //Output real part only cblas_scopy((int)ndft,Yc,2,Y,1); } } else { for (size_t g=G; g>0u; --g, X+=2u*B*(Lx-1u), Y+=B*(ndft-1u)) { for (size_t b=B; b>0u; --b, X+=2u*K*(ndft-ndft/2u-ndft%2u-Lx)+2u, ++Y) { //Copy into Xc for (size_t nf=Lx; nf>0u; --nf, X+=2u*K) { *Xc++ = *X; *Xc++ = *(X+1); } if (ndft%2u==0u) { X -= 2u*K; } for (size_t nf=ndft-ndft/2u; nf>1u; --nf) { X-=2u*K; *Xc++ = *X; *Xc++ = -*(X+1); } Xc -= 2u*ndft; //Matrix multiply cblas_cgemv(CblasRowMajor,CblasNoTrans,(int)ndft,(int)ndft,o,IDFT,(int)ndft,Xc,1,z,Yc,1); //Output real part only cblas_scopy((int)ndft,Yc,2,Y,(int)K); } } } } free(IDFT); free(Xc); free(Yc); } return 0; } int idft_cblas_d (double *Y, const double *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const size_t ndft, const int sc) { if (dim>3u) { fprintf(stderr,"error in idft_cblas_d: dim must be in [0 3]\n"); return 1; } const size_t N = R*C*S*H; const size_t Lx = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H; if (ndft<Lx) { fprintf(stderr,"error in idft_cblas_d: ndft must be >= Lx (length of vecs in X)\n"); return 1; } //Scaling const double s = sc ? 2.0*sqrt(0.5*(double)ndft)/(double)ndft : 1.0/(double)ndft; if (N==0u || ndft==0u) {} else if (ndft==1u) { for (size_t n=N; n>0u; --n, ++X, ++Y) { *Y = *X; } } else { //Init IDFT matrix const size_t NN = ndft * ndft; const double P2_N = 2.0*M_PI/(double)ndft; double *IDFT; IDFT = (double *)aligned_alloc(sizeof(double),2u*NN*sizeof(double)); if (!IDFT) { fprintf(stderr,"error in idft_cblas_d: problem with aligned_alloc. "); perror("aligned_alloc"); return 1; } for (size_t l=0u; l<ndft; ++l) { *IDFT++ = s; *IDFT++ = 0.0; } for (size_t n=1u; n<ndft; ++n) { for (size_t l=0u; l<ndft; ++l) { *IDFT++ = s * cos(P2_N*(double)n*(double)l); *IDFT++ = s * sin(P2_N*(double)n*(double)l); } } IDFT -= 2u*NN; //Init complex matrix multiply const double z[2] = {0.0f,0.0f}, o[2] = {1.0f,0.0f}; double *Xc, *Yc; Xc = (double *)aligned_alloc(sizeof(double),2u*ndft*sizeof(double)); Yc = (double *)aligned_alloc(sizeof(double),2u*ndft*sizeof(double)); if (!Xc) { fprintf(stderr,"error in idft_cblas_d: problem with aligned_alloc. "); perror("aligned_alloc"); return 1; } if (!Yc) { fprintf(stderr,"error in idft_cblas_d: problem with aligned_alloc. "); perror("aligned_alloc"); return 1; } for (size_t n=0u; n<2u*ndft; ++n, ++Xc) { *Xc = 0.0; } Xc -= 2u*ndft; if (Lx==N) { //Copy into Xc for (size_t nf=Lx; nf>0u; --nf) { *Xc++ = *X++; *Xc++ = *X++; } if (ndft%2u==0u) { X -= 2; } for (size_t nf=ndft-ndft/2u; nf>1u; --nf) { X-=2; *Xc++ = *X; *Xc++ = -*(X+1); } Xc -= 2u*ndft; //Matrix multiply cblas_zgemv(CblasRowMajor,CblasNoTrans,(int)ndft,(int)ndft,o,IDFT,(int)ndft,Xc,1,z,Yc,1); //Output real part only cblas_dcopy((int)ndft,Yc,2,Y,1); } else { const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u); const size_t B = (iscolmajor && dim==0u) ? C*S*H : K; const size_t V = N/Lx, G = V/B; if (K==1u && (G==1u || B==1u)) { for (size_t v=0u; v<V; ++v, Y+=ndft) { //Copy into Xc for (size_t nf=Lx; nf>0u; --nf) { *Xc++ = *X++; *Xc++ = *X++; } if (ndft%2u==0u) { X -= 2; } for (size_t nf=ndft-ndft/2u; nf>1u; --nf) { X-=2; *Xc++ = *X; *Xc++ = -*(X+1); } Xc -= 2u*ndft; X += 2u*(ndft-ndft/2u-ndft%2u); //Matrix multiply cblas_zgemv(CblasRowMajor,CblasNoTrans,(int)ndft,(int)ndft,o,IDFT,(int)ndft,Xc,1,z,Yc,1); //Output real part only cblas_dcopy((int)ndft,Yc,2,Y,1); } } else { for (size_t g=G; g>0u; --g, X+=2u*B*(Lx-1u), Y+=B*(ndft-1u)) { for (size_t b=B; b>0u; --b, X+=2u*K*(ndft-ndft/2u-ndft%2u-Lx)+2u, ++Y) { //Copy into Xc for (size_t nf=Lx; nf>0u; --nf, X+=2u*K) { *Xc++ = *X; *Xc++ = *(X+1); } if (ndft%2u==0u) { X -= 2u*K; } for (size_t nf=ndft-ndft/2u; nf>1u; --nf) { X-=2u*K; *Xc++ = *X; *Xc++ = -*(X+1); } Xc -= 2u*ndft; //Matrix multiply cblas_zgemv(CblasRowMajor,CblasNoTrans,(int)ndft,(int)ndft,o,IDFT,(int)ndft,Xc,1,z,Yc,1); //Output real part only cblas_dcopy((int)ndft,Yc,2,Y,(int)K); } } } } free(IDFT); free(Xc); free(Yc); } return 0; } int idft_cblas_c (float *Y, const float *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const size_t ndft, const int sc) { if (dim>3u) { fprintf(stderr,"error in idft_cblas_c: dim must be in [0 3]\n"); return 1; } const size_t N = R*C*S*H; const size_t Lx = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H; if (ndft<Lx) { fprintf(stderr,"error in idft_cblas_c: ndft must be >= Lx (length of vecs in X)\n"); return 1; } //Scaling const float s = sc ? 2.0f*sqrtf(0.5f*(float)ndft)/(float)ndft : 1.0f/(float)ndft; if (N==0u || ndft==0u) {} else if (ndft==1u) { for (size_t n=2u*N; n>0u; --n, ++X, ++Y) { *Y = *X * s; } } else { //Init IDFT matrix const size_t LN = Lx * ndft; const float P2_N = (float)(2.0*M_PI/(double)ndft); float *IDFT; IDFT = (float *)aligned_alloc(sizeof(float),2u*LN*sizeof(float)); if (!IDFT) { fprintf(stderr,"error in idft_cblas_c: problem with aligned_alloc. "); perror("aligned_alloc"); return 1; } for (size_t l=0u; l<Lx; ++l) { *IDFT++ = s; *IDFT++ = 0.0f; } for (size_t n=1u; n<ndft; ++n) { for (size_t l=0u; l<Lx; ++l) { *IDFT++ = s * cosf(P2_N*(float)n*(float)l); *IDFT++ = s * sinf(P2_N*(float)n*(float)l); } } IDFT -= 2u*LN; //Init complex matrix multiply const float z[2] = {0.0f,0.0f}, o[2] = {1.0f,0.0f}; if (Lx==N) { //Matrix multiply cblas_cgemv(CblasRowMajor,CblasNoTrans,(int)ndft,(int)Lx,o,IDFT,(int)Lx,X,1,z,Y,1); } else { const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u); const size_t B = (iscolmajor && dim==0u) ? C*S*H : K; const size_t V = N/Lx, G = V/B; if (K==1u && (G==1u || B==1u)) { for (size_t v=0u; v<V; ++v, Y+=2u*ndft) { //Matrix multiply cblas_cgemv(CblasRowMajor,CblasNoTrans,(int)ndft,(int)Lx,o,IDFT,(int)Lx,X,1,z,Y,1); } } else { for (size_t g=G; g>0u; --g, X+=2u*B*(Lx-1u), Y+=2u*B*(ndft-1u)) { for (size_t b=B; b>0u; --b, X+=2, Y+=2) { //Matrix multiply cblas_cgemv(CblasRowMajor,CblasNoTrans,(int)ndft,(int)Lx,o,IDFT,(int)Lx,X,(int)K,z,Y,(int)K); } } } } free(IDFT); } return 0; } int idft_cblas_z (double *Y, const double *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const size_t ndft, const int sc) { if (dim>3u) { fprintf(stderr,"error in idft_cblas_z: dim must be in [0 3]\n"); return 1; } const size_t N = R*C*S*H; const size_t Lx = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H; if (ndft<Lx) { fprintf(stderr,"error in idft_cblas_z: ndft must be >= Lx (length of vecs in X)\n"); return 1; } //Scaling const double s = sc ? 2.0*sqrt(0.5*(double)ndft)/(double)ndft : 1.0/(double)ndft; if (N==0u || ndft==0u) {} else if (ndft==1u) { for (size_t n=2u*N; n>0u; --n, ++X, ++Y) { *Y = *X * s; } } else { //Init IDFT matrix const size_t LN = Lx * ndft; const double P2_N = 2.0*M_PI/(double)ndft; double *IDFT; IDFT = (double *)aligned_alloc(sizeof(double),2u*LN*sizeof(double)); if (!IDFT) { fprintf(stderr,"error in idft_cblas_z: problem with aligned_alloc. "); perror("aligned_alloc"); return 1; } for (size_t l=0u; l<Lx; ++l) { *IDFT++ = s; *IDFT++ = 0.0; } for (size_t n=1u; n<ndft; ++n) { for (size_t l=0u; l<Lx; ++l) { *IDFT++ = s * cos(P2_N*(double)n*(double)l); *IDFT++ = s * sin(P2_N*(double)n*(double)l); } } IDFT -= 2u*LN; //Init complex matrix multiply const double z[2] = {0.0,0.0}, o[2] = {1.0,0.0}; if (Lx==N) { //Matrix multiply cblas_zgemv(CblasRowMajor,CblasNoTrans,(int)ndft,(int)Lx,o,IDFT,(int)Lx,X,1,z,Y,1); } else { const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u); const size_t B = (iscolmajor && dim==0u) ? C*S*H : K; const size_t V = N/Lx, G = V/B; if (K==1u && (G==1u || B==1u)) { for (size_t v=0u; v<V; ++v, Y+=2u*ndft) { //Matrix multiply cblas_zgemv(CblasRowMajor,CblasNoTrans,(int)ndft,(int)Lx,o,IDFT,(int)Lx,X,1,z,Y,1); } } else { for (size_t g=G; g>0u; --g, X+=2u*B*(Lx-1u), Y+=2u*B*(ndft-1u)) { for (size_t b=B; b>0u; --b, X+=2, Y+=2) { //Matrix multiply cblas_zgemv(CblasRowMajor,CblasNoTrans,(int)ndft,(int)Lx,o,IDFT,(int)Lx,X,(int)K,z,Y,(int)K); } } } } free(IDFT); } return 0; } #ifdef __cplusplus } } #endif
{ "alphanum_fraction": 0.481221374, "avg_line_length": 39.9390243902, "ext": "c", "hexsha": "e2aa546df06a4b39222fe55c69b41f3532f2f8a1", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-10-05T13:50:32.000Z", "max_forks_repo_forks_event_min_datetime": "2021-10-05T13:50:32.000Z", "max_forks_repo_head_hexsha": "28880ede8ca715c2a5a9b596742070f9bda9830e", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "erikedwards4/dsp", "max_forks_repo_path": "c/idft.cblas.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "28880ede8ca715c2a5a9b596742070f9bda9830e", "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/dsp", "max_issues_repo_path": "c/idft.cblas.c", "max_line_length": 183, "max_stars_count": 1, "max_stars_repo_head_hexsha": "28880ede8ca715c2a5a9b596742070f9bda9830e", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "erikedwards4/dsp", "max_stars_repo_path": "c/idft.cblas.c", "max_stars_repo_stars_event_max_datetime": "2020-08-26T09:22:40.000Z", "max_stars_repo_stars_event_min_datetime": "2020-08-26T09:22:40.000Z", "num_tokens": 5714, "size": 16375 }
#ifndef RENDERING_ENTITY_STEREO_VIEWERCENTRICENTITY_H #define RENDERING_ENTITY_STEREO_VIEWERCENTRICENTITY_H #include "stereoimageentity.h" #include <gsl/gsl> class QPaintEvent; class QPainter; namespace s3d { struct ViewerContext; } // namespace s3d class ViewerCentricEntity : public StereoImageEntity { public: ViewerCentricEntity(); void init() override; void setHorizontalShift(float shift) override; void setAspectRatio(float ratio) override; void setTextureLeft(QOpenGLTexture* texture) override; void setTextureRight(QOpenGLTexture* texture) override; void setViewerContext(gsl::not_null<s3d::ViewerContext*> viewerContext); void setDepthRangeMeters(float min, float max); void setDisplayZoom(float displayZoom); void draw(QPaintDevice* paintDevice) override; QPoint worldToWidget(QPointF pos, int deviceWidth, int deviceHeight); float worldYToWidgetX(float y, int deviceWidth, int deviceHeight); float worldZToWidgetY(float z, int deviceHeight); float getPixelToWorldRatio(float deviceHeight); private: void drawScreen(QPainter* painter); void drawViewer(QPainter* painter); private: s3d::ViewerContext* m_viewerContext{}; float m_displayZoom{1.0f}; float m_minZ{-1.0f}; float m_maxZ{3.0f}; }; #endif // RENDERING_ENTITY_STEREO_VIEWERCENTRICENTITY_H
{ "alphanum_fraction": 0.791634981, "avg_line_length": 27.3958333333, "ext": "h", "hexsha": "98283f4490dfd22f6e5397807bdd23de440d29a4", "lang": "C", "max_forks_count": 6, "max_forks_repo_forks_event_max_datetime": "2021-05-18T16:22:03.000Z", "max_forks_repo_forks_event_min_datetime": "2017-07-13T21:51:09.000Z", "max_forks_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "hugbed/OpenS3D", "max_forks_repo_path": "src/apps/S3DAnalyzer/rendering/entity/stereo/viewercentricentity.h", "max_issues_count": 40, "max_issues_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_issues_repo_issues_event_max_datetime": "2017-12-21T18:41:23.000Z", "max_issues_repo_issues_event_min_datetime": "2017-04-12T17:24:44.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "hugbed/OpenS3D", "max_issues_repo_path": "src/apps/S3DAnalyzer/rendering/entity/stereo/viewercentricentity.h", "max_line_length": 74, "max_stars_count": 8, "max_stars_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "hugbed/OpenS3D", "max_stars_repo_path": "src/apps/S3DAnalyzer/rendering/entity/stereo/viewercentricentity.h", "max_stars_repo_stars_event_max_datetime": "2020-04-20T03:23:15.000Z", "max_stars_repo_stars_event_min_datetime": "2017-04-16T16:38:15.000Z", "num_tokens": 335, "size": 1315 }
#include <stdio.h> #include <string.h> #include <gsl/gsl_statistics_double.h> #include "tz_error.h" #include "tz_constant.h" #include "tz_image_lib.h" #include "tz_objdetect.h" #include "tz_imatrix.h" #include "tz_stack_math.h" #include "tz_stack_bwdist.h" #include "tz_stack_bwmorph.h" #include "tz_voxel_linked_list.h" #include "tz_stack_sampling.h" #include "tz_stack_draw.h" #include "tz_voxel_graphics.h" INIT_EXCEPTION_MAIN(e) int main(int argc, char* argv[]) { char neuron_name[100]; if (argc == 1) { strcpy(neuron_name, "fly_neuron"); } else { strcpy(neuron_name, argv[1]); } char file_path[100]; sprintf(file_path, "../data/%s.tif", neuron_name); Stack *canvas = Read_Stack(file_path); Translate_Stack(canvas, COLOR, 1); Print_Stack_Info(canvas); sprintf(file_path, "../data/%s/grow_bundle.tif", neuron_name); Stack *bundle = Read_Stack(file_path); Stack *bundle_boundary = Stack_Perimeter(bundle, NULL, 4); Kill_Stack(bundle); sprintf(file_path, "../data/%s/bundle_seed.tif", neuron_name); Stack *seed = Read_Stack(file_path); Rgb_Color color; Set_Color(&color, 0, 255, 0); Stack_Label_Bwc(canvas, bundle_boundary, color); Set_Color(&color, 255, 0, 0); Stack_Label_Bwc(canvas, seed, color); sprintf(file_path, "../data/%s/bundle_label.tif", neuron_name); Write_Stack(file_path, canvas); Kill_Stack(canvas); Kill_Stack(bundle_boundary); Kill_Stack(seed); return 0; }
{ "alphanum_fraction": 0.7165517241, "avg_line_length": 24.5762711864, "ext": "c", "hexsha": "c2612307588d451a49b2cca5d6c834bc41926c95", "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": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzhmark/vaa3d_tools", "max_forks_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/fly_neuron_bundle_label.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_issues_repo_issues_event_max_datetime": "2016-12-03T05:33:13.000Z", "max_issues_repo_issues_event_min_datetime": "2016-12-03T05:33:13.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzhmark/vaa3d_tools", "max_issues_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/fly_neuron_bundle_label.c", "max_line_length": 65, "max_stars_count": 1, "max_stars_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zzhmark/vaa3d_tools", "max_stars_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/fly_neuron_bundle_label.c", "max_stars_repo_stars_event_max_datetime": "2021-12-27T19:14:03.000Z", "max_stars_repo_stars_event_min_datetime": "2021-12-27T19:14:03.000Z", "num_tokens": 407, "size": 1450 }
/* permutation/gsl_permutation.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2004, 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. */ #ifndef __GSL_PERMUTATION_H__ #define __GSL_PERMUTATION_H__ #include <stdlib.h> #include <gsl/gsl_types.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_inline.h> #include <gsl/gsl_check_range.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 struct gsl_permutation_struct { size_t size; size_t *data; }; typedef struct gsl_permutation_struct gsl_permutation; gsl_permutation *gsl_permutation_alloc (const size_t n); gsl_permutation *gsl_permutation_calloc (const size_t n); void gsl_permutation_init (gsl_permutation * p); void gsl_permutation_free (gsl_permutation * p); int gsl_permutation_memcpy (gsl_permutation * dest, const gsl_permutation * src); int gsl_permutation_fread (FILE * stream, gsl_permutation * p); int gsl_permutation_fwrite (FILE * stream, const gsl_permutation * p); int gsl_permutation_fscanf (FILE * stream, gsl_permutation * p); int gsl_permutation_fprintf (FILE * stream, const gsl_permutation * p, const char *format); size_t gsl_permutation_size (const gsl_permutation * p); size_t * gsl_permutation_data (const gsl_permutation * p); int gsl_permutation_swap (gsl_permutation * p, const size_t i, const size_t j); int gsl_permutation_valid (const gsl_permutation * p); void gsl_permutation_reverse (gsl_permutation * p); int gsl_permutation_inverse (gsl_permutation * inv, const gsl_permutation * p); int gsl_permutation_next (gsl_permutation * p); int gsl_permutation_prev (gsl_permutation * p); int gsl_permutation_mul (gsl_permutation * p, const gsl_permutation * pa, const gsl_permutation * pb); int gsl_permutation_linear_to_canonical (gsl_permutation * q, const gsl_permutation * p); int gsl_permutation_canonical_to_linear (gsl_permutation * p, const gsl_permutation * q); size_t gsl_permutation_inversions (const gsl_permutation * p); size_t gsl_permutation_linear_cycles (const gsl_permutation * p); size_t gsl_permutation_canonical_cycles (const gsl_permutation * q); INLINE_DECL size_t gsl_permutation_get (const gsl_permutation * p, const size_t i); #ifdef HAVE_INLINE INLINE_FUN size_t gsl_permutation_get (const gsl_permutation * p, const size_t i) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(i >= p->size)) { GSL_ERROR_VAL ("index out of range", GSL_EINVAL, 0); } #endif return p->data[i]; } #endif /* HAVE_INLINE */ __END_DECLS #endif /* __GSL_PERMUTATION_H__ */
{ "alphanum_fraction": 0.7752540347, "avg_line_length": 33.1287128713, "ext": "h", "hexsha": "10ac0f58a2e1d962f1ef62e5a6c65f15aef9d683", "lang": "C", "max_forks_count": 173, "max_forks_repo_forks_event_max_datetime": "2022-03-27T07:27:04.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-08T18:01:54.000Z", "max_forks_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_forks_repo_licenses": [ "Net-SNMP", "Xnet" ], "max_forks_repo_name": "juandesant/astrometry.net", "max_forks_repo_path": "gsl-an/gsl/gsl_permutation.h", "max_issues_count": 208, "max_issues_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_issues_repo_issues_event_max_datetime": "2022-03-25T15:21:34.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-08T20:26:38.000Z", "max_issues_repo_licenses": [ "Net-SNMP", "Xnet" ], "max_issues_repo_name": "juandesant/astrometry.net", "max_issues_repo_path": "gsl-an/gsl/gsl_permutation.h", "max_line_length": 102, "max_stars_count": 460, "max_stars_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_stars_repo_licenses": [ "Net-SNMP", "Xnet" ], "max_stars_repo_name": "juandesant/astrometry.net", "max_stars_repo_path": "gsl-an/gsl/gsl_permutation.h", "max_stars_repo_stars_event_max_datetime": "2022-03-29T00:37:55.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-06T13:20:04.000Z", "num_tokens": 875, "size": 3346 }
#pragma once #include <filesystem> #include <unordered_map> #include <optional> #include <variant> #include <string> #include <vector> #include <gsl/gsl> #include <DirectML.h> #include "BucketAllocator.h" class Model { public: // When binding a buffer to an operator it is possible to use a subregion of // the buffer by specifying an elementOffset, elementCount, and elementSizeInBytes. // Additionally, an optional format specifier dictates how to interpret the buffer // contents; when omitted the buffer will be interpreted using the same data type used // to initialize it. struct BufferBindingSource { std::string name; uint64_t elementCount; uint64_t elementSizeInBytes; uint64_t elementOffset; std::optional<DXGI_FORMAT> format; // For Append/Consume buffers only: std::optional<std::string> counterName; uint64_t counterOffsetBytes; }; using Bindings = std::unordered_map<std::string, std::vector<BufferBindingSource>>; // RESOURCES // ------------------------------------------------------------------------ struct BufferDesc { uint64_t sizeInBytes; std::vector<std::byte> initialValues; DML_TENSOR_DATA_TYPE initialValuesDataType; uint64_t initialValuesOffsetInBytes; }; struct ResourceDesc { std::string name; std::variant<BufferDesc> value; }; // DISPATCHABLES // ------------------------------------------------------------------------ struct DmlDispatchableDesc { struct BindPoint { std::string name; uint32_t resourceCount; bool required; }; struct BindPoints { std::vector<BindPoint> inputs; std::vector<BindPoint> outputs; }; DML_OPERATOR_DESC* desc; BindPoints bindPoints; DML_EXECUTION_FLAGS executionFlags; Bindings initBindings; }; struct HlslDispatchableDesc { enum class Compiler { DXC }; std::filesystem::path sourcePath; Compiler compiler; std::vector<std::string> compilerArgs; }; struct DispatchableDesc { std::string name; std::variant<DmlDispatchableDesc, HlslDispatchableDesc> value; }; // COMMANDS // ------------------------------------------------------------------------ struct DispatchCommand { std::string dispatchableName; Bindings bindings; std::array<uint32_t, 3> threadGroupCount; }; struct PrintCommand { std::string resourceName; }; using Command = std::variant<DispatchCommand, PrintCommand>; Model() = default; Model( std::vector<ResourceDesc>&& resourceDescs, std::vector<DispatchableDesc>&& dispatchableDescs, std::vector<Command>&& commands, BucketAllocator&& allocator); Model(const Model&) = delete; Model& operator=(const Model&) = delete; Model(Model&&) = default; Model& operator=(Model&&) = default; gsl::span<const ResourceDesc> GetResourceDescs() const { return m_resourceDescs; } gsl::span<const DispatchableDesc> GetDispatchableDescs() const { return m_dispatchableDescs; } gsl::span<const Command> GetCommands() const { return m_commands; } const ResourceDesc& GetResource(std::string_view name) const { return *m_resourceDescsByName.find(name.data())->second; } const DispatchableDesc& GetDispatchable(std::string_view name) const { return *m_dispatchableDescsByName.find(name.data())->second; } private: std::vector<ResourceDesc> m_resourceDescs; std::vector<DispatchableDesc> m_dispatchableDescs; std::vector<Command> m_commands; BucketAllocator m_allocator; std::unordered_map<std::string, ResourceDesc*> m_resourceDescsByName; std::unordered_map<std::string, DispatchableDesc*> m_dispatchableDescsByName; };
{ "alphanum_fraction": 0.6215338496, "avg_line_length": 28.7985611511, "ext": "h", "hexsha": "bcba7ac3fabd72d1bfa7c9357ab8de4fd081d6cf", "lang": "C", "max_forks_count": 20, "max_forks_repo_forks_event_max_datetime": "2020-06-12T15:57:58.000Z", "max_forks_repo_forks_event_min_datetime": "2019-05-13T12:56:29.000Z", "max_forks_repo_head_hexsha": "d4657006a60a7b7d9baf17638c42aee27258c836", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "miaobin/DirectML", "max_forks_repo_path": "DxDispatch/src/model/Model.h", "max_issues_count": 4, "max_issues_repo_head_hexsha": "d4657006a60a7b7d9baf17638c42aee27258c836", "max_issues_repo_issues_event_max_datetime": "2020-06-09T01:51:06.000Z", "max_issues_repo_issues_event_min_datetime": "2019-05-10T09:12:59.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "miaobin/DirectML", "max_issues_repo_path": "DxDispatch/src/model/Model.h", "max_line_length": 137, "max_stars_count": 61, "max_stars_repo_head_hexsha": "d4657006a60a7b7d9baf17638c42aee27258c836", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "miaobin/DirectML", "max_stars_repo_path": "DxDispatch/src/model/Model.h", "max_stars_repo_stars_event_max_datetime": "2020-06-14T07:36:27.000Z", "max_stars_repo_stars_event_min_datetime": "2019-05-07T14:41:46.000Z", "num_tokens": 876, "size": 4003 }
/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~* ** ** ** This file forms part of the Underworld geophysics modelling application. ** ** ** ** For full license and copyright information, please refer to the LICENSE.md file ** ** located at the project root, or contact the authors. ** ** ** **~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/ #include <mpi.h> #include <StGermain/StGermain.h> #include <StgDomain/StgDomain.h> #include <StgFEM/StgFEM.h> #include "types.h" #include <petsc.h> #include <petscvec.h> #include <petscmat.h> #include <petscksp.h> #include <petscpc.h> #include <petscsnes.h> #include <petscis.h> #include <petscviewer.h> #include <petscsys.h> #include <petscversion.h> #if ( (PETSC_VERSION_MAJOR >= 3) && (PETSC_VERSION_MINOR >=3) ) #if (PETSC_VERSION_MINOR >=6) #include "petsc/private/kspimpl.h" #else #include "petsc-private/kspimpl.h" /*I "petscksp.h" I*/ #endif #else #include "private/kspimpl.h" /*I "petscksp.h" I*/ #endif //#include "ksptypes.h" #include "ksp-register.h" #include "StokesBlockKSPInterface.h" #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <string.h> /* Macro for checking number integrity - i.e. checks if number is infinite or "not a number" */ #define SBKSP_isGoodNumber( number ) ( (! isnan( number ) ) && ( ! isinf( number ) ) ) #define SBKSP_GetPetscMatrix( matrix ) ( (Mat)(matrix) ) #define SBKSP_GetPetscVector( vector ) ( (Vec)(vector) ) #define SBKSP_GetPetscKSP( solver ) ( (KSP)(solver) ) PetscErrorCode _BlockSolve( void* solver, void* _stokesSLE ); const Type StokesBlockKSPInterface_Type = "StokesBlockKSPInterface"; void* _StokesBlockKSPInterface_DefaultNew( Name name ) { SizeT _sizeOfSelf = sizeof(StokesBlockKSPInterface); Type type = StokesBlockKSPInterface_Type; Stg_Class_DeleteFunction* _delete = _SLE_Solver_Delete; Stg_Class_PrintFunction* _print = _SLE_Solver_Print; Stg_Class_CopyFunction* _copy = _SLE_Solver_Copy; Stg_Component_BuildFunction* _build = _StokesBlockKSPInterface_Build; Stg_Component_InitialiseFunction* _initialise = _StokesBlockKSPInterface_Initialise; Stg_Component_ExecuteFunction* _execute = _SLE_Solver_Execute; Stg_Component_DestroyFunction* _destroy = _SLE_Solver_Destroy; SLE_Solver_GetResidualFunc* _getResidual = NULL; Stg_Component_DefaultConstructorFunction* _defaultConstructor = _StokesBlockKSPInterface_DefaultNew; Stg_Component_ConstructFunction* _construct = _StokesBlockKSPInterface_AssignFromXML; SLE_Solver_SolverSetupFunction* _solverSetup = _StokesBlockKSPInterface_SolverSetup; SLE_Solver_SolveFunction* _solve = _StokesBlockKSPInterface_Solve; AllocationType nameAllocationType = NON_GLOBAL /* default value NON_GLOBAL */; return (void*) _StokesBlockKSPInterface_New( STOKESBLOCKKSPINTERFACE_PASSARGS ); } /* Creation implementation / Virtual constructor */ /* Set up function pointers */ StokesBlockKSPInterface* _StokesBlockKSPInterface_New( STOKESBLOCKKSPINTERFACE_DEFARGS ) { StokesBlockKSPInterface* self; /* Allocate memory */ assert( _sizeOfSelf >= sizeof(StokesBlockKSPInterface) ); self = (StokesBlockKSPInterface*) _SLE_Solver_New( SLE_SOLVER_PASSARGS ); /* Virtual info */ return self; } void _StokesBlockKSPInterface_Init( StokesBlockKSPInterface* self, StiffnessMatrix* preconditioner, Stokes_SLE * st_sle, PETScMGSolver * mg, Name filename, char * string, StiffnessMatrix* k2StiffMat, StiffnessMatrix* mStiffMat, ForceVector* f2ForceVec, ForceVector* jForceVec, double penaltyNumber, double hFactor, StiffnessMatrix* vmStiffMat, ForceVector* vmForceVec ) { self->preconditioner = preconditioner; self->st_sle = st_sle; self->mg = mg; self->optionsFile = filename; self->optionsString = string; self->k2StiffMat = k2StiffMat; self->f2ForceVec = f2ForceVec; self->penaltyNumber = penaltyNumber; self->hFactor = hFactor; self->mStiffMat = mStiffMat; self->jForceVec = jForceVec; self->vmStiffMat = vmStiffMat; self->vmForceVec = vmForceVec; /* add the vecs and matrices to the Base SLE class's dynamic lists, so they can be initialised and built properly */ /* if (k2StiffMat ) SystemLinearEquations_AddStiffnessMatrix( st_sle, k2StiffMat ); if (f2ForceVec ) SystemLinearEquations_AddForceVector( st_sle, f2ForceVec ); if (mStiffMat ) SystemLinearEquations_AddStiffnessMatrix( st_sle, mStiffMat ); if (jForceVec ) SystemLinearEquations_AddForceVector( st_sle, jForceVec ); if (vmStiffMat ) SystemLinearEquations_AddStiffnessMatrix( st_sle, vmStiffMat ); if (vmForceVec ) SystemLinearEquations_AddForceVector( st_sle, vmForceVec ); */ } void _StokesBlockKSPInterface_Build( void* solver, void* sle ) {/* it is the sle here being passed in*/ StokesBlockKSPInterface* self = (StokesBlockKSPInterface*)solver; Stream_IndentBranch( StgFEM_Debug ); /* Build Preconditioner */ if ( self->preconditioner ) { Stg_Component_Build( self->preconditioner, sle, False ); SystemLinearEquations_AddStiffnessMatrix( self->st_sle, self->preconditioner ); } if( self->mg ){ Stg_Component_Build( self->mg, sle, False ); } Stream_UnIndentBranch( StgFEM_Debug ); } void _StokesBlockKSPInterface_AssignFromXML( void* solver, Stg_ComponentFactory* cf, void* data ) { StokesBlockKSPInterface* self = (StokesBlockKSPInterface*) solver; //double tolerance; //Iteration_Index maxUzawaIterations, minUzawaIterations; StiffnessMatrix* preconditioner; StiffnessMatrix* k2StiffMat; ForceVector* f2ForceVec; StiffnessMatrix* mStiffMat; ForceVector* jForceVec; double penaltyNumber; double hFactor; StiffnessMatrix* vmStiffMat; ForceVector* vmForceVec; //Bool useAbsoluteTolerance; //Bool monitor; Stokes_SLE * st_sle; PETScMGSolver * mg; //Name filename; //char* string; _SLE_Solver_AssignFromXML( self, cf, data ); preconditioner = Stg_ComponentFactory_ConstructByKey( cf, self->name, (Dictionary_Entry_Key)"Preconditioner", StiffnessMatrix, False, data ); st_sle = Stg_ComponentFactory_ConstructByKey( cf, self->name, (Dictionary_Entry_Key)"stokesEqn", Stokes_SLE, True, data ); mg = Stg_ComponentFactory_ConstructByKey( cf, self->name, (Dictionary_Entry_Key)"mgSolver", PETScMGSolver, False, data); k2StiffMat = Stg_ComponentFactory_ConstructByKey( cf, self->name, (Dictionary_Entry_Key)"2ndStressTensorMatrix", StiffnessMatrix, False, data ); f2ForceVec = Stg_ComponentFactory_ConstructByKey( cf, self->name, (Dictionary_Entry_Key)"2ndForceVector", ForceVector, False, data ); penaltyNumber = Stg_ComponentFactory_GetDouble( cf, self->name, (Dictionary_Entry_Key)"penaltyNumber", 0.0 ); hFactor = Stg_ComponentFactory_GetDouble( cf, self->name, (Dictionary_Entry_Key)"hFactor", 0.0 ); mStiffMat = Stg_ComponentFactory_ConstructByKey( cf, self->name, (Dictionary_Entry_Key)"MassMatrix", StiffnessMatrix, False, data ); jForceVec = Stg_ComponentFactory_ConstructByKey( cf, self->name, (Dictionary_Entry_Key)"JunkForceVector", ForceVector, False, data ); vmStiffMat = Stg_ComponentFactory_ConstructByKey( cf, self->name, (Dictionary_Entry_Key)"VelocityMassMatrix", StiffnessMatrix, False, data ); vmForceVec = Stg_ComponentFactory_ConstructByKey( cf, self->name, (Dictionary_Entry_Key)"VMassForceVector", ForceVector, False, data ); _StokesBlockKSPInterface_Init( self, preconditioner, st_sle, mg, NULL, NULL, k2StiffMat, mStiffMat, f2ForceVec, jForceVec, penaltyNumber, hFactor, vmStiffMat, vmForceVec); } void _StokesBlockKSPInterface_Initialise( void* solver, void* data ) { StokesBlockKSPInterface* self = (StokesBlockKSPInterface*) solver; Stokes_SLE* sle = (Stokes_SLE*) self->st_sle; /* Initialise Parent */ _SLE_Solver_Initialise( self, sle ); KSPRegisterAllKSP("Solvers/KSPSolvers/src"); } /* SolverSetup */ void _StokesBlockKSPInterface_SolverSetup( void* solver, void* stokesSLE ) { StokesBlockKSPInterface* self = (StokesBlockKSPInterface*) solver; //Stokes_SLE* sle = (Stokes_SLE*) stokesSLE; Journal_DPrintf( self->debug, "In %s:\n", __func__ ); Stream_IndentBranch( StgFEM_Debug ); Stream_UnIndentBranch( StgFEM_Debug ); } void SBKSP_SetSolver( void* solver, void* stokesSLE ) { SLE_Solver* self = (SLE_Solver*) solver; Stokes_SLE* sle = (Stokes_SLE*) stokesSLE; sle->solver=self; } void SBKSP_SetPenalty( void* solver, double penalty ) { StokesBlockKSPInterface* self = (StokesBlockKSPInterface*) solver; self->penaltyNumber=penalty; } int SBKSP_GetPressureIts(void *solver){ StokesBlockKSPInterface* self = (StokesBlockKSPInterface*) solver; return self->stats.pressure_its; } /***********************************************************************************************************/ /***********************************************************************************************************/ /***********************************************************************************************************/ void SBKSP_GetStokesOperators( Stokes_SLE *stokesSLE, Mat *K,Mat *G,Mat *D,Mat *C,Mat *approxS, Vec *f,Vec *h,Vec *u,Vec *p ) { *K = *G = *D = *C = PETSC_NULL; if (stokesSLE->kStiffMat){ *K = SBKSP_GetPetscMatrix( stokesSLE->kStiffMat->matrix ); } if (stokesSLE->gStiffMat){ *G = SBKSP_GetPetscMatrix( stokesSLE->gStiffMat->matrix ); } if (stokesSLE->dStiffMat){ *D = SBKSP_GetPetscMatrix( stokesSLE->dStiffMat->matrix ); } if (stokesSLE->cStiffMat){ *C = SBKSP_GetPetscMatrix( stokesSLE->cStiffMat->matrix ); } /* preconditioner */ *approxS = PETSC_NULL; if( ((StokesBlockKSPInterface*)stokesSLE->solver)->preconditioner ) { StiffnessMatrix *preconditioner; preconditioner = ((StokesBlockKSPInterface*)stokesSLE->solver)->preconditioner; *approxS = SBKSP_GetPetscMatrix( preconditioner->matrix ); } *f = *h = PETSC_NULL; if (stokesSLE->fForceVec){ *f = SBKSP_GetPetscVector( stokesSLE->fForceVec->vector ); } if (stokesSLE->hForceVec){ *h = SBKSP_GetPetscVector( stokesSLE->hForceVec->vector ); } *u = *p = PETSC_NULL; if (stokesSLE->uSolnVec){ *u = SBKSP_GetPetscVector( stokesSLE->uSolnVec->vector ); } if (stokesSLE->pSolnVec){ *p = SBKSP_GetPetscVector( stokesSLE->pSolnVec->vector ); } } /***********************************************************************************************************/ /***********************************************************************************************************/ /***********************************************************************************************************/ /* Sets up Solver to be a custom ksp (KSP_BSSCR) solve by default: */ void _StokesBlockKSPInterface_Solve( void* solver, void* _stokesSLE ) { StokesBlockKSPInterface* self = (StokesBlockKSPInterface*)solver; PetscLogDouble flopsA,flopsB; PetscTruth found, get_flops; found = PETSC_FALSE; get_flops = PETSC_FALSE; PetscOptionsGetTruth( PETSC_NULL, "-get_flops", &get_flops, &found); if(get_flops){ PetscGetFlops(&flopsA); } _BlockSolve(solver, _stokesSLE); if(get_flops){ PetscGetFlops(&flopsB); self->stats.total_flops=(double)(flopsB-flopsA); } } PetscErrorCode _BlockSolve( void* solver, void* _stokesSLE ) { Stokes_SLE* stokesSLE = (Stokes_SLE*)_stokesSLE; StokesBlockKSPInterface* Solver = (StokesBlockKSPInterface*)solver; /* Create shortcuts to stuff needed on sle */ Mat K; Mat G; Mat Gt; Mat D; Mat C; Mat approxS; Vec u; Vec p; Vec f; Vec h; Mat stokes_P; Mat stokes_A; Vec stokes_x; Vec stokes_b; Mat a[2][2]; Vec x[2]; Vec b[2]; KSP stokes_ksp; PC stokes_pc; PetscTruth sym,flg; PetscErrorCode ierr; PetscInt N,n; SBKSP_GetStokesOperators( stokesSLE, &K,&G,&D,&C, &approxS, &f,&h, &u,&p ); /* create Gt */ if( !D ) { ierr = MatTranspose( G, MAT_INITIAL_MATRIX, &Gt);CHKERRQ(ierr); sym = PETSC_TRUE; Solver->DIsSym = sym; } else { Gt = D; sym = PETSC_FALSE; Solver->DIsSym = sym; } flg=PETSC_FALSE; PetscOptionsHasName(PETSC_NULL,"-use_petsc_ksp",&flg); if (flg) { if( !C ) { /* Everything in this bracket, dependent on !C, is to build a matrix with diagonals of 0 for C the previous comment ways need a 'zero' matrix to keep fieldsplit happy in petsc? */ MatType mtype; Vec V; //MatGetSize( G, &M, &N ); VecGetSize(p, &N); VecGetLocalSize( p, &n ); MatCreate( PetscObjectComm((PetscObject) K), &C ); MatSetSizes( C, PETSC_DECIDE ,PETSC_DECIDE, N, N ); #if (((PETSC_VERSION_MAJOR==3) && (PETSC_VERSION_MINOR>=3)) || (PETSC_VERSION_MAJOR>3) ) MatSetUp(C); #endif MatGetType( G, &mtype ); MatSetType( C, mtype ); MatGetVecs( G, &V, PETSC_NULL ); VecSet(V, 0.0); //VecSet(h, 1.0); ierr = VecAssemblyBegin( V );CHKERRQ(ierr); ierr = VecAssemblyEnd ( V );CHKERRQ(ierr); ierr = MatDiagonalSet(C,V,INSERT_VALUES);CHKERRQ(ierr); ierr = MatAssemblyBegin( C, MAT_FINAL_ASSEMBLY );CHKERRQ(ierr); ierr = MatAssemblyEnd ( C, MAT_FINAL_ASSEMBLY );CHKERRQ(ierr); } } a[0][0]=K; a[0][1]=G; a[1][0]=Gt; a[1][1]=C; ierr = MatCreateNest(PetscObjectComm((PetscObject) K), 2, NULL, 2, NULL, (Mat *)a, &stokes_A);CHKERRQ(ierr); ierr = MatAssemblyBegin( stokes_A, MAT_FINAL_ASSEMBLY );CHKERRQ(ierr); ierr = MatAssemblyEnd( stokes_A, MAT_FINAL_ASSEMBLY );CHKERRQ(ierr); x[0]=u; x[1]=p; ierr = VecCreateNest(PetscObjectComm((PetscObject) u), 2, NULL, x, &stokes_x);CHKERRQ(ierr); ierr = VecAssemblyBegin( stokes_x );CHKERRQ(ierr); ierr = VecAssemblyEnd( stokes_x);CHKERRQ(ierr); b[0]=f; b[1]=h; ierr = VecCreateNest(PetscObjectComm((PetscObject) f), 2, NULL, b, &stokes_b);CHKERRQ(ierr); ierr = VecAssemblyBegin( stokes_b );CHKERRQ(ierr); ierr = VecAssemblyEnd( stokes_b);CHKERRQ(ierr); /* if( approxS ) { */ /* a[0][0]=K; a[0][1]=G; */ /* a[1][0]=NULL; a[1][1]=approxS; */ /* ierr = MatCreateNest(PetscObjectComm((PetscObject) K), 2, NULL, 2, NULL, (Mat *)a, &stokes_P);CHKERRQ(ierr); */ /* ierr = MatAssemblyBegin( stokes_P, MAT_FINAL_ASSEMBLY );CHKERRQ(ierr); */ /* ierr = MatAssemblyEnd( stokes_P, MAT_FINAL_ASSEMBLY );CHKERRQ(ierr); */ /* } */ /* else { */ stokes_P = stokes_A; /* } */ /* probably should make a Destroy function for these two */ /* Update options from file and/or string here so we can change things on the fly */ //PetscOptionsInsertFile(PETSC_COMM_WORLD, Solver->optionsFile, PETSC_FALSE); //PetscOptionsInsertString(Solver->optionsString); ierr = KSPCreate( PETSC_COMM_WORLD, &stokes_ksp );CHKERRQ(ierr); Stg_KSPSetOperators( stokes_ksp, stokes_A, stokes_P, SAME_NONZERO_PATTERN ); ierr = KSPSetType( stokes_ksp, "bsscr" );/* i.e. making this the default solver : calls KSPCreate_XXX */CHKERRQ(ierr); ierr = KSPGetPC( stokes_ksp, &stokes_pc );CHKERRQ(ierr); ierr = PCSetType( stokes_pc, PCNONE );CHKERRQ(ierr); ierr = KSPSetInitialGuessNonzero( stokes_ksp, PETSC_TRUE );CHKERRQ(ierr); ierr = KSPSetFromOptions( stokes_ksp );CHKERRQ(ierr); /* Doing this so the KSP Solver has access to the StgFEM Multigrid struct (PETScMGSolver). As well as any custom stuff on the Stokes_SLE struct */ if( stokes_ksp->data ){/* then ksp->data has been created in a KSpSetUp_XXX function */ /* testing for our KSP types that need the data that is on Solver... */ /* for the moment then, this function not completely agnostic about our KSPs */ //if(!strcmp("bsscr",stokes_ksp->type_name)){/* if is bsscr then set up the data on the ksp */ flg=PETSC_FALSE; PetscOptionsHasName(PETSC_NULL,"-use_petsc_ksp",&flg); if (!flg) { ((KSP_COMMON*)(stokes_ksp->data))->st_sle = Solver->st_sle; ((KSP_COMMON*)(stokes_ksp->data))->mg = Solver->mg; ((KSP_COMMON*)(stokes_ksp->data))->DIsSym = Solver->DIsSym; ((KSP_COMMON*)(stokes_ksp->data))->preconditioner = Solver->preconditioner; ((KSP_COMMON*)(stokes_ksp->data))->solver = Solver; } } ierr = KSPSolve( stokes_ksp, stokes_b, stokes_x );CHKERRQ(ierr); Stg_KSPDestroy(&stokes_ksp ); //if( ((StokesBlockKSPInterface*)stokesSLE->solver)->preconditioner ) if(stokes_P != stokes_A) { Stg_MatDestroy(&stokes_P ); } Stg_MatDestroy(&stokes_A ); Stg_VecDestroy(&stokes_x); Stg_VecDestroy(&stokes_b); if(!D){ Stg_MatDestroy(&Gt); } if(C && (stokesSLE->cStiffMat->matrix != C) ){ Stg_MatDestroy(&C); } PetscFunctionReturn(0); }
{ "alphanum_fraction": 0.6415072989, "avg_line_length": 39.8961625282, "ext": "c", "hexsha": "034ddd5c2e7beb43fdcab74784dced52da333612", "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": "27acbbbb70b00870bebc4f98c69af8edaa4f8bc4", "max_forks_repo_licenses": [ "CC-BY-4.0" ], "max_forks_repo_name": "StuartRClark/mantle", "max_forks_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/StokesBlockKSPInterface.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "27acbbbb70b00870bebc4f98c69af8edaa4f8bc4", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "CC-BY-4.0" ], "max_issues_repo_name": "StuartRClark/mantle", "max_issues_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/StokesBlockKSPInterface.c", "max_line_length": 146, "max_stars_count": 1, "max_stars_repo_head_hexsha": "27acbbbb70b00870bebc4f98c69af8edaa4f8bc4", "max_stars_repo_licenses": [ "CC-BY-4.0" ], "max_stars_repo_name": "StuartRClark/mantle", "max_stars_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/StokesBlockKSPInterface.c", "max_stars_repo_stars_event_max_datetime": "2022-01-28T20:00:12.000Z", "max_stars_repo_stars_event_min_datetime": "2022-01-28T20:00:12.000Z", "num_tokens": 5219, "size": 17674 }
/* Copyright [2021] [IBM Corporation] 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. */ #ifndef _MCAS_NUMA_NODE_MASK__H_ #define _MCAS_NUMA_NODE_MASK__H_ #include <numa.h> /* bitmask */ #include <common/string_view.h> #include <gsl/pointers> /* not_null */ #include <memory> /* unique_ptr */ struct numa_node_mask_dtor { void operator()(bitmask *b) { numa_free_nodemask(b); } }; struct numa_node_mask { numa_node_mask(common::string_view mask_) : _mask(std::unique_ptr<bitmask, numa_node_mask_dtor>(mask_not_null(std::string(mask_)))) { } numa_node_mask(const bitmask *b) : _mask(std::unique_ptr<bitmask, numa_node_mask_dtor>(numa_allocate_nodemask())) { copy_bitmask_to_bitmask(const_cast<bitmask *>(b), get()); } const bitmask *get() const { return _mask.get().get(); } bitmask *get() { return _mask.get().get(); } /* get first 64 bits in mask */ uint64_t get64() { uint64_t r = 0; for ( unsigned i = 0; i != 64; ++i ) { if ( numa_bitmask_isbitset(get(), i) ) { r |= ( 1U << i ); } } return r; } private: static bitmask *mask_not_null(common::string_view mask_) { auto m = numa_parse_nodestring(std::string(mask_).c_str()); return m ? m : numa_allocate_nodemask(); } gsl::not_null<std::unique_ptr<bitmask, numa_node_mask_dtor>> _mask; }; #endif
{ "alphanum_fraction": 0.7116564417, "avg_line_length": 28.4603174603, "ext": "h", "hexsha": "92e04091f76543998f6cb50d9967beb385c719db", "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": "f655d6e952577de11b52e2f4ab6f48c73ce5dba1", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "IBM/artemis", "max_forks_repo_path": "src/components/store/mapstore/src/numa_node_mask.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "f655d6e952577de11b52e2f4ab6f48c73ce5dba1", "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": "IBM/artemis", "max_issues_repo_path": "src/components/store/mapstore/src/numa_node_mask.h", "max_line_length": 91, "max_stars_count": null, "max_stars_repo_head_hexsha": "f655d6e952577de11b52e2f4ab6f48c73ce5dba1", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "IBM/artemis", "max_stars_repo_path": "src/components/store/mapstore/src/numa_node_mask.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 503, "size": 1793 }
/**************************************************************** * * Copyright (C) Max Planck Institute * for Biological Cybernetics, Tuebingen, Germany * * Author: Gabriele Lohmann, 2015 * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * *****************************************************************/ /* ** trial average using spline interpolation ** ** G.Lohmann, May 2014 */ #include <viaio/Vlib.h> #include <viaio/VImage.h> #include <viaio/mu.h> #include <viaio/option.h> #include <gsl/gsl_cblas.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_spline.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <math.h> #define ABS(x) ((x) > 0 ? (x) : -(x)) #define SQR(x) ((x)*(x)) #define LEN 10000 /* buffer length */ #define NTRIALS 10000 /* max number of trials */ typedef struct SpointStruct { VShort x; VShort y; VShort z; } SPoint; typedef struct TrialStruct { int id; float onset; float duration; float height; } Trial; Trial trial[NTRIALS]; int ntrials=0; int nevents=0; int test_ascii(int val) { if (val >= 'a' && val <= 'z') return 1; if (val >= 'A' && val <= 'Z') return 1; if (val >= '0' && val <= '9') return 1; if (val == ' ') return 1; if (val == '\0') return 1; if (val == '\n') return 1; if (val == '\r') return 1; if (val == '\t') return 1; if (val == '\v') return 1; return 0; } /* parse design file */ void ReadDesign(VString designfile) { FILE *fp=NULL; int i,j,k,id; char buf[LEN]; float onset=0,duration=0,height=0; fp = fopen(designfile,"r"); if (!fp) VError(" error opening design file %s",designfile); i = ntrials = nevents = 0; while (!feof(fp)) { for (j=0; j<LEN; j++) buf[j] = '\0'; if (fgets(buf,LEN,fp) == NULL) break; if (strlen(buf) < 2) continue; if (buf[0] == '%' || buf[0] == '#') continue; if (! test_ascii((int)buf[0])) VError(" input file must be a text file"); /* remove non-alphanumeric characters */ for (j=0; j<strlen(buf); j++) { k = (int)buf[j]; if (!isgraph(k) && buf[j] != '\n' && buf[j] != '\r' && buf[j] != '\0') { buf[j] = ' '; } if (buf[j] == '\v') buf[j] = ' '; /* remove tabs */ if (buf[j] == '\t') buf[j] = ' '; } if (sscanf(buf,"%d %f %f %f",&id,&onset,&duration,&height) != 4) VError(" line %d: illegal input format",i+1); if (duration < 0.5 && duration >= -0.0001) duration = 0.5; trial[i].id = id; trial[i].onset = onset; trial[i].duration = duration; trial[i].height = height; i++; if (i > NTRIALS) VError(" too many trials %d",i); if (id > nevents) nevents = id; } fclose(fp); ntrials = i; } int main (int argc,char *argv[]) { static VString designfile = ""; static VShort cond_id = 1; static VShort trial_id = 0; static VDouble temporal_resolution = 1.0; static VDouble start = 0; static VDouble length = 20; static VOptionDescRec options[] = { {"design", VStringRepn, 1, & designfile, VRequiredOpt, NULL,"Design file (ascii)" }, {"cond", VShortRepn, 1, & cond_id, VOptionalOpt, NULL,"Id of experimental condition"}, {"trial", VShortRepn, 1, & trial_id, VOptionalOpt, NULL,"Id of trial (starts at 0)"}, {"resolution", VDoubleRepn, 1, & temporal_resolution, VOptionalOpt, NULL," output temporal resolution in secs"}, {"start", VDoubleRepn, 1, & start, VOptionalOpt, NULL, "start relative to beginning of trial in secs"}, {"length", VDoubleRepn, 1, & length, VOptionalOpt, NULL, "trial length in seconds"}, }; FILE *in_file=NULL,*out_file=NULL; VAttrList list=NULL; VAttrListPosn posn; int i,j,k,slice,row,col; int nslices=0,nrows=0,ncols=0,ntimesteps=0; double t=0; char *prg = GetLipsiaName("vcuttrials"); fprintf (stderr, "%s\n", prg); /* parse command line */ VParseFilterCmd (VNumber (options),options,argc,argv,&in_file,&out_file); /* get image dimensions, read functional data */ if (! (list = VReadFile (in_file, NULL))) exit (1); fclose(in_file); nslices = 0; VImage tmp=NULL; for (VFirstAttr (list, & posn); VAttrExists (& posn); VNextAttr (& posn)) { if (VGetAttrRepn (& posn) != VImageRepn) continue; VGetAttrValue (& posn, NULL,VImageRepn, & tmp); /* if (VPixelRepn(tmp) != VShortRepn) continue; */ nslices++; } if (nslices < 1) VError(" no slices"); VAttrList geoinfo = VGetGeoInfo(list); VImage *src = (VImage *) VCalloc(nslices,sizeof(VImage)); i = ntimesteps = nrows = ncols = 0; for (VFirstAttr (list, & posn); VAttrExists (& posn); VNextAttr (& posn)) { if (VGetAttrRepn (& posn) != VImageRepn) continue; VGetAttrValue (& posn, NULL,VImageRepn, & src[i]); /* if (VPixelRepn(src[i]) != VShortRepn) continue; */ if (VImageNBands(src[i]) > ntimesteps) ntimesteps = VImageNBands(src[i]); if (VImageNRows(src[i]) > nrows) nrows = VImageNRows(src[i]); if (VImageNColumns(src[i]) > ncols) ncols = VImageNColumns(src[i]); i++; } fprintf(stderr," nslices: %d, nrows: %d, ncols: %d, ntimesteps: %d\n",nslices,nrows,ncols,ntimesteps); /* read repetition time */ double tr = 0; if (VGetAttr (VImageAttrList (src[0]), "repetition_time", NULL, VDoubleRepn, (VPointer) & tr) != VAttrFound) { VError(" attribute 'repetition_time' missing"); } tr /= 1000.0; double experiment_duration = tr * (double)ntimesteps; /* read design file */ ReadDesign(designfile); /* select trial id */ int tid=0,j0=-1; for (j=0; j<ntrials; j++) { if (trial[j].id == cond_id && tid == trial_id) { j0 = j; break; } if (trial[j].id == cond_id) tid++; } if (j0 < 0) VError("trial not found"); fprintf(stderr," trial onset: %f\n",trial[j0].onset); /* adjust start time */ trial[j0].onset += start; if (trial[j0].onset < 0) { VWarning(" negative onset, reset to zero"); trial[j0].onset = 0; } if (trial[j0].onset + length >= experiment_duration) { VWarning(" experiment_duration exceeded",experiment_duration); length = experiment_duration - trial[j0].onset-0.5; VWarning(" parameter '-length' set to %f\n",length); } int nt = (int)(length/temporal_resolution + 0.5); fprintf(stderr," number of output timesteps: %d\n",nt); /* ini output data structs */ VImage *dest = (VImage *) VCalloc(nslices, sizeof(VImage)); VAttrList out_list = VCreateAttrList(); if (geoinfo != NULL) VSetGeoInfo(geoinfo,out_list); for (slice=0; slice<nslices; slice++) { dest[slice] = VCreateImage(nt,nrows,ncols,VPixelRepn(src[slice])); VFillImage(dest[slice],VAllBands,0); VCopyImageAttrs (src[slice], dest[slice]); VAppendAttr(out_list,"image",NULL,VImageRepn,dest[slice]); } /* spline interpolation */ double tstep = temporal_resolution; double *xx = (double *) VCalloc(ntimesteps,sizeof(double)); double *yy = (double *) VCalloc(ntimesteps,sizeof(double)); gsl_interp_accel *acc = gsl_interp_accel_alloc (); gsl_spline *spline = gsl_spline_alloc (gsl_interp_cspline, ntimesteps); for (slice=0; slice<nslices; slice++) { for (row=0; row<nrows; row++) { for (col=0; col<ncols; col++) { for (k=0; k<ntimesteps; k++) { xx[k] = tr*((double)k); yy[k] = (double)VGetPixel(src[slice],k,row,col); } gsl_spline_init (spline, xx, yy, ntimesteps); k=0; for (t=0; t<length; t += tstep) { if (k >= nt) break; double xi = trial[j].onset + t; double yi = 0; if (xi < experiment_duration && xi >= 0) { if (gsl_spline_eval_e (spline,xi,acc,&yi) == GSL_EDOM) continue; } VSetPixel(dest[slice],k,row,col,yi); k++; } } } } /* write to disk */ if (! VWriteFile (out_file, out_list)) exit (1); fprintf (stderr, "%s: done.\n", argv[0]); exit(0); }
{ "alphanum_fraction": 0.6140433553, "avg_line_length": 29.3702422145, "ext": "c", "hexsha": "289e6fb4a614fe56693e715083c58df5bc9d5409", "lang": "C", "max_forks_count": 8, "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z", "max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z", "max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zrajna/lipsia", "max_forks_repo_path": "src/ted/vcuttrials/vcuttrials.c", "max_issues_count": 7, "max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z", "max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zrajna/lipsia", "max_issues_repo_path": "src/ted/vcuttrials/vcuttrials.c", "max_line_length": 116, "max_stars_count": 17, "max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zrajna/lipsia", "max_stars_repo_path": "src/ted/vcuttrials/vcuttrials.c", "max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z", "max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z", "num_tokens": 2678, "size": 8488 }
/* err/stream.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 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 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. */ #include <config.h> #include <stddef.h> #include <stdlib.h> #include <stdio.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_message.h> FILE * gsl_stream = NULL ; gsl_stream_handler_t * gsl_stream_handler = NULL; void gsl_stream_printf (const char *label, const char *file, int line, const char *reason) { if (gsl_stream == NULL) { gsl_stream = stderr; } if (gsl_stream_handler) { (*gsl_stream_handler) (label, file, line, reason); return; } fprintf (gsl_stream, "gsl: %s:%d: %s: %s\n", file, line, label, reason); } gsl_stream_handler_t * gsl_set_stream_handler (gsl_stream_handler_t * new_handler) { gsl_stream_handler_t * previous_handler = gsl_stream_handler; gsl_stream_handler = new_handler; return previous_handler; } FILE * gsl_set_stream (FILE * new_stream) { FILE * previous_stream; if (gsl_stream == NULL) { gsl_stream = stderr; } previous_stream = gsl_stream; gsl_stream = new_stream; return previous_stream; }
{ "alphanum_fraction": 0.7130144605, "avg_line_length": 26.8358208955, "ext": "c", "hexsha": "801c1c085d62efa6d54ed84b205877e3a921e99d", "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/err/stream.c", "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/err/stream.c", "max_line_length": 74, "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/err/stream.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": 473, "size": 1798 }
// 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. // Formatting library for C++ - the core API for char/UTF-8 // // Copyright (c) 2012 - present, Victor Zverovich // All rights reserved. // // For the license information refer to format.h. #include <gsl/gsl-lite.hpp> #include <units/bits/fmt_hacks.h> #include <concepts> #include <limits> #include <string_view> // most of the below code is based on/copied from libfmt namespace units::detail { struct auto_id {}; enum class fmt_align { none, left, right, center }; enum class fmt_sign { none, minus, plus, space }; enum class arg_id_kind { none, index, name }; template<typename Char> struct fill_t { private: static constexpr size_t max_size = 4 / sizeof(Char); // At most one codepoint (so one char32_t or four utf-8 char8_t) Char data_[max_size] = {Char{' '}}; unsigned char size_ = 1; public: constexpr void operator=(std::basic_string_view<Char> s) { auto size = s.size(); if (size > max_size) return throw STD_FMT::format_error("invalid fill"); for (size_t i = 0; i < size; ++i) data_[i] = s[i]; size_ = static_cast<unsigned char>(size); } [[nodiscard]] constexpr size_t size() const { return size_; } [[nodiscard]] constexpr const Char* data() const { return data_; } [[nodiscard]] constexpr Char& operator[](size_t index) { return data_[index]; } [[nodiscard]] constexpr const Char& operator[](size_t index) const { return data_[index]; } }; template<typename T> inline constexpr bool is_integer = std::is_integral<T>::value && !std::is_same<T, bool>::value && !std::is_same<T, char>::value && !std::is_same<T, wchar_t>::value; template<typename Char> [[nodiscard]] constexpr bool is_ascii_letter(Char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); } // Converts a character to ASCII. Returns a number > 127 on conversion failure. template<std::integral Char> [[nodiscard]] constexpr Char to_ascii(Char value) { return value; } template<typename Char> requires std::is_enum_v<Char> [[nodiscard]] constexpr auto to_ascii(Char value) -> std::underlying_type_t<Char> { return value; } struct width_checker { template<typename T> [[nodiscard]] constexpr unsigned long long operator()(T value) const { if constexpr (is_integer<T>) { if constexpr (std::numeric_limits<T>::is_signed) { if (value < 0) throw STD_FMT::format_error("negative width"); } return static_cast<unsigned long long>(value); } else { throw STD_FMT::format_error("width is not integer"); } } }; struct precision_checker { template<typename T> [[nodiscard]] constexpr unsigned long long operator()(T value) const { if constexpr (is_integer<T>) { if constexpr (std::numeric_limits<T>::is_signed) { if (value < 0) throw STD_FMT::format_error("negative precision"); } return static_cast<unsigned long long>(value); } else { throw STD_FMT::format_error("precision is not integer"); } } }; // Format specifiers for built-in and string types. template<typename Char> struct basic_format_specs { int width = 0; int precision = -1; char type = '\0'; fmt_align align : 4 = fmt_align::none; fmt_sign sign : 3 = fmt_sign::none; bool alt : 1 = false; // Alternate form ('#'). bool localized : 1 = false; fill_t<Char> fill; }; // Format specifiers with width and precision resolved at formatting rather // than parsing time to allow re-using the same parsed specifiers with // different sets of arguments (precompilation of format strings). template<typename Char> struct dynamic_format_specs : basic_format_specs<Char> { int dynamic_width_index = -1; int dynamic_precision_index = -1; }; [[nodiscard]] constexpr int verify_dynamic_arg_index_in_range(size_t idx) { if (idx > static_cast<size_t>(std::numeric_limits<int>::max())) { throw STD_FMT::format_error("Dynamic width or precision index too large."); } return static_cast<int>(idx); } template<typename CharT> [[nodiscard]] constexpr int on_dynamic_arg(size_t arg_id, STD_FMT::basic_format_parse_context<CharT>& context) { context.check_arg_id(FMT_TO_ARG_ID(arg_id)); return verify_dynamic_arg_index_in_range(arg_id); } template<typename CharT> [[nodiscard]] constexpr int on_dynamic_arg(auto_id, STD_FMT::basic_format_parse_context<CharT>& context) { return verify_dynamic_arg_index_in_range(FMT_FROM_ARG_ID(context.next_arg_id())); } template<class Handler, typename FormatContext> [[nodiscard]] constexpr int get_dynamic_spec(int index, FormatContext& ctx) { const unsigned long long value = STD_FMT::visit_format_arg(Handler{}, ctx.arg(FMT_TO_ARG_ID(static_cast<size_t>(index)))); if (value > static_cast<unsigned long long>(std::numeric_limits<int>::max())) { throw STD_FMT::format_error("number is too big"); } return static_cast<int>(value); } // Parses the range [begin, end) as an unsigned integer. This function assumes // that the range is non-empty and the first character is a digit. template<std::input_iterator It, std::sentinel_for<It> S> [[nodiscard]] constexpr It parse_nonnegative_int(It begin, S end, size_t& value) { gsl_Expects(begin != end && '0' <= *begin && *begin <= '9'); constexpr auto max_int = static_cast<unsigned>(std::numeric_limits<int>::max()); constexpr auto big_int = max_int / 10u; value = 0; do { if (value > big_int) { value = max_int + 1; break; } value = value * 10 + static_cast<unsigned int>(*begin - '0'); ++begin; } while (begin != end && '0' <= *begin && *begin <= '9'); if (value > max_int) throw STD_FMT::format_error("Number is too big"); return begin; } template<std::input_iterator It, std::sentinel_for<It> S> [[nodiscard]] constexpr It parse_nonnegative_int(It begin, S end, int& value) { size_t val_unsigned = 0; begin = parse_nonnegative_int(begin, end, val_unsigned); // Never invalid because parse_nonnegative_integer throws an error for values that don't fit in signed integers value = static_cast<int>(val_unsigned); return begin; } template<std::input_iterator It, std::sentinel_for<It> S, typename IDHandler> [[nodiscard]] constexpr It do_parse_arg_id(It begin, S end, IDHandler&& handler) { gsl_Expects(begin != end); auto c = *begin; if (c >= '0' && c <= '9') { size_t index = 0; if (c != '0') begin = parse_nonnegative_int(begin, end, index); else ++begin; if (begin == end || (*begin != '}' && *begin != ':')) throw STD_FMT::format_error("invalid format string"); else handler(index); return begin; } throw STD_FMT::format_error("invalid format string"); } template<std::input_iterator It, std::sentinel_for<It> S, typename IDHandler> [[nodiscard]] constexpr It parse_arg_id(It begin, S end, IDHandler&& handler) { auto c = *begin; if (c != '}' && c != ':') return do_parse_arg_id(begin, end, handler); handler(); return begin; } template<std::input_iterator It, std::sentinel_for<It> S, typename Handler> [[nodiscard]] constexpr It parse_sign(It begin, S end, Handler&& handler) { gsl_Expects(begin != end); switch (to_ascii(*begin)) { case '+': handler.on_sign(fmt_sign::plus); ++begin; break; case '-': handler.on_sign(fmt_sign::minus); ++begin; break; case ' ': handler.on_sign(fmt_sign::space); ++begin; break; default: break; } return begin; } template<std::input_iterator It, std::sentinel_for<It> S, typename Handler> [[nodiscard]] constexpr It parse_width(It begin, S end, Handler&& handler) { struct width_adapter { Handler& handler; constexpr void operator()() { handler.on_dynamic_width(auto_id{}); } constexpr void operator()(size_t id) { handler.on_dynamic_width(id); } }; gsl_Expects(begin != end); if ('0' <= *begin && *begin <= '9') { int width = 0; begin = parse_nonnegative_int(begin, end, width); if (width != -1) handler.on_width(width); else throw STD_FMT::format_error("number is too big"); } else if (*begin == '{') { ++begin; if (begin != end) begin = parse_arg_id(begin, end, width_adapter{handler}); if (begin == end || *begin != '}') throw STD_FMT::format_error("invalid format string"); ++begin; } return begin; } template<std::input_iterator It, std::sentinel_for<It> S, typename Handler> [[nodiscard]] constexpr It parse_precision(It begin, S end, Handler&& handler) { struct precision_adapter { Handler& handler; constexpr void operator()() { handler.on_dynamic_precision(auto_id{}); } constexpr void operator()(size_t id) { handler.on_dynamic_precision(id); } }; ++begin; auto c = begin != end ? *begin : std::iter_value_t<It>(); if ('0' <= c && c <= '9') { auto precision = 0; begin = parse_nonnegative_int(begin, end, precision); if (precision != -1) handler.on_precision(precision); else throw STD_FMT::format_error("number is too big"); } else if (c == '{') { ++begin; if (begin != end) begin = parse_arg_id(begin, end, precision_adapter{handler}); if (begin == end || *begin++ != '}') throw STD_FMT::format_error("invalid format string"); } else { throw STD_FMT::format_error("missing precision specifier"); } return begin; } template<std::input_iterator It> constexpr int code_point_length(It begin) { if constexpr (sizeof(std::iter_value_t<It>) != 1) return 1; constexpr char lengths[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0}; int len = lengths[static_cast<unsigned char>(*begin) >> 3]; // Compute the pointer to the next character early so that the next // iteration can start working on the next character. Neither Clang // nor GCC figure out this reordering on their own. return len + !len; } // Parses fill and alignment. template<std::input_iterator It, std::sentinel_for<It> S, typename Handler> [[nodiscard]] constexpr It parse_align(It begin, S end, Handler&& handler) { gsl_Expects(begin != end); auto align = fmt_align::none; auto p = begin + code_point_length(begin); if (p >= end) p = begin; for (;;) { switch (to_ascii(*p)) { case '<': align = fmt_align::left; break; case '>': align = fmt_align::right; break; case '^': align = fmt_align::center; break; default: break; } if (align != fmt_align::none) { if (p != begin) { auto c = *begin; if (c == '{') throw STD_FMT::format_error("invalid fill character '{'"); handler.on_fill(std::basic_string_view<std::iter_value_t<It>>(begin, static_cast<size_t>(p - begin))); begin = p + 1; } else ++begin; handler.on_align(align); break; } else if (p == begin) { break; } p = begin; } return begin; } // Parses standard format specifiers and sends notifications about parsed // components to handler. template<std::input_iterator It, std::sentinel_for<It> S, typename SpecHandler> [[nodiscard]] constexpr It parse_format_specs(It begin, S end, SpecHandler&& handler) { if (begin + 1 < end && begin[1] == '}' && is_ascii_letter(*begin) && *begin != 'L') { handler.on_type(*begin++); return begin; } if (begin == end) return begin; begin = ::units::detail::parse_align(begin, end, handler); if (begin == end) return begin; // Parse sign. begin = ::units::detail::parse_sign(begin, end, handler); if (begin == end) return begin; if (*begin == '#') { handler.on_hash(); if (++begin == end) return begin; } // Parse zero flag. if (*begin == '0') { handler.on_zero(); if (++begin == end) return begin; } begin = ::units::detail::parse_width(begin, end, handler); if (begin == end) return begin; // Parse precision. if (*begin == '.') { begin = ::units::detail::parse_precision(begin, end, handler); if (begin == end) return begin; } if (*begin == 'L') { handler.on_localized(); ++begin; } // Parse type. if (begin != end && *begin != '}') handler.on_type(*begin++); return begin; } // A format specifier handler that sets fields in basic_format_specs. template<typename Char> class specs_setter { protected: basic_format_specs<Char>& specs_; public: constexpr explicit specs_setter(basic_format_specs<Char>& specs) : specs_(specs) {} constexpr void on_align(fmt_align align) { specs_.align = align; } constexpr void on_fill(std::basic_string_view<Char> fill) { specs_.fill = fill; } constexpr void on_sign(fmt_sign s) { specs_.sign = s; } constexpr void on_hash() { specs_.alt = true; } constexpr void on_localized() { specs_.localized = true; } constexpr void on_zero() { specs_.fill[0] = Char('0'); } constexpr void on_width(int width) { specs_.width = width; } constexpr void on_precision(int precision) { specs_.precision = precision; } constexpr void on_type(Char type) { specs_.type = static_cast<char>(type); } }; // Format spec handler that saves references to arguments representing dynamic // width and precision to be resolved at formatting time. template<typename ParseContext> class dynamic_specs_handler : public specs_setter<typename ParseContext::char_type> { public: using char_type = TYPENAME ParseContext::char_type; constexpr dynamic_specs_handler(dynamic_format_specs<char_type>& specs, ParseContext& ctx) : specs_setter<char_type>(specs), specs_(specs), context_(ctx) {} template<typename T> constexpr void on_dynamic_width(T t) { specs_.dynamic_width_index = on_dynamic_arg(t, context_); } template<typename T> constexpr void on_dynamic_precision(T t) { specs_.dynamic_precision_index = on_dynamic_arg(t, context_); } private: dynamic_format_specs<char_type>& specs_; ParseContext& context_; }; } // namespace units::detail
{ "alphanum_fraction": 0.6730909816, "avg_line_length": 32.4288793103, "ext": "h", "hexsha": "457c87ff0b6508f361faddc8a96affb8596de0c8", "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": "212c9e05f252ffddbf77a8dba125f05d64d0d14a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "hofbi/units", "max_forks_repo_path": "src/core-fmt/include/units/bits/fmt.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "212c9e05f252ffddbf77a8dba125f05d64d0d14a", "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": "hofbi/units", "max_issues_repo_path": "src/core-fmt/include/units/bits/fmt.h", "max_line_length": 113, "max_stars_count": null, "max_stars_repo_head_hexsha": "212c9e05f252ffddbf77a8dba125f05d64d0d14a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "hofbi/units", "max_stars_repo_path": "src/core-fmt/include/units/bits/fmt.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3833, "size": 15047 }
#include <stdio.h> #include <string.h> #include <errno.h> #include <math.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> struct color { double value[3]; }; struct color cartesian_to_polar(struct color source_color) { struct color target_color; target_color.value[0] = source_color.value[0]; target_color.value[1] = hypot(source_color.value[1], source_color.value[2]); target_color.value[2] = atan2(source_color.value[2], source_color.value[1])*180.0/M_PI; if (target_color.value[2] < 0) { target_color.value[2] = target_color.value[2] + 360; } return target_color; } struct color polar_to_cartesian(struct color source_color) { struct color target_color; double angle; angle = source_color.value[2]/180*(M_PI); target_color.value[0] = source_color.value[0]; target_color.value[1] = cos(angle)*source_color.value[1]; target_color.value[2] = sin(angle)*source_color.value[1]; return target_color; } /* XYZ = CIE 1931 XYZ */ struct color XYZ_values_to_OSA74(double X, double Y, double Z) { struct color target_color; double x = X/(X+Y+Z); double y = Y/(X+Y+Z); double Y0 = (4.4934*x*x + 4.3034*y*y - 4.276*x*y - 1.3744*x - 2.5643*y + 1.8103)*Y; double Lambda = 5.9*(cbrt(Y0) - 2.0/3 + 0.042*cbrt(Y0-30)); double C = Lambda/(5.9*(cbrt(Y0) - 2.0/3)); double R = 0.7990*X + 0.4194*Y - 0.1648*Z; double G = -0.4493*X + 1.3265*Y + 0.0927*Z; double B = -0.1149*X + 0.3394*Y + 0.7170*Z; /* target_color.value[0] = (Lambda - 14.3993)/sqrt(2); */ target_color.value[0] = (Lambda - 14.4)/sqrt(2); target_color.value[1] = C*(1.7*cbrt(R) + 8*cbrt(G) - 9.7*cbrt(B)); target_color.value[2] = C*(-13.7*cbrt(R) + 17.7*cbrt(G) - 4*cbrt(B)); return target_color; } struct color XYZ_values_to_OSA90(double X, double Y, double Z) { struct color target_color; double x = X/(X+Y+Z); double y = Y/(X+Y+Z); double Y0 = (4.4934*x*x + 4.3034*y*y - 4.276*x*y - 1.3744*x - 2.5643*y + 1.8103)*Y; double Lambda = 5.9*(cbrt(Y0) - 2.0/3 + 0.06*cbrt(Y0-30)); double C = Lambda/(5.9*(cbrt(Y0) - 2.0/3)); double R = 0.9285*X + 0.3251*Y - 0.1915*Z; double G = -0.4493*X + 1.3265*Y + 0.0927*Z; double B = -0.2032*X + 0.6*Y + 0.5523*Z; /* target_color.value[0] = (Lambda - 14.3993)/sqrt(2); */ target_color.value[0] = (Lambda - 14.4)/sqrt(2); target_color.value[1] = C*(-1.3*cbrt(R) + 17*cbrt(G) - 15.7*cbrt(B)); target_color.value[2] = C*(-12.7*cbrt(R) + 19*cbrt(G) - 6.3*cbrt(B)); return target_color; } struct color XYZ_to_OSA74(struct color source_color) { double X, Y, Z; X = source_color.value[0]; Y = source_color.value[1]; Z = source_color.value[2]; return XYZ_values_to_OSA74(X, Y, Z); } struct color XYZ_to_OSA90(struct color source_color) { double X, Y, Z; X = source_color.value[0]; Y = source_color.value[1]; Z = source_color.value[2]; return XYZ_values_to_OSA90(X, Y, Z); } int print_matrix(gsl_matrix *matrix) { int row, column; for(row = 0; row < matrix->size1; row++) { for(column = 0; column < matrix->size2; column++) { printf("%8.8f", gsl_matrix_get(matrix, row, column)); } putchar('\n'); } return 0; } struct color OSA74_to_XYZ(struct color source_color) { double L, j, g; L = source_color.value[0]; j = source_color.value[1]; g = source_color.value[2]; struct color target_color; int max_iterations = 600; double X, Y, Z, previous_X, previous_Y, previous_Z, Delta; double L0, L1, L2, L3, j0, j1, j2, j3, g0, g1, g2, g3; struct color color0, color1, color2, color3; gsl_matrix *matrix0 = gsl_matrix_alloc(3, 3); gsl_matrix *inverse_matrix0 = gsl_matrix_alloc(3, 3); gsl_matrix *matrix1 = gsl_matrix_alloc(3, 1); gsl_matrix *matrix2 = gsl_matrix_alloc(3, 1); gsl_permutation *permutation = gsl_permutation_alloc(3); int sign = 0; /* start values */ /*X = 28.4; Y = 30.0; Z = 32.2; Delta = 0.5;*/ X = 28.4; Y = 30.0; Z = 32.2; Delta = 0.005; gsl_matrix_set(matrix2, 0, 0, X); gsl_matrix_set(matrix2, 1, 0, Y); gsl_matrix_set(matrix2, 2, 0, Z); int i = 0; do { /* calculate colors for influence matrix */ color0 = XYZ_values_to_OSA74(X, Y, Z); color1 = XYZ_values_to_OSA74(X+Delta, Y, Z); color2 = XYZ_values_to_OSA74(X, Y+Delta, Z); color3 = XYZ_values_to_OSA74(X, Y, Z+Delta); L0 = color0.value[0]; j0 = color0.value[1]; g0 = color0.value[2]; L1 = color1.value[0]; j1 = color1.value[1]; g1 = color1.value[2]; L2 = color2.value[0]; j2 = color2.value[1]; g2 = color2.value[2]; L3 = color3.value[0]; j3 = color3.value[1]; g3 = color3.value[2]; gsl_matrix_set(matrix0, 0, 0, (L1-L0)/Delta); gsl_matrix_set(matrix0, 0, 1, (L2-L0)/Delta); gsl_matrix_set(matrix0, 0, 2, (L3-L0)/Delta); gsl_matrix_set(matrix0, 1, 0, (j1-j0)/Delta); gsl_matrix_set(matrix0, 1, 1, (j2-j0)/Delta); gsl_matrix_set(matrix0, 1, 2, (j3-j0)/Delta); gsl_matrix_set(matrix0, 2, 0, (g1-g0)/Delta); gsl_matrix_set(matrix0, 2, 1, (g2-g0)/Delta); gsl_matrix_set(matrix0, 2, 2, (g3-g0)/Delta); gsl_matrix_set(matrix1, 0, 0, L-L0); gsl_matrix_set(matrix1, 1, 0, j-j0); gsl_matrix_set(matrix1, 2, 0, g-g0); /* update matrix2: matrix2 = inverse_matrix0 matrix1 + matrix2 */ /* incremental term (inverse_matrix0 × matrix1) is divided by (5+cbrt(i)) */ gsl_linalg_LU_decomp(matrix0, permutation, &sign); gsl_linalg_LU_invert(matrix0, permutation, inverse_matrix0); gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1/(5+cbrt(i)), inverse_matrix0, matrix1, 1.0, matrix2); previous_X = X; previous_Y = Y; previous_Z = Z; X = gsl_matrix_get(matrix2, 0, 0); Y = gsl_matrix_get(matrix2, 1, 0); Z = gsl_matrix_get(matrix2, 2, 0); /* printf("\n%d\n", i); print_matrix(matrix2); */ i++; } while ((i < max_iterations) && ((fabs(X - previous_X) > 0.0001) || (fabs(Y - previous_Y) > 0.0001) || (fabs(Z - previous_Z) > 0.0001))); /*printf("Iterations: %i\n", i);*/ /*free memory*/ gsl_matrix_free(matrix0); gsl_matrix_free(inverse_matrix0); gsl_matrix_free(matrix1); gsl_matrix_free(matrix2); /*gsl_matrix_free(matrix_product);*/ gsl_permutation_free(permutation); if (i == max_iterations) { fprintf(stderr, "Error: Maximum iterations reached.\n"); } target_color.value[0] = X; target_color.value[1] = Y; target_color.value[2] = Z; return target_color; } struct color OSA90_to_XYZ(struct color source_color) { double L, j, g; L = source_color.value[0]; j = source_color.value[1]; g = source_color.value[2]; struct color target_color; int max_iterations = 600; double X, Y, Z, previous_X, previous_Y, previous_Z, Delta; double L0, L1, L2, L3, j0, j1, j2, j3, g0, g1, g2, g3; struct color color0, color1, color2, color3; gsl_matrix *matrix0 = gsl_matrix_alloc(3, 3); gsl_matrix *inverse_matrix0 = gsl_matrix_alloc(3, 3); gsl_matrix *matrix1 = gsl_matrix_alloc(3, 1); gsl_matrix *matrix2 = gsl_matrix_alloc(3, 1); gsl_permutation *permutation = gsl_permutation_alloc(3); int sign = 0; /* start values */ /*X = 28.4; Y = 30.0; Z = 32.2; Delta = 0.5;*/ X = 28.4; Y = 30.0; Z = 32.2; Delta = 0.005; gsl_matrix_set(matrix2, 0, 0, X); gsl_matrix_set(matrix2, 1, 0, Y); gsl_matrix_set(matrix2, 2, 0, Z); int i = 0; do { /* calculate colors for influence matrix */ color0 = XYZ_values_to_OSA90(X, Y, Z); color1 = XYZ_values_to_OSA90(X+Delta, Y, Z); color2 = XYZ_values_to_OSA90(X, Y+Delta, Z); color3 = XYZ_values_to_OSA90(X, Y, Z+Delta); L0 = color0.value[0]; j0 = color0.value[1]; g0 = color0.value[2]; L1 = color1.value[0]; j1 = color1.value[1]; g1 = color1.value[2]; L2 = color2.value[0]; j2 = color2.value[1]; g2 = color2.value[2]; L3 = color3.value[0]; j3 = color3.value[1]; g3 = color3.value[2]; gsl_matrix_set(matrix0, 0, 0, (L1-L0)/Delta); gsl_matrix_set(matrix0, 0, 1, (L2-L0)/Delta); gsl_matrix_set(matrix0, 0, 2, (L3-L0)/Delta); gsl_matrix_set(matrix0, 1, 0, (j1-j0)/Delta); gsl_matrix_set(matrix0, 1, 1, (j2-j0)/Delta); gsl_matrix_set(matrix0, 1, 2, (j3-j0)/Delta); gsl_matrix_set(matrix0, 2, 0, (g1-g0)/Delta); gsl_matrix_set(matrix0, 2, 1, (g2-g0)/Delta); gsl_matrix_set(matrix0, 2, 2, (g3-g0)/Delta); gsl_matrix_set(matrix1, 0, 0, L-L0); gsl_matrix_set(matrix1, 1, 0, j-j0); gsl_matrix_set(matrix1, 2, 0, g-g0); /* update matrix2: matrix2 = inverse_matrix0 matrix1 + matrix2 */ /* incremental term (inverse_matrix0 × matrix1) is divided by (5+cbrt(i)) */ gsl_linalg_LU_decomp(matrix0, permutation, &sign); gsl_linalg_LU_invert(matrix0, permutation, inverse_matrix0); gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1/(5+cbrt(i)), inverse_matrix0, matrix1, 1.0, matrix2); previous_X = X; previous_Y = Y; previous_Z = Z; X = gsl_matrix_get(matrix2, 0, 0); Y = gsl_matrix_get(matrix2, 1, 0); Z = gsl_matrix_get(matrix2, 2, 0); /* printf("\n%d\n", i); print_matrix(matrix2); */ i++; } while ((i < max_iterations) && ((fabs(X - previous_X) > 0.0001) || (fabs(Y - previous_Y) > 0.0001) || (fabs(Z - previous_Z) > 0.0001))); /*printf("Iterations: %i\n", i);*/ /*free memory*/ gsl_matrix_free(matrix0); gsl_matrix_free(inverse_matrix0); gsl_matrix_free(matrix1); gsl_matrix_free(matrix2); /*gsl_matrix_free(matrix_product);*/ gsl_permutation_free(permutation); if (i == max_iterations) { fprintf(stderr, "Error: Maximum iterations reached.\n"); } target_color.value[0] = X; target_color.value[1] = Y; target_color.value[2] = Z; return target_color; } double npow(double base, double exponent) { if (base < 0) { return -pow(fabs(base), exponent); } else { return pow(base, exponent); } } const double c1 = 3424/pow(2, 12); const double c2 = 2413/pow(2, 7); const double c3 = 2392/pow(2, 7); const double n = 2610/pow(2, 14); const double p = 1.7*2523/pow(2, 5); double perceptual_quantizer(double cone_response) { return npow((c1 + c2*npow(cone_response/10000, n)) / (1 + c3*npow(cone_response/10000, n)), p); } double invert_perceptual_quantizer(double cone_response) { /*printf("input: %f\n", cone_response);*/ /*printf("return: %f\n", 10000*npow((c1 - npow(cone_response, 1/p))/(c3*npow(cone_response, 1/p) - c2), 1/n));*/ return 10000*npow((c1 - npow(cone_response, 1/p))/(c3*npow(cone_response, 1/p) - c2), 1/n); } const double d = -0.56; const double d0 = 1.6295499532821566E-11; struct color XYZ_to_Jab(struct color source_color) { double X = source_color.value[0]; double Y = source_color.value[1]; double Z = source_color.value[2]; double adjusted_X, adjusted_Y, L, M, S, adjusted_L, adjusted_M, adjusted_S, I, J, a, b, C, h; struct color target_color; adjusted_X = 1.15*X - 0.15*Z; adjusted_Y = 0.66*Y + 0.34*X; L = 0.41478972*adjusted_X + 0.579999*adjusted_Y + 0.0146480*Z; M = -0.2015100*adjusted_X + 1.120649*adjusted_Y + 0.0531008*Z; S = -0.0166008*adjusted_X + 0.264800*adjusted_Y + 0.6684799*Z; adjusted_L = perceptual_quantizer(L); adjusted_M = perceptual_quantizer(M); adjusted_S = perceptual_quantizer(S); I = 0.5*adjusted_L + 0.5*adjusted_M; J = ((1+d)*I)/(1+d*I) - d0; a = 3.524000*adjusted_L - 4.066708*adjusted_M + 0.542708*adjusted_S; b = 0.199076*adjusted_L + 1.096799*adjusted_M - 1.295875*adjusted_S; target_color.value[0] = J; target_color.value[1] = a; target_color.value[2] = b; return target_color; } struct color Jab_to_XYZ(struct color source_color) { double J = source_color.value[0]; double a = source_color.value[1]; double b = source_color.value[2]; double I, adjusted_L, adjusted_M, adjusted_S, L, M, S, adjusted_X, adjusted_Y, X, Y, Z; struct color target_color; I = ((J + d0)/(1 + d - d*(J + d0))); adjusted_L = I + 0.138605*a + 0.0580473*b; adjusted_M = I - 0.138605*a - 0.0580473*b; adjusted_S = I - 0.0960192*a - 0.811892*b; L = invert_perceptual_quantizer(adjusted_L); M = invert_perceptual_quantizer(adjusted_M); S = invert_perceptual_quantizer(adjusted_S); adjusted_X = 1.92423*L - 1.00479*M + 0.0376514*S; adjusted_Y = 0.350317*L + 0.726481*M - 0.0653844*S; Z = -0.0909828*L - 0.312728*M + 1.52277*S; X = (adjusted_X + 0.15*Z)/1.15; Y = (adjusted_Y - 0.34*X)/0.66; target_color.value[0] = X; target_color.value[1] = Y; target_color.value[2] = Z; return target_color; } const double J_scale = 0.167174631034780; struct color scale_Jab(struct color source_color) { struct color target_color; target_color.value[0] = source_color.value[0]/J_scale*100; target_color.value[1] = source_color.value[1]/J_scale*100; target_color.value[2] = source_color.value[2]; return target_color; } struct color unscale_Jab(struct color source_color) { struct color target_color; target_color.value[0] = source_color.value[0]*J_scale/100; target_color.value[1] = source_color.value[1]*J_scale/100; target_color.value[2] = source_color.value[2]; return target_color; } double apply_gamma_correction(double value) { if (value > 0.0031308) { return 1.055*pow(value, (1.0/2.4)) - 0.055; } else { return 12.92*value; } } double remove_gamma_correction(double value) { if (value > 0.04045) { return pow(((value+0.055)/1.055), 2.4); } else { return value/12.92; } } struct color XYZ_to_sRGB(struct color source_color) { double X, Y, Z; X = source_color.value[0]; Y = source_color.value[1]; Z = source_color.value[2]; struct color target_color; double linear_R, linear_G, linear_B, R, G, B; /* XYZ source values range = [0, 100] */ X = X/100.0; Y = Y/100.0; Z = Z/100.0; /* 2° observer, D65 illuminant */ linear_R = X* 3.2406 + Y*-1.5372 + Z*-0.4986; linear_G = X*-0.9689 + Y* 1.8758 + Z* 0.0415; linear_B = X* 0.0557 + Y*-0.2040 + Z* 1.0570; R = apply_gamma_correction(linear_R); G = apply_gamma_correction(linear_G); B = apply_gamma_correction(linear_B); if ((R<0.0) || (R>1.0) || (G<0.0) || (G>1.0) || (B<0.0) || (B>1.0)) { errno = ERANGE; } /* RGB target values range = [0, 255] */ target_color.value[0] = R*255; target_color.value[1] = G*255; target_color.value[2] = B*255; return target_color; } struct color sRGB_to_XYZ(struct color source_color) { double R, G, B; R = source_color.value[0]; G = source_color.value[1]; B = source_color.value[2]; struct color target_color; double linear_R, linear_G, linear_B, X, Y, Z; /* RGB source values range = [0, 255] */ R = R/255.0; G = G/255.0; B = B/255.0; linear_R = remove_gamma_correction(R); linear_G = remove_gamma_correction(G); linear_B = remove_gamma_correction(B); /* 2° observer, D65 illuminant */ X = linear_R*0.4124 + linear_G*0.3576 + linear_B*0.1805; Y = linear_R*0.2126 + linear_G*0.7152 + linear_B*0.0722; Z = linear_R*0.0193 + linear_G*0.1192 + linear_B*0.9505; /* XYZ target values range = [0, 100] */ target_color.value[0] = 100*X; target_color.value[1] = 100*Y; target_color.value[2] = 100*Z; return target_color; } const double Y_threshold = pow((6/29.0), 3); const double D65_X = 95.0156; const double D65_Y = 100; const double D65_Z = 108.8199; /*const double D65_X = 97.31273;*/ /*const double D65_Y = 100.00;*/ /*const double D65_Z = 138.59590;*/ struct color XYZ_to_Luv(struct color source_color) { /* L, u, v stand for L*, u*, v* */ double X, Y, Z, prime_u, prime_v, relative_Y, white_prime_u, white_prime_v, L, u, v; struct color target_color; X = source_color.value[0]; Y = source_color.value[1]; Z = source_color.value[2]; prime_u = (4*X) / (X + 15*Y + 3*Z); prime_v = (9*Y) / (X + 15*Y + 3*Z); white_prime_u = (4*D65_X) / (D65_X + 15*D65_Y + 3*D65_Z); white_prime_v = (9*D65_Y) / (D65_X + 15*D65_Y + 3*D65_Z); relative_Y = Y/D65_Y; if (relative_Y > pow((6/29.0), 3)) { L = cbrt(relative_Y)*116 - 16; } else { L = relative_Y*pow((29/3.0), 3); } u = 13*L*(prime_u - white_prime_u); v = 13*L*(prime_v - white_prime_v); target_color.value[0] = L; target_color.value[1] = u; target_color.value[2] = v; return target_color; } struct color Luv_to_XYZ(struct color source_color) { /* L, u, v stand for L*, u*, v* */ double L, u, v, white_prime_u, white_prime_v, prime_u, prime_v, X, Y, Z; struct color target_color; L = source_color.value[0]; u = source_color.value[1]; v = source_color.value[2]; white_prime_u = (4*D65_X) / (D65_X + 15*D65_Y + 3*D65_Z); white_prime_v = (9*D65_Y) / (D65_X + 15*D65_Y + 3*D65_Z); prime_u = u/(13*L) + white_prime_u; prime_v = v/(13*L) + white_prime_v; if (L > 8.0) { Y = D65_Y*pow((L + 16)/116.0, 3); } else { Y = D65_Y*L*pow(3/29.0, 3); } X = Y * (9*prime_u)/(4.0*prime_v); Z = Y * (12 - 3*prime_u - 20*prime_v)/(4.0*prime_v); target_color.value[0] = X; target_color.value[1] = Y; target_color.value[2] = Z; return target_color; } /* OSA74 range: -19.1032--10.0938 (29.1970) */ struct color OSA74_to_pOSA74(struct color source_color) { double L, j, g, new_L, chroma, hue; struct color target_color; L = source_color.value[0]; j = source_color.value[1]; g = source_color.value[2]; new_L = (L*sqrt(2) + 19.1032)*100/29.1970; chroma = hypot(j, g)*100/29.1970; hue = atan2(g, j)*180.0/M_PI; if (hue < 0) { hue = hue + 360; } target_color.value[0] = new_L; target_color.value[1] = chroma; target_color.value[2] = hue; return target_color; } struct color pOSA74_to_OSA74(struct color source_color) { double new_L, chroma, hue, L, angle, j, g; struct color target_color; new_L = source_color.value[0]; chroma = source_color.value[1]; hue = source_color.value[2]; L = (new_L*29.1970/100 - 19.1032)/sqrt(2); angle = hue/180*(M_PI); j = cos(angle)*chroma*29.1970/100; g = sin(angle)*chroma*29.1970/100; target_color.value[0] = L; target_color.value[1] = j; target_color.value[2] = g; return target_color; } int RGB_to_hex(struct color RGB_color) { int R = (int)(RGB_color.value[0] + 0.5); int G = (int)(RGB_color.value[1] + 0.5); int B = (int)(RGB_color.value[2] + 0.5); return (R<<16) | (G<<8) | B; } struct color hex_to_RGB(int hex_value) { struct color RGB_color; RGB_color.value[0] = ((hex_value>>16) & 0xFF)/255.0; RGB_color.value[1] = ((hex_value>>8) & 0xFF)/255.0; RGB_color.value[2] = (hex_value & 0xFF)/255.0; return RGB_color; } int main(int argc, char *argv[]) { int i; struct color source_color; struct color intermediate_color; struct color target_color; char next_char; char *source_format = argv[1]; char *target_format = argv[2]; /* check arguments */ /* check argument count */ if (argc != 6) { fprintf(stderr, "Usage: %s source_format target_format value1 value2 value3\n", argv[0]); return EXIT_FAILURE; } if (strcmp(source_format, target_format) == 0) { fprintf(stderr, "Source and target formats are identical.\n"); return EXIT_FAILURE; } /* check if color values are numbers */ for (i = 3; i < argc; i++) { if (sscanf(argv[i], "%lf%c", &source_color.value[i-3], &next_char) != 1) { fprintf(stderr, "Invalid color values, values must be numbers.\n"); return EXIT_FAILURE; } } /* OSA/polar conversions do not need intermediate conversion to XYZ */ if ((strcmp(source_format, "pOSA74") == 0) && (strcmp(target_format, "OSA74") == 0)) { target_color = pOSA74_to_OSA74(source_color); printf("%.2f %.2f %.2f\n", target_color.value[0], target_color.value[1], target_color.value[2]); return EXIT_SUCCESS; } else if ((strcmp(source_format, "OSA74") == 0) && (strcmp(target_format, "pOSA74") == 0)) { target_color = OSA74_to_pOSA74(source_color); printf("%.2f %.2f %.2f\n", target_color.value[0], target_color.value[1], target_color.value[2]); return EXIT_SUCCESS; } /* convert from source format to XYZ */ if (strcmp(source_format, "Jab") == 0) { intermediate_color = Jab_to_XYZ(polar_to_cartesian(unscale_Jab(source_color))); /*intermediate_color = Jab_to_XYZ(polar_to_cartesian(source_color));*/ /*intermediate_color = Jab_to_XYZ(source_color);*/ } else if (strcmp(source_format, "LCh") == 0) { intermediate_color = Luv_to_XYZ(polar_to_cartesian(source_color)); } else if (strcmp(source_format, "Luv") == 0) { intermediate_color = Luv_to_XYZ(source_color); } else if (strcmp(source_format, "OSA74") == 0) { intermediate_color = OSA74_to_XYZ(source_color); } else if (strcmp(source_format, "OSA90") == 0) { intermediate_color = OSA90_to_XYZ(source_color); } else if (strcmp(source_format, "pOSA74") == 0) { /*intermediate_color = OSA90_to_XYZ(polar_to_OSA(source_color));*/ intermediate_color = OSA74_to_XYZ(pOSA74_to_OSA74(source_color)); } else if (strcmp(source_format, "sRGB") == 0) { intermediate_color = sRGB_to_XYZ(source_color); } else if (strcmp(source_format, "XYZ") == 0) { intermediate_color = source_color; } else { fprintf(stderr, "Invalid source format."); return EXIT_FAILURE; } /* convert from XYZ to target format */ if (strcmp(target_format, "Jab") == 0) { target_color = scale_Jab(cartesian_to_polar(XYZ_to_Jab(intermediate_color))); /*target_color = cartesian_to_polar(XYZ_to_Jab(intermediate_color));*/ /*target_color = XYZ_to_Jab(intermediate_color);*/ } else if (strcmp(target_format, "LCh") == 0) { target_color = cartesian_to_polar(XYZ_to_Luv(intermediate_color)); } else if (strcmp(target_format, "Luv") == 0) { target_color = XYZ_to_Luv(intermediate_color); } else if (strcmp(target_format, "OSA74") == 0) { target_color = XYZ_to_OSA74(intermediate_color); } else if (strcmp(target_format, "OSA90") == 0) { target_color = XYZ_to_OSA90(intermediate_color); } else if (strcmp(target_format, "pOSA74") == 0) { target_color = OSA74_to_pOSA74(XYZ_to_OSA74(intermediate_color)); } else if (strcmp(target_format, "polarOSA74") == 0) { target_color = cartesian_to_polar(XYZ_to_OSA74(intermediate_color)); } else if (strcmp(target_format, "sRGB") == 0) { target_color = XYZ_to_sRGB(intermediate_color); } else if (strcmp(target_format, "XYZ") == 0) { target_color = intermediate_color; } else { fprintf(stderr, "Invalid target format."); return EXIT_FAILURE; } if (errno == ERANGE) { fprintf(stderr, "The requested color lies outside of the %s gamut.\n", target_format); /*return EXIT_FAILURE;*/ /*printf("%d %d %d\n", 149, 149, 148);*/ return EXIT_SUCCESS; } /* round RGB values to integers */ if (strcmp(target_format, "sRGB") == 0) { /*printf("%.0f %.0f %.0f\n", target_color.value[0], target_color.value[1], target_color.value[2]);*/ printf("#%06x\n", RGB_to_hex(target_color)); } else { printf("%.4f %.4f %.4f\n", target_color.value[0], target_color.value[1], target_color.value[2]); } return EXIT_SUCCESS; }
{ "alphanum_fraction": 0.6750067379, "avg_line_length": 31.9397417504, "ext": "c", "hexsha": "b944eba609700f51ced548743f216b4957b818bf", "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": "c4698edcd829881aa9cb40f5833d03cf3b9e8151", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "joshuakraemer/color-converter", "max_forks_repo_path": "converter.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "c4698edcd829881aa9cb40f5833d03cf3b9e8151", "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": "joshuakraemer/color-converter", "max_issues_repo_path": "converter.c", "max_line_length": 139, "max_stars_count": null, "max_stars_repo_head_hexsha": "c4698edcd829881aa9cb40f5833d03cf3b9e8151", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "joshuakraemer/color-converter", "max_stars_repo_path": "converter.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 7841, "size": 22262 }
/****************************************************************************** * gsl_sprng.h: rewrite of gsl-sprng.h to use sprng streams * * Author: Yan Y. Liu <yanliu@illinois.edu> * * Date: 2014/08/17 * * Copyright and license of this source file are specified in LICENSE.TXT * * under the root directory of this software package. * ******************************************************************************/ /* * gsl-sprng.h: rewrite of gsl-sprng.h to use sprng streams * * This header file is based on Darren Wilkinson's version for simple interface, * which does not use streams. We also refer to IceCube's C++ extension based on * sprng 4.0. * * Darren Wilkinson http://www.staff.ncl.ac.uk/d.j.wilkinson/ * IceCube project: http://icecube.wisc.edu/ * * To use, just add the line: * #include "gsl-sprng.h" * immediately after the line: * #include <gsl/gsl_rng.h> * near the start of your code. * Make sure you alloc the rng on each processor. If you wish to * set a seed, you should set it to be the same on each processor. */ #ifndef GSL_SPRNG_H #define GSL_SPRNG_H #define USE_MPI #include "sprng.h" /***************************/ /* gsl definition of sprng */ /***************************/ typedef struct { int streamnum; int nstreams; int seed; int *stream; } gsl_sprng_state_t; /* seed is gsl_rng_default_seed * either 0 by default or GSL_RNG_SEED environment variable */ void sprng_set(void * vstate, unsigned long int seed); /* the get() function to get integer random number */ unsigned long sprng_get(void * vstate); /* the get() function to get double random number */ double sprng_get_double(void * vstate); /***************************/ /* gsl_sprng API */ /***************************/ /* replace all gsl_rng_* func with corresponding one below */ /* initialize gsl_rng */ gsl_rng *gsl_sprng_alloc (int streamnum, int nstreams, int seed, int * stream); /* finalize gsl_rng */ void gsl_sprng_free (gsl_rng * r); /* print out gsl_rng stream info for debug purpose */ void gsl_sprng_print (gsl_rng * r); /* load gsl_rng from a file */ int gsl_sprng_fread (char * fpath, gsl_rng * r); /* store gsl_rng to a file */ int gsl_sprng_fwrite (char * fpath, const gsl_rng * r); #endif
{ "alphanum_fraction": 0.5840965862, "avg_line_length": 33.3611111111, "ext": "h", "hexsha": "9f3a5b0d7fc314c7afb78d2d4cce8d69fb0576b4", "lang": "C", "max_forks_count": 20, "max_forks_repo_forks_event_max_datetime": "2021-06-17T14:29:16.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-28T15:28:48.000Z", "max_forks_repo_head_hexsha": "bb0c21ca479db5ac3ecf789ab280d5e45c3c7805", "max_forks_repo_licenses": [ "NCSA", "BSD-3-Clause" ], "max_forks_repo_name": "ElsevierSoftwareX/SOFTX-D-15-00005", "max_forks_repo_path": "pgap/gsl-sprng.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "bb0c21ca479db5ac3ecf789ab280d5e45c3c7805", "max_issues_repo_issues_event_max_datetime": "2016-07-25T17:38:26.000Z", "max_issues_repo_issues_event_min_datetime": "2016-07-25T02:25:20.000Z", "max_issues_repo_licenses": [ "NCSA", "BSD-3-Clause" ], "max_issues_repo_name": "ElsevierSoftwareX/SOFTX-D-15-00005", "max_issues_repo_path": "pgap/gsl-sprng.h", "max_line_length": 81, "max_stars_count": 22, "max_stars_repo_head_hexsha": "9a7d7c02b2f1d7b6bfd1b08fbb2150c30ddd1046", "max_stars_repo_licenses": [ "NCSA", "BSD-3-Clause" ], "max_stars_repo_name": "ElsevierSoftwareX/SOFTX_2018_242", "max_stars_repo_path": "pgap/gsl-sprng.h", "max_stars_repo_stars_event_max_datetime": "2021-07-28T15:38:19.000Z", "max_stars_repo_stars_event_min_datetime": "2015-07-16T01:05:44.000Z", "num_tokens": 560, "size": 2402 }
// https://github.com/attractivechaos/matmul #include <stdlib.h> #include <stdint.h> #include <string.h> #include <stdio.h> /********************************** * Pseudo-random number generator * **********************************/ static uint64_t mat_rng[2] = { 11ULL, 1181783497276652981ULL }; static inline uint64_t xorshift128plus(uint64_t s[2]) { uint64_t x, y; x = s[0], y = s[1]; s[0] = y; x ^= x << 23; s[1] = x ^ y ^ (x >> 17) ^ (y >> 26); y += s[1]; return y; } double mat_drand(void) { return (xorshift128plus(mat_rng)>>11) * (1.0/9007199254740992.0); } /******************************************* * Helper routines for matrix manipulation * *******************************************/ float **mat_init(int n_rows, int n_cols) { float **m; int i; m = (float**)malloc(n_rows * sizeof(float*)); m[0] = (float*)calloc(n_rows * n_cols, sizeof(float)); for (i = 1; i < n_rows; ++i) m[i] = m[i-1] + n_cols; return m; } void mat_destroy(float **m) { free(m[0]); free(m); } float **mat_gen_random(int n_rows, int n_cols) { float **m; int i, j; m = mat_init(n_rows, n_cols); for (i = 0; i < n_rows; ++i) for (j = 0; j < n_cols; ++j) m[i][j] = mat_drand(); return m; } float **mat_transpose(int n_rows, int n_cols, float *const* a) { int i, j; float **m; m = mat_init(n_cols, n_rows); for (i = 0; i < n_rows; ++i) for (j = 0; j < n_cols; ++j) m[j][i] = a[i][j]; return m; } float sdot_1(int n, const float *x, const float *y) { int i; float s = 0.0f; for (i = 0; i < n; ++i) s += x[i] * y[i]; return s; } float sdot_8(int n, const float *x, const float *y) { int i, n8 = n>>3<<3; float s, t[8]; t[0] = t[1] = t[2] = t[3] = t[4] = t[5] = t[6] = t[7] = 0.0f; for (i = 0; i < n8; i += 8) { t[0] += x[i+0] * y[i+0]; t[1] += x[i+1] * y[i+1]; t[2] += x[i+2] * y[i+2]; t[3] += x[i+3] * y[i+3]; t[4] += x[i+4] * y[i+4]; t[5] += x[i+5] * y[i+5]; t[6] += x[i+6] * y[i+6]; t[7] += x[i+7] * y[i+7]; } for (s = 0.0f; i < n; ++i) s += x[i] * y[i]; s += t[0] + t[1] + t[2] + t[3] + t[4] + t[5] + t[6] + t[7]; return s; } #ifdef __SSE__ #include <xmmintrin.h> float sdot_sse(int n, const float *x, const float *y) { int i, n8 = n>>3<<3; __m128 vs1, vs2; float s, t[4]; vs1 = _mm_setzero_ps(); vs2 = _mm_setzero_ps(); for (i = 0; i < n8; i += 8) { __m128 vx1, vx2, vy1, vy2; vx1 = _mm_loadu_ps(&x[i]); vx2 = _mm_loadu_ps(&x[i+4]); vy1 = _mm_loadu_ps(&y[i]); vy2 = _mm_loadu_ps(&y[i+4]); vs1 = _mm_add_ps(vs1, _mm_mul_ps(vx1, vy1)); vs2 = _mm_add_ps(vs2, _mm_mul_ps(vx2, vy2)); } for (s = 0.0f; i < n; ++i) s += x[i] * y[i]; _mm_storeu_ps(t, vs1); s += t[0] + t[1] + t[2] + t[3]; _mm_storeu_ps(t, vs2); s += t[0] + t[1] + t[2] + t[3]; return s; } #endif /************************* * Matrix multiplication * *************************/ float **mat_mul0(int n_a_rows, int n_a_cols, float *const *a, int n_b_cols, float *const *b) { int i, j, k; float **m; m = mat_init(n_a_rows, n_b_cols); for (i = 0; i < n_a_rows; ++i) { for (j = 0; j < n_b_cols; ++j) { float t = 0.0; for (k = 0; k < n_a_cols; ++k) t += a[i][k] * b[k][j]; m[i][j] = t; } } return m; } float **mat_mul1(int n_a_rows, int n_a_cols, float *const *a, int n_b_cols, float *const *b) { int i, j, k, n_b_rows = n_a_cols; float **m, **bT; m = mat_init(n_a_rows, n_b_cols); bT = mat_transpose(n_b_rows, n_b_cols, b); for (i = 0; i < n_a_rows; ++i) { const float *ai = a[i]; float *mi = m[i]; for (j = 0; j < n_b_cols; ++j) { float t = 0.0f, *bTj = bT[j]; for (k = 0; k < n_a_cols; ++k) t += ai[k] * bTj[k]; mi[j] = t; } } mat_destroy(bT); return m; } #ifdef __SSE__ float **mat_mul2(int n_a_rows, int n_a_cols, float *const *a, int n_b_cols, float *const *b) { int i, j, n_b_rows = n_a_cols; float **m, **bT; m = mat_init(n_a_rows, n_b_cols); bT = mat_transpose(n_b_rows, n_b_cols, b); for (i = 0; i < n_a_rows; ++i) for (j = 0; j < n_b_cols; ++j) m[i][j] = sdot_sse(n_a_cols, a[i], bT[j]); mat_destroy(bT); return m; } float **mat_mul7(int n_a_rows, int n_a_cols, float *const *a, int n_b_cols, float *const *b) { int i, j, ii, jj, x = 16, n_b_rows = n_a_cols; float **m, **bT; m = mat_init(n_a_rows, n_b_cols); bT = mat_transpose(n_b_rows, n_b_cols, b); for (i = 0; i < n_a_rows; i += x) { for (j = 0; j < n_b_cols; j += x) { int je = n_b_cols < j + x? n_b_cols : j + x; int ie = n_a_rows < i + x? n_a_rows : i + x; for (ii = i; ii < ie; ++ii) for (jj = j; jj < je; ++jj) m[ii][jj] += sdot_sse(n_a_cols, a[ii], bT[jj]); } } mat_destroy(bT); return m; } #endif float **mat_mul3(int n_a_rows, int n_a_cols, float *const *a, int n_b_cols, float *const *b) { int i, j, n_b_rows = n_a_cols; float **m, **bT; m = mat_init(n_a_rows, n_b_cols); bT = mat_transpose(n_b_rows, n_b_cols, b); for (i = 0; i < n_a_rows; ++i) for (j = 0; j < n_b_cols; ++j) m[i][j] = sdot_8(n_a_cols, a[i], bT[j]); mat_destroy(bT); return m; } float **mat_mul4(int n_a_rows, int n_a_cols, float *const *a, int n_b_cols, float *const *b) { int i, j, n_b_rows = n_a_cols; float **m, **bT; m = mat_init(n_a_rows, n_b_cols); bT = mat_transpose(n_b_rows, n_b_cols, b); for (i = 0; i < n_a_rows; ++i) for (j = 0; j < n_b_cols; ++j) m[i][j] = sdot_1(n_a_cols, a[i], bT[j]); mat_destroy(bT); return m; } #ifdef HAVE_CBLAS #include <cblas.h> float **mat_mul5(int n_a_rows, int n_a_cols, float *const *a, int n_b_cols, float *const *b) { int i, j, n_b_rows = n_a_cols; float **m, **bT; m = mat_init(n_a_rows, n_b_cols); bT = mat_transpose(n_b_rows, n_b_cols, b); for (i = 0; i < n_a_rows; ++i) for (j = 0; j < n_b_cols; ++j) m[i][j] = cblas_sdot(n_a_cols, a[i], 1, bT[j], 1); mat_destroy(bT); return m; } float **mat_mul6(int n_a_rows, int n_a_cols, float *const *a, int n_b_cols, float *const *b) { float **m, n_b_rows = n_a_cols; m = mat_init(n_a_rows, n_b_cols); cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, n_a_rows, n_b_cols, n_a_cols, 1.0f, a[0], n_a_rows, b[0], n_b_rows, 0.0f, m[0], n_a_rows); return m; } #endif /***************** * Main function * *****************/ #include <unistd.h> #include <time.h> int main(int argc, char *argv[]) { int c, n = 1000, algo = 2; clock_t t; float **a, **b, **m = 0; while ((c = getopt(argc, argv, "n:a:h")) >= 0) { if (c == 'n') n = atoi(optarg); else if (c == 'a') algo = atoi(optarg); else if (c == 'h') { fprintf(stderr, "Usage: mat-eval [options]\n"); fprintf(stderr, "Options:\n"); fprintf(stderr, " -n INT size of the square matrix [%d]\n", n); fprintf(stderr, " -a INT matrix multiplication implementation [%d]\n", algo); fprintf(stderr, " 0: naive - no optimization\n"); fprintf(stderr, " 1: transposing the second matrix\n"); #ifdef __SSE__ fprintf(stderr, " 2: explicitly vectorized sdot() with SSE\n"); fprintf(stderr, " 7: explicitly SSE sdot() plus loop tiling\n"); #endif fprintf(stderr, " 3: implicitly vectorized sdot()\n"); fprintf(stderr, " 4: no vectorization hints\n"); #ifdef HAVE_CBLAS fprintf(stderr, " 5: with sdot() from an external CBLAS library\n"); fprintf(stderr, " 6: with sgemm() from an external CBLAS library\n"); #endif fprintf(stderr, " -h this help message\n"); return 1; } } a = mat_gen_random(n, n); b = mat_gen_random(n, n); t = clock(); if (algo == 0) { m = mat_mul0(n, n, a, n, b); } else if (algo == 1) { m = mat_mul1(n, n, a, n, b); #ifdef __SSE__ } else if (algo == 2) { m = mat_mul2(n, n, a, n, b); } else if (algo == 7) { m = mat_mul7(n, n, a, n, b); #endif } else if (algo == 3) { m = mat_mul3(n, n, a, n, b); } else if (algo == 4) { m = mat_mul4(n, n, a, n, b); #ifdef HAVE_CBLAS } else if (algo == 5) { m = mat_mul5(n, n, a, n, b); } else if (algo == 6) { m = mat_mul6(n, n, a, n, b); #endif } else { fprintf(stderr, "ERROR: unknown algorithm %d\n", algo); return 1; } fprintf(stderr, "CPU time: %g\n", (double)(clock() - t) / CLOCKS_PER_SEC); fprintf(stderr, "Central cell: %g\n", m[n/2][n/2]); if (m) mat_destroy(m); mat_destroy(b); mat_destroy(a); return 0; }
{ "alphanum_fraction": 0.5507774538, "avg_line_length": 25.3292307692, "ext": "c", "hexsha": "045ce1b08104c50973e968f2bcf2eecad98517a4", "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": "5e0308c38bd8aec7ac33b794f7d9551cfdf01733", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "chrisroman/llvm-pass-skeleton", "max_forks_repo_path": "benchmarks/matmul.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "5e0308c38bd8aec7ac33b794f7d9551cfdf01733", "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": "chrisroman/llvm-pass-skeleton", "max_issues_repo_path": "benchmarks/matmul.c", "max_line_length": 146, "max_stars_count": 1, "max_stars_repo_head_hexsha": "5e0308c38bd8aec7ac33b794f7d9551cfdf01733", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "chrisroman/llvm-pass-skeleton", "max_stars_repo_path": "benchmarks/matmul.c", "max_stars_repo_stars_event_max_datetime": "2020-10-26T02:45:22.000Z", "max_stars_repo_stars_event_min_datetime": "2020-10-26T02:45:22.000Z", "num_tokens": 3191, "size": 8232 }
/* specfunc/hyperg_1F1.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 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 */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include "gsl_sf_elementary.h" #include "gsl_sf_exp.h" #include "gsl_sf_bessel.h" #include "gsl_sf_gamma.h" #include "gsl_sf_laguerre.h" #include "gsl_sf_hyperg.h" #include "error.h" #include "hyperg.h" #define _1F1_INT_THRESHOLD (100.0*GSL_DBL_EPSILON) /* Asymptotic result for 1F1(a, b, x) x -> -Infinity. * Assumes b-a != neg integer and b != neg integer. */ static int hyperg_1F1_asymp_negx(const double a, const double b, const double x, gsl_sf_result * result) { gsl_sf_result lg_b; gsl_sf_result lg_bma; double sgn_b; double sgn_bma; int stat_b = gsl_sf_lngamma_sgn_e(b, &lg_b, &sgn_b); int stat_bma = gsl_sf_lngamma_sgn_e(b-a, &lg_bma, &sgn_bma); if(stat_b == GSL_SUCCESS && stat_bma == GSL_SUCCESS) { gsl_sf_result F; int stat_F = gsl_sf_hyperg_2F0_series_e(a, 1.0+a-b, -1.0/x, -1, &F); if(F.val != 0) { double ln_term_val = a*log(-x); double ln_term_err = 2.0 * GSL_DBL_EPSILON * (fabs(a) + fabs(ln_term_val)); double ln_pre_val = lg_b.val - lg_bma.val - ln_term_val; double ln_pre_err = lg_b.err + lg_bma.err + ln_term_err; int stat_e = gsl_sf_exp_mult_err_e(ln_pre_val, ln_pre_err, sgn_bma*sgn_b*F.val, F.err, result); return GSL_ERROR_SELECT_2(stat_e, stat_F); } else { result->val = 0.0; result->err = 0.0; return stat_F; } } else { DOMAIN_ERROR(result); } } /* Asymptotic result for 1F1(a, b, x) x -> +Infinity * Assumes b != neg integer and a != neg integer */ static int hyperg_1F1_asymp_posx(const double a, const double b, const double x, gsl_sf_result * result) { gsl_sf_result lg_b; gsl_sf_result lg_a; double sgn_b; double sgn_a; int stat_b = gsl_sf_lngamma_sgn_e(b, &lg_b, &sgn_b); int stat_a = gsl_sf_lngamma_sgn_e(a, &lg_a, &sgn_a); if(stat_a == GSL_SUCCESS && stat_b == GSL_SUCCESS) { gsl_sf_result F; int stat_F = gsl_sf_hyperg_2F0_series_e(b-a, 1.0-a, 1.0/x, -1, &F); if(stat_F == GSL_SUCCESS && F.val != 0) { double lnx = log(x); double ln_term_val = (a-b)*lnx; double ln_term_err = 2.0 * GSL_DBL_EPSILON * (fabs(a) + fabs(b)) * fabs(lnx) + 2.0 * GSL_DBL_EPSILON * fabs(a-b); double ln_pre_val = lg_b.val - lg_a.val + ln_term_val + x; double ln_pre_err = lg_b.err + lg_a.err + ln_term_err + 2.0 * GSL_DBL_EPSILON * fabs(x); int stat_e = gsl_sf_exp_mult_err_e(ln_pre_val, ln_pre_err, sgn_a*sgn_b*F.val, F.err, result); return GSL_ERROR_SELECT_2(stat_e, stat_F); } else { result->val = 0.0; result->err = 0.0; return stat_F; } } else { DOMAIN_ERROR(result); } } /* Asymptotic result for x < 2b-4a, 2b-4a large. * [Abramowitz+Stegun, 13.5.21] * * assumes 0 <= x/(2b-4a) <= 1 */ static int hyperg_1F1_large2bm4a(const double a, const double b, const double x, gsl_sf_result * result) { double eta = 2.0*b - 4.0*a; double cos2th = x/eta; double sin2th = 1.0 - cos2th; double th = acos(sqrt(cos2th)); double pre_h = 0.25*M_PI*M_PI*eta*eta*cos2th*sin2th; gsl_sf_result lg_b; int stat_lg = gsl_sf_lngamma_e(b, &lg_b); double t1 = 0.5*(1.0-b)*log(0.25*x*eta); double t2 = 0.25*log(pre_h); double lnpre_val = lg_b.val + 0.5*x + t1 - t2; double lnpre_err = lg_b.err + 2.0 * GSL_DBL_EPSILON * (fabs(0.5*x) + fabs(t1) + fabs(t2)); double s1 = sin(a*M_PI); double s2 = sin(0.25*eta*(2.0*th - sin(2.0*th)) + 0.25*M_PI); double ser_val = s1 + s2; double ser_err = 2.0 * GSL_DBL_EPSILON * (fabs(s1) + fabs(s2)); int stat_e = gsl_sf_exp_mult_err_e(lnpre_val, lnpre_err, ser_val, ser_err, result); return GSL_ERROR_SELECT_2(stat_e, stat_lg); } /* Luke's rational approximation. * See [Luke, Algorithms for the Computation of Mathematical Functions, p.182] * * Like the case of the 2F1 rational approximations, these are * probably guaranteed to converge for x < 0, barring gross * numerical instability in the pre-asymptotic regime. */ static int hyperg_1F1_luke(const double a, const double c, const double xin, gsl_sf_result * result) { const double RECUR_BIG = 1.0e+50; const int nmax = 5000; int n = 3; const double x = -xin; const double x3 = x*x*x; const double t0 = a/c; const double t1 = (a+1.0)/(2.0*c); const double t2 = (a+2.0)/(2.0*(c+1.0)); double F = 1.0; double prec; double Bnm3 = 1.0; /* B0 */ double Bnm2 = 1.0 + t1 * x; /* B1 */ double Bnm1 = 1.0 + t2 * x * (1.0 + t1/3.0 * x); /* B2 */ double Anm3 = 1.0; /* A0 */ double Anm2 = Bnm2 - t0 * x; /* A1 */ double Anm1 = Bnm1 - t0*(1.0 + t2*x)*x + t0 * t1 * (c/(c+1.0)) * x*x; /* A2 */ while(1) { double npam1 = n + a - 1; double npcm1 = n + c - 1; double npam2 = n + a - 2; double npcm2 = n + c - 2; double tnm1 = 2*n - 1; double tnm3 = 2*n - 3; double tnm5 = 2*n - 5; double F1 = (n-a-2) / (2*tnm3*npcm1); double F2 = (n+a)*npam1 / (4*tnm1*tnm3*npcm2*npcm1); double F3 = -npam2*npam1*(n-a-2) / (8*tnm3*tnm3*tnm5*(n+c-3)*npcm2*npcm1); double E = -npam1*(n-c-1) / (2*tnm3*npcm2*npcm1); double An = (1.0+F1*x)*Anm1 + (E + F2*x)*x*Anm2 + F3*x3*Anm3; double Bn = (1.0+F1*x)*Bnm1 + (E + F2*x)*x*Bnm2 + F3*x3*Bnm3; double r = An/Bn; prec = fabs((F - r)/F); F = r; if(prec < GSL_DBL_EPSILON || n > nmax) break; if(fabs(An) > RECUR_BIG || fabs(Bn) > RECUR_BIG) { An /= RECUR_BIG; Bn /= RECUR_BIG; Anm1 /= RECUR_BIG; Bnm1 /= RECUR_BIG; Anm2 /= RECUR_BIG; Bnm2 /= RECUR_BIG; Anm3 /= RECUR_BIG; Bnm3 /= RECUR_BIG; } else if(fabs(An) < 1.0/RECUR_BIG || fabs(Bn) < 1.0/RECUR_BIG) { An *= RECUR_BIG; Bn *= RECUR_BIG; Anm1 *= RECUR_BIG; Bnm1 *= RECUR_BIG; Anm2 *= RECUR_BIG; Bnm2 *= RECUR_BIG; Anm3 *= RECUR_BIG; Bnm3 *= RECUR_BIG; } n++; Bnm3 = Bnm2; Bnm2 = Bnm1; Bnm1 = Bn; Anm3 = Anm2; Anm2 = Anm1; Anm1 = An; } result->val = F; result->err = 2.0 * fabs(F * prec); result->err += 2.0 * GSL_DBL_EPSILON * (n-1.0) * fabs(F); return GSL_SUCCESS; } /* Series for 1F1(1,b,x) * b > 0 */ static int hyperg_1F1_1_series(const double b, const double x, gsl_sf_result * result) { double sum_val = 1.0; double sum_err = 0.0; double term = 1.0; double n = 1.0; while(fabs(term/sum_val) > 2.0*GSL_DBL_EPSILON) { term *= x/(b+n-1); sum_val += term; sum_err += 2.0 * 4.0 * GSL_DBL_EPSILON * fabs(term); n += 1.0; } result->val = sum_val; result->err = sum_err; result->err += 2.0 * fabs(term); return GSL_SUCCESS; } /* 1F1(1,b,x) * b >= 1, b integer */ static int hyperg_1F1_1_int(const int b, const double x, gsl_sf_result * result) { if(b < 1) { DOMAIN_ERROR(result); } else if(b == 1) { return gsl_sf_exp_e(x, result); } else if(b == 2) { return gsl_sf_exprel_e(x, result); } else if(b == 3) { return gsl_sf_exprel_2_e(x, result); } else { return gsl_sf_exprel_n_e(b-1, x, result); } } /* 1F1(1,b,x) * b >=1, b real * * checked OK: [GJ] Thu Oct 1 16:46:35 MDT 1998 */ static int hyperg_1F1_1(const double b, const double x, gsl_sf_result * result) { double ax = fabs(x); double ib = floor(b + 0.1); if(b < 1.0) { DOMAIN_ERROR(result); } else if(b == 1.0) { return gsl_sf_exp_e(x, result); } else if(b >= 1.4*ax) { return hyperg_1F1_1_series(b, x, result); } else if(fabs(b - ib) < _1F1_INT_THRESHOLD && ib < INT_MAX) { return hyperg_1F1_1_int((int)ib, x, result); } else if(x > 0.0) { if(x > 100.0 && b < 0.75*x) { return hyperg_1F1_asymp_posx(1.0, b, x, result); } else if(b < 1.0e+05) { /* Recurse backward on b, from a * chosen offset point. For x > 0, * which holds here, this should * be a stable direction. */ const double off = ceil(1.4*x-b) + 1.0; double bp = b + off; gsl_sf_result M; int stat_s = hyperg_1F1_1_series(bp, x, &M); const double err_rat = M.err / fabs(M.val); while(bp > b+0.1) { /* M(1,b-1) = x/(b-1) M(1,b) + 1 */ bp -= 1.0; M.val = 1.0 + x/bp * M.val; } result->val = M.val; result->err = err_rat * fabs(M.val); result->err += 2.0 * GSL_DBL_EPSILON * (fabs(off)+1.0) * fabs(M.val); return stat_s; } else { return hyperg_1F1_large2bm4a(1.0, b, x, result); } } else { /* x <= 0 and b not large compared to |x| */ if(ax < 10.0 && b < 10.0) { return hyperg_1F1_1_series(b, x, result); } else if(ax >= 100.0 && GSL_MAX_DBL(fabs(2.0-b),1.0) < 0.99*ax) { return hyperg_1F1_asymp_negx(1.0, b, x, result); } else { return hyperg_1F1_luke(1.0, b, x, result); } } } /* 1F1(a,b,x)/Gamma(b) for b->0 * [limit of Abramowitz+Stegun 13.3.7] */ static int hyperg_1F1_renorm_b0(const double a, const double x, gsl_sf_result * result) { double eta = a*x; if(eta > 0.0) { double root_eta = sqrt(eta); gsl_sf_result I1_scaled; int stat_I = gsl_sf_bessel_I1_scaled_e(2.0*root_eta, &I1_scaled); if(I1_scaled.val <= 0.0) { result->val = 0.0; result->err = 0.0; return GSL_ERROR_SELECT_2(stat_I, GSL_EDOM); } else { const double lnr_val = 0.5*x + 0.5*log(eta) + fabs(x) + log(I1_scaled.val); const double lnr_err = GSL_DBL_EPSILON * (1.5*fabs(x) + 1.0) + fabs(I1_scaled.err/I1_scaled.val); return gsl_sf_exp_err_e(lnr_val, lnr_err, result); } } else if(eta == 0.0) { result->val = 0.0; result->err = 0.0; return GSL_SUCCESS; } else { /* eta < 0 */ double root_eta = sqrt(-eta); gsl_sf_result J1; int stat_J = gsl_sf_bessel_J1_e(2.0*root_eta, &J1); if(J1.val <= 0.0) { result->val = 0.0; result->err = 0.0; return GSL_ERROR_SELECT_2(stat_J, GSL_EDOM); } else { const double t1 = 0.5*x; const double t2 = 0.5*log(-eta); const double t3 = fabs(x); const double t4 = log(J1.val); const double lnr_val = t1 + t2 + t3 + t4; const double lnr_err = GSL_DBL_EPSILON * (1.5*fabs(x) + 1.0) + fabs(J1.err/J1.val); gsl_sf_result ex; int stat_e = gsl_sf_exp_err_e(lnr_val, lnr_err, &ex); result->val = -ex.val; result->err = ex.err; return stat_e; } } } /* 1F1'(a,b,x)/1F1(a,b,x) * Uses Gautschi's version of the CF. * [Gautschi, Math. Comp. 31, 994 (1977)] * * Supposedly this suffers from the "anomalous convergence" * problem when b < x. I have seen anomalous convergence * in several of the continued fractions associated with * 1F1(a,b,x). This particular CF formulation seems stable * for b > x. However, it does display a painful artifact * of the anomalous convergence; the convergence plateaus * unless b >>> x. For example, even for b=1000, x=1, this * method locks onto a ratio which is only good to about * 4 digits. Apparently the rest of the digits are hiding * way out on the plateau, but finite-precision lossage * means you will never get them. */ #if 0 static int hyperg_1F1_CF1_p(const double a, const double b, const double x, double * result) { const double RECUR_BIG = GSL_SQRT_DBL_MAX; const int maxiter = 5000; int n = 1; double Anm2 = 1.0; double Bnm2 = 0.0; double Anm1 = 0.0; double Bnm1 = 1.0; double a1 = 1.0; double b1 = 1.0; double An = b1*Anm1 + a1*Anm2; double Bn = b1*Bnm1 + a1*Bnm2; double an, bn; double fn = An/Bn; while(n < maxiter) { double old_fn; double del; n++; Anm2 = Anm1; Bnm2 = Bnm1; Anm1 = An; Bnm1 = Bn; an = (a+n)*x/((b-x+n-1)*(b-x+n)); bn = 1.0; An = bn*Anm1 + an*Anm2; Bn = bn*Bnm1 + an*Bnm2; if(fabs(An) > RECUR_BIG || fabs(Bn) > RECUR_BIG) { An /= RECUR_BIG; Bn /= RECUR_BIG; Anm1 /= RECUR_BIG; Bnm1 /= RECUR_BIG; Anm2 /= RECUR_BIG; Bnm2 /= RECUR_BIG; } old_fn = fn; fn = An/Bn; del = old_fn/fn; if(fabs(del - 1.0) < 10.0*GSL_DBL_EPSILON) break; } *result = a/(b-x) * fn; if(n == maxiter) GSL_ERROR ("error", GSL_EMAXITER); else return GSL_SUCCESS; } #endif /* 0 */ /* 1F1'(a,b,x)/1F1(a,b,x) * Uses Gautschi's series transformation of the * continued fraction. This is apparently the best * method for getting this ratio in the stable region. * The convergence is monotone and supergeometric * when b > x. * Assumes a >= -1. */ static int hyperg_1F1_CF1_p_ser(const double a, const double b, const double x, double * result) { if(a == 0.0) { *result = 0.0; return GSL_SUCCESS; } else { const int maxiter = 5000; double sum = 1.0; double pk = 1.0; double rhok = 0.0; int k; for(k=1; k<maxiter; k++) { double ak = (a + k)*x/((b-x+k-1.0)*(b-x+k)); rhok = -ak*(1.0 + rhok)/(1.0 + ak*(1.0+rhok)); pk *= rhok; sum += pk; if(fabs(pk/sum) < 2.0*GSL_DBL_EPSILON) break; } *result = a/(b-x) * sum; if(k == maxiter) GSL_ERROR ("error", GSL_EMAXITER); else return GSL_SUCCESS; } } /* 1F1(a+1,b,x)/1F1(a,b,x) * * I think this suffers from typical "anomalous convergence". * I could not find a region where it was truly useful. */ #if 0 static int hyperg_1F1_CF1(const double a, const double b, const double x, double * result) { const double RECUR_BIG = GSL_SQRT_DBL_MAX; const int maxiter = 5000; int n = 1; double Anm2 = 1.0; double Bnm2 = 0.0; double Anm1 = 0.0; double Bnm1 = 1.0; double a1 = b - a - 1.0; double b1 = b - x - 2.0*(a+1.0); double An = b1*Anm1 + a1*Anm2; double Bn = b1*Bnm1 + a1*Bnm2; double an, bn; double fn = An/Bn; while(n < maxiter) { double old_fn; double del; n++; Anm2 = Anm1; Bnm2 = Bnm1; Anm1 = An; Bnm1 = Bn; an = (a + n - 1.0) * (b - a - n); bn = b - x - 2.0*(a+n); An = bn*Anm1 + an*Anm2; Bn = bn*Bnm1 + an*Bnm2; if(fabs(An) > RECUR_BIG || fabs(Bn) > RECUR_BIG) { An /= RECUR_BIG; Bn /= RECUR_BIG; Anm1 /= RECUR_BIG; Bnm1 /= RECUR_BIG; Anm2 /= RECUR_BIG; Bnm2 /= RECUR_BIG; } old_fn = fn; fn = An/Bn; del = old_fn/fn; if(fabs(del - 1.0) < 10.0*GSL_DBL_EPSILON) break; } *result = fn; if(n == maxiter) GSL_ERROR ("error", GSL_EMAXITER); else return GSL_SUCCESS; } #endif /* 0 */ /* 1F1(a,b+1,x)/1F1(a,b,x) * * This seemed to suffer from "anomalous convergence". * However, I have no theory for this recurrence. */ #if 0 static int hyperg_1F1_CF1_b(const double a, const double b, const double x, double * result) { const double RECUR_BIG = GSL_SQRT_DBL_MAX; const int maxiter = 5000; int n = 1; double Anm2 = 1.0; double Bnm2 = 0.0; double Anm1 = 0.0; double Bnm1 = 1.0; double a1 = b + 1.0; double b1 = (b + 1.0) * (b - x); double An = b1*Anm1 + a1*Anm2; double Bn = b1*Bnm1 + a1*Bnm2; double an, bn; double fn = An/Bn; while(n < maxiter) { double old_fn; double del; n++; Anm2 = Anm1; Bnm2 = Bnm1; Anm1 = An; Bnm1 = Bn; an = (b + n) * (b + n - 1.0 - a) * x; bn = (b + n) * (b + n - 1.0 - x); An = bn*Anm1 + an*Anm2; Bn = bn*Bnm1 + an*Bnm2; if(fabs(An) > RECUR_BIG || fabs(Bn) > RECUR_BIG) { An /= RECUR_BIG; Bn /= RECUR_BIG; Anm1 /= RECUR_BIG; Bnm1 /= RECUR_BIG; Anm2 /= RECUR_BIG; Bnm2 /= RECUR_BIG; } old_fn = fn; fn = An/Bn; del = old_fn/fn; if(fabs(del - 1.0) < 10.0*GSL_DBL_EPSILON) break; } *result = fn; if(n == maxiter) GSL_ERROR ("error", GSL_EMAXITER); else return GSL_SUCCESS; } #endif /* 0 */ /* 1F1(a,b,x) * |a| <= 1, b > 0 */ static int hyperg_1F1_small_a_bgt0(const double a, const double b, const double x, gsl_sf_result * result) { const double bma = b-a; const double oma = 1.0-a; const double ap1mb = 1.0+a-b; const double abs_bma = fabs(bma); const double abs_oma = fabs(oma); const double abs_ap1mb = fabs(ap1mb); const double ax = fabs(x); if(a == 0.0) { result->val = 1.0; result->err = 0.0; return GSL_SUCCESS; } else if(a == 1.0) { return hyperg_1F1_1(b, x, result); } else if(a == -1.0) { result->val = 1.0 + a/b * x; result->err = GSL_DBL_EPSILON * (1.0 + fabs(a/b * x)); result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else if(b >= 1.4*ax) { return gsl_sf_hyperg_1F1_series_e(a, b, x, result); } else if(x > 0.0) { if(x > 100.0 && abs_bma*abs_oma < 0.5*x) { return hyperg_1F1_asymp_posx(a, b, x, result); } else if(b < 5.0e+06) { /* Recurse backward on b from * a suitably high point. */ const double b_del = ceil(1.4*x-b) + 1.0; double bp = b + b_del; gsl_sf_result r_Mbp1; gsl_sf_result r_Mb; double Mbp1; double Mb; double Mbm1; int stat_0 = gsl_sf_hyperg_1F1_series_e(a, bp+1.0, x, &r_Mbp1); int stat_1 = gsl_sf_hyperg_1F1_series_e(a, bp, x, &r_Mb); const double err_rat = fabs(r_Mbp1.err/r_Mbp1.val) + fabs(r_Mb.err/r_Mb.val); Mbp1 = r_Mbp1.val; Mb = r_Mb.val; while(bp > b+0.1) { /* Do backward recursion. */ Mbm1 = ((x+bp-1.0)*Mb - x*(bp-a)/bp*Mbp1)/(bp-1.0); bp -= 1.0; Mbp1 = Mb; Mb = Mbm1; } result->val = Mb; result->err = err_rat * (fabs(b_del)+1.0) * fabs(Mb); result->err += 2.0 * GSL_DBL_EPSILON * fabs(Mb); return GSL_ERROR_SELECT_2(stat_0, stat_1); } else { return hyperg_1F1_large2bm4a(a, b, x, result); } } else { /* x < 0 and b not large compared to |x| */ if(ax < 10.0 && b < 10.0) { return gsl_sf_hyperg_1F1_series_e(a, b, x, result); } else if(ax >= 100.0 && GSL_MAX(abs_ap1mb,1.0) < 0.99*ax) { return hyperg_1F1_asymp_negx(a, b, x, result); } else { return hyperg_1F1_luke(a, b, x, result); } } } /* 1F1(b+eps,b,x) * |eps|<=1, b > 0 */ static int hyperg_1F1_beps_bgt0(const double eps, const double b, const double x, gsl_sf_result * result) { if(b > fabs(x) && fabs(eps) < GSL_SQRT_DBL_EPSILON) { /* If b-a is very small and x/b is not too large we can * use this explicit approximation. * * 1F1(b+eps,b,x) = exp(ax/b) (1 - eps x^2 (v2 + v3 x + ...) + ...) * * v2 = a/(2b^2(b+1)) * v3 = a(b-2a)/(3b^3(b+1)(b+2)) * ... * * See [Luke, Mathematical Functions and Their Approximations, p.292] * * This cannot be used for b near a negative integer or zero. * Also, if x/b is large the deviation from exp(x) behaviour grows. */ double a = b + eps; gsl_sf_result exab; int stat_e = gsl_sf_exp_e(a*x/b, &exab); double v2 = a/(2.0*b*b*(b+1.0)); double v3 = a*(b-2.0*a)/(3.0*b*b*b*(b+1.0)*(b+2.0)); double v = v2 + v3 * x; double f = (1.0 - eps*x*x*v); result->val = exab.val * f; result->err = exab.err * fabs(f); result->err += fabs(exab.val) * GSL_DBL_EPSILON * (1.0 + fabs(eps*x*x*v)); result->err += 4.0 * GSL_DBL_EPSILON * fabs(result->val); return stat_e; } else { /* Otherwise use a Kummer transformation to reduce * it to the small a case. */ gsl_sf_result Kummer_1F1; int stat_K = hyperg_1F1_small_a_bgt0(-eps, b, -x, &Kummer_1F1); if(Kummer_1F1.val != 0.0) { int stat_e = gsl_sf_exp_mult_err_e(x, 2.0*GSL_DBL_EPSILON*fabs(x), Kummer_1F1.val, Kummer_1F1.err, result); return GSL_ERROR_SELECT_2(stat_e, stat_K); } else { result->val = 0.0; result->err = 0.0; return stat_K; } } } /* 1F1(a,2a,x) = Gamma(a + 1/2) E(x) (|x|/4)^(-a+1/2) scaled_I(a-1/2,|x|/2) * * E(x) = exp(x) x > 0 * = 1 x < 0 * * a >= 1/2 */ static int hyperg_1F1_beq2a_pos(const double a, const double x, gsl_sf_result * result) { if(x == 0.0) { result->val = 1.0; result->err = 0.0; return GSL_SUCCESS; } else { gsl_sf_result I; int stat_I = gsl_sf_bessel_Inu_scaled_e(a-0.5, 0.5*fabs(x), &I); gsl_sf_result lg; int stat_g = gsl_sf_lngamma_e(a + 0.5, &lg); double ln_term = (0.5-a)*log(0.25*fabs(x)); double lnpre_val = lg.val + GSL_MAX_DBL(x,0.0) + ln_term; double lnpre_err = lg.err + GSL_DBL_EPSILON * (fabs(ln_term) + fabs(x)); int stat_e = gsl_sf_exp_mult_err_e(lnpre_val, lnpre_err, I.val, I.err, result); return GSL_ERROR_SELECT_3(stat_e, stat_g, stat_I); } } /* Determine middle parts of diagonal recursion along b=2a * from two endpoints, i.e. * * given: M(a,b) and M(a+1,b+2) * get: M(a+1,b+1) and M(a,b+1) */ #if 0 inline static int hyperg_1F1_diag_step(const double a, const double b, const double x, const double Mab, const double Map1bp2, double * Map1bp1, double * Mabp1) { if(a == b) { *Map1bp1 = Mab; *Mabp1 = Mab - x/(b+1.0) * Map1bp2; } else { *Map1bp1 = Mab - x * (a-b)/(b*(b+1.0)) * Map1bp2; *Mabp1 = (a * *Map1bp1 - b * Mab)/(a-b); } return GSL_SUCCESS; } #endif /* 0 */ /* Determine endpoint of diagonal recursion. * * given: M(a,b) and M(a+1,b+2) * get: M(a+1,b) and M(a+1,b+1) */ #if 0 inline static int hyperg_1F1_diag_end_step(const double a, const double b, const double x, const double Mab, const double Map1bp2, double * Map1b, double * Map1bp1) { *Map1bp1 = Mab - x * (a-b)/(b*(b+1.0)) * Map1bp2; *Map1b = Mab + x/b * *Map1bp1; return GSL_SUCCESS; } #endif /* 0 */ /* Handle the case of a and b both positive integers. * Assumes a > 0 and b > 0. */ static int hyperg_1F1_ab_posint(const int a, const int b, const double x, gsl_sf_result * result) { double ax = fabs(x); if(a == b) { return gsl_sf_exp_e(x, result); /* 1F1(a,a,x) */ } else if(a == 1) { return gsl_sf_exprel_n_e(b-1, x, result); /* 1F1(1,b,x) */ } else if(b == a + 1) { gsl_sf_result K; int stat_K = gsl_sf_exprel_n_e(a, -x, &K); /* 1F1(1,1+a,-x) */ int stat_e = gsl_sf_exp_mult_err_e(x, 2.0 * GSL_DBL_EPSILON * fabs(x), K.val, K.err, result); return GSL_ERROR_SELECT_2(stat_e, stat_K); } else if(a == b + 1) { gsl_sf_result ex; int stat_e = gsl_sf_exp_e(x, &ex); result->val = ex.val * (1.0 + x/b); result->err = ex.err * (1.0 + x/b); result->err += ex.val * GSL_DBL_EPSILON * (1.0 + fabs(x/b)); result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return stat_e; } else if(a == b + 2) { gsl_sf_result ex; int stat_e = gsl_sf_exp_e(x, &ex); double poly = (1.0 + x/b*(2.0 + x/(b+1.0))); result->val = ex.val * poly; result->err = ex.err * fabs(poly); result->err += ex.val * GSL_DBL_EPSILON * (1.0 + fabs(x/b) * (2.0 + fabs(x/(b+1.0)))); result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return stat_e; } else if(b == 2*a) { return hyperg_1F1_beq2a_pos(a, x, result); /* 1F1(a,2a,x) */ } else if( ( b < 10 && a < 10 && ax < 5.0 ) || ( b > a*ax ) || ( b > a && ax < 5.0 ) ) { return gsl_sf_hyperg_1F1_series_e(a, b, x, result); } else if(b > a && b >= 2*a + x) { /* Use the Gautschi CF series, then * recurse backward to a=0 for normalization. * This will work for either sign of x. */ double rap; int stat_CF1 = hyperg_1F1_CF1_p_ser(a, b, x, &rap); double ra = 1.0 + x/a * rap; double Ma = GSL_SQRT_DBL_MIN; double Map1 = ra * Ma; double Mnp1 = Map1; double Mn = Ma; double Mnm1; int n; for(n=a; n>0; n--) { Mnm1 = (n * Mnp1 - (2*n-b+x) * Mn) / (b-n); Mnp1 = Mn; Mn = Mnm1; } result->val = Ma/Mn; result->err = 2.0 * GSL_DBL_EPSILON * (fabs(a) + 1.0) * fabs(Ma/Mn); return stat_CF1; } else if(b > a && b < 2*a + x && b > x) { /* Use the Gautschi series representation of * the continued fraction. Then recurse forward * to the a=b line for normalization. This will * work for either sign of x, although we do need * to check for b > x, for when x is positive. */ double rap; int stat_CF1 = hyperg_1F1_CF1_p_ser(a, b, x, &rap); double ra = 1.0 + x/a * rap; gsl_sf_result ex; int stat_ex; double Ma = GSL_SQRT_DBL_MIN; double Map1 = ra * Ma; double Mnm1 = Ma; double Mn = Map1; double Mnp1; int n; for(n=a+1; n<b; n++) { Mnp1 = ((b-n)*Mnm1 + (2*n-b+x)*Mn)/n; Mnm1 = Mn; Mn = Mnp1; } stat_ex = gsl_sf_exp_e(x, &ex); /* 1F1(b,b,x) */ result->val = ex.val * Ma/Mn; result->err = ex.err * fabs(Ma/Mn); result->err += 4.0 * GSL_DBL_EPSILON * (fabs(b-a)+1.0) * fabs(result->val); return GSL_ERROR_SELECT_2(stat_ex, stat_CF1); } else if(x >= 0.0) { if(b < a) { /* The point b,b is below the b=2a+x line. * Forward recursion on a from b,b+1 is possible. * Note that a > b + 1 as well, since we already tried a = b + 1. */ if(x + log(fabs(x/b)) < GSL_LOG_DBL_MAX-2.0) { double ex = exp(x); int n; double Mnm1 = ex; /* 1F1(b,b,x) */ double Mn = ex * (1.0 + x/b); /* 1F1(b+1,b,x) */ double Mnp1; for(n=b+1; n<a; n++) { Mnp1 = ((b-n)*Mnm1 + (2*n-b+x)*Mn)/n; Mnm1 = Mn; Mn = Mnp1; } result->val = Mn; result->err = (x + 1.0) * GSL_DBL_EPSILON * fabs(Mn); result->err *= fabs(a-b)+1.0; return GSL_SUCCESS; } else { OVERFLOW_ERROR(result); } } else { /* b > a * b < 2a + x * b <= x (otherwise we would have finished above) * * Gautschi anomalous convergence region. However, we can * recurse forward all the way from a=0,1 because we are * always underneath the b=2a+x line. */ gsl_sf_result r_Mn; double Mnm1 = 1.0; /* 1F1(0,b,x) */ double Mn; /* 1F1(1,b,x) */ double Mnp1; int n; gsl_sf_exprel_n_e(b-1, x, &r_Mn); Mn = r_Mn.val; for(n=1; n<a; n++) { Mnp1 = ((b-n)*Mnm1 + (2*n-b+x)*Mn)/n; Mnm1 = Mn; Mn = Mnp1; } result->val = Mn; result->err = fabs(Mn) * (1.0 + fabs(a)) * fabs(r_Mn.err / r_Mn.val); result->err += 2.0 * GSL_DBL_EPSILON * fabs(Mn); return GSL_SUCCESS; } } else { /* x < 0 * b < a (otherwise we would have tripped one of the above) */ if(a <= 0.5*(b-x) || a >= -x) { /* Gautschi continued fraction is in the anomalous region, * so we must find another way. We recurse down in b, * from the a=b line. */ double ex = exp(x); double Manp1 = ex; double Man = ex * (1.0 + x/(a-1.0)); double Manm1; int n; for(n=a-1; n>b; n--) { Manm1 = (-n*(1-n-x)*Man - x*(n-a)*Manp1)/(n*(n-1.0)); Manp1 = Man; Man = Manm1; } result->val = Man; result->err = (fabs(x) + 1.0) * GSL_DBL_EPSILON * fabs(Man); result->err *= fabs(b-a)+1.0; return GSL_SUCCESS; } else { /* Pick a0 such that b ~= 2a0 + x, then * recurse down in b from a0,a0 to determine * the values near the line b=2a+x. Then recurse * forward on a from a0. */ int a0 = ceil(0.5*(b-x)); double Ma0b; /* M(a0,b) */ double Ma0bp1; /* M(a0,b+1) */ double Ma0p1b; /* M(a0+1,b) */ double Mnm1; double Mn; double Mnp1; int n; { double ex = exp(x); double Ma0np1 = ex; double Ma0n = ex * (1.0 + x/(a0-1.0)); double Ma0nm1; for(n=a0-1; n>b; n--) { Ma0nm1 = (-n*(1-n-x)*Ma0n - x*(n-a0)*Ma0np1)/(n*(n-1.0)); Ma0np1 = Ma0n; Ma0n = Ma0nm1; } Ma0bp1 = Ma0np1; Ma0b = Ma0n; Ma0p1b = (b*(a0+x)*Ma0b + x*(a0-b)*Ma0bp1)/(a0*b); } Mnm1 = Ma0b; Mn = Ma0p1b; for(n=a0+1; n<a; n++) { Mnp1 = ((b-n)*Mnm1 + (2*n-b+x)*Mn)/n; Mnm1 = Mn; Mn = Mnp1; } result->val = Mn; result->err = (fabs(x) + 1.0) * GSL_DBL_EPSILON * fabs(Mn); result->err *= fabs(b-a)+1.0; return GSL_SUCCESS; } } } /* Evaluate a <= 0, a integer, cases directly. (Polynomial; Horner) * When the terms are all positive, this * must work. We will assume this here. */ static int hyperg_1F1_a_negint_poly(const int a, const double b, const double x, gsl_sf_result * result) { if(a == 0) { result->val = 1.0; result->err = 1.0; return GSL_SUCCESS; } else { int N = -a; double poly = 1.0; int k; for(k=N-1; k>=0; k--) { double t = (a+k)/(b+k) * (x/(k+1)); double r = t + 1.0/poly; if(r > 0.9*GSL_DBL_MAX/poly) { OVERFLOW_ERROR(result); } else { poly *= r; /* P_n = 1 + t_n P_{n-1} */ } } result->val = poly; result->err = 2.0 * (sqrt(N) + 1.0) * GSL_DBL_EPSILON * fabs(poly); return GSL_SUCCESS; } } /* Evaluate negative integer a case by relation * to Laguerre polynomials. This is more general than * the direct polynomial evaluation, but is safe * for all values of x. * * 1F1(-n,b,x) = n!/(b)_n Laguerre[n,b-1,x] * = n B(b,n) Laguerre[n,b-1,x] * * assumes b is not a negative integer */ static int hyperg_1F1_a_negint_lag(const int a, const double b, const double x, gsl_sf_result * result) { const int n = -a; gsl_sf_result lag; const int stat_l = gsl_sf_laguerre_n_e(n, b-1.0, x, &lag); if(b < 0.0) { gsl_sf_result lnfact; gsl_sf_result lng1; gsl_sf_result lng2; double s1, s2; const int stat_f = gsl_sf_lnfact_e(n, &lnfact); const int stat_g1 = gsl_sf_lngamma_sgn_e(b + n, &lng1, &s1); const int stat_g2 = gsl_sf_lngamma_sgn_e(b, &lng2, &s2); const double lnpre_val = lnfact.val - (lng1.val - lng2.val); const double lnpre_err = lnfact.err + lng1.err + lng2.err + 2.0 * GSL_DBL_EPSILON * fabs(lnpre_val); const int stat_e = gsl_sf_exp_mult_err_e(lnpre_val, lnpre_err, s1*s2*lag.val, lag.err, result); return GSL_ERROR_SELECT_5(stat_e, stat_l, stat_g1, stat_g2, stat_f); } else { gsl_sf_result lnbeta; gsl_sf_lnbeta_e(b, n, &lnbeta); if(fabs(lnbeta.val) < 0.1) { /* As we have noted, when B(x,y) is near 1, * evaluating log(B(x,y)) is not accurate. * Instead we evaluate B(x,y) directly. */ const double ln_term_val = log(1.25*n); const double ln_term_err = 2.0 * GSL_DBL_EPSILON * ln_term_val; gsl_sf_result beta; int stat_b = gsl_sf_beta_e(b, n, &beta); int stat_e = gsl_sf_exp_mult_err_e(ln_term_val, ln_term_err, lag.val, lag.err, result); result->val *= beta.val/1.25; result->err *= beta.val/1.25; return GSL_ERROR_SELECT_3(stat_e, stat_l, stat_b); } else { /* B(x,y) was not near 1, so it is safe to use * the logarithmic values. */ const double ln_n = log(n); const double ln_term_val = lnbeta.val + ln_n; const double ln_term_err = lnbeta.err + 2.0 * GSL_DBL_EPSILON * fabs(ln_n); int stat_e = gsl_sf_exp_mult_err_e(ln_term_val, ln_term_err, lag.val, lag.err, result); return GSL_ERROR_SELECT_2(stat_e, stat_l); } } } /* Handle negative integer a case for x > 0 and * generic b. * * Combine [Abramowitz+Stegun, 13.6.9 + 13.6.27] * M(-n,b,x) = (-1)^n / (b)_n U(-n,b,x) = n! / (b)_n Laguerre^(b-1)_n(x) */ #if 0 static int hyperg_1F1_a_negint_U(const int a, const double b, const double x, gsl_sf_result * result) { const int n = -a; const double sgn = ( GSL_IS_ODD(n) ? -1.0 : 1.0 ); double sgpoch; gsl_sf_result lnpoch; gsl_sf_result U; const int stat_p = gsl_sf_lnpoch_sgn_e(b, n, &lnpoch, &sgpoch); const int stat_U = gsl_sf_hyperg_U_e(-n, b, x, &U); const int stat_e = gsl_sf_exp_mult_err_e(-lnpoch.val, lnpoch.err, sgn * sgpoch * U.val, U.err, result); return GSL_ERROR_SELECT_3(stat_e, stat_U, stat_p); } #endif /* Assumes a <= -1, b <= -1, and b <= a. */ static int hyperg_1F1_ab_negint(const int a, const int b, const double x, gsl_sf_result * result) { if(x == 0.0) { result->val = 1.0; result->err = 0.0; return GSL_SUCCESS; } else if(x > 0.0) { return hyperg_1F1_a_negint_poly(a, b, x, result); } else { /* Apply a Kummer transformation to make x > 0 so * we can evaluate the polynomial safely. Of course, * this assumes b <= a, which must be true for * a<0 and b<0, since otherwise the thing is undefined. */ gsl_sf_result K; int stat_K = hyperg_1F1_a_negint_poly(b-a, b, -x, &K); int stat_e = gsl_sf_exp_mult_err_e(x, 2.0 * GSL_DBL_EPSILON * fabs(x), K.val, K.err, result); return GSL_ERROR_SELECT_2(stat_e, stat_K); } } /* [Abramowitz+Stegun, 13.1.3] * * M(a,b,x) = Gamma(1+a-b)/Gamma(2-b) x^(1-b) * * { Gamma(b)/Gamma(a) M(1+a-b,2-b,x) - (b-1) U(1+a-b,2-b,x) } * * b not an integer >= 2 * a-b not a negative integer */ static int hyperg_1F1_U(const double a, const double b, const double x, gsl_sf_result * result) { const double bp = 2.0 - b; const double ap = a - b + 1.0; gsl_sf_result lg_ap, lg_bp; double sg_ap; int stat_lg0 = gsl_sf_lngamma_sgn_e(ap, &lg_ap, &sg_ap); int stat_lg1 = gsl_sf_lngamma_e(bp, &lg_bp); int stat_lg2 = GSL_ERROR_SELECT_2(stat_lg0, stat_lg1); double t1 = (bp-1.0) * log(x); double lnpre_val = lg_ap.val - lg_bp.val + t1; double lnpre_err = lg_ap.err + lg_bp.err + 2.0 * GSL_DBL_EPSILON * fabs(t1); gsl_sf_result lg_2mbp, lg_1papmbp; double sg_2mbp, sg_1papmbp; int stat_lg3 = gsl_sf_lngamma_sgn_e(2.0-bp, &lg_2mbp, &sg_2mbp); int stat_lg4 = gsl_sf_lngamma_sgn_e(1.0+ap-bp, &lg_1papmbp, &sg_1papmbp); int stat_lg5 = GSL_ERROR_SELECT_2(stat_lg3, stat_lg4); double lnc1_val = lg_2mbp.val - lg_1papmbp.val; double lnc1_err = lg_2mbp.err + lg_1papmbp.err + GSL_DBL_EPSILON * (fabs(lg_2mbp.val) + fabs(lg_1papmbp.val)); gsl_sf_result M; gsl_sf_result_e10 U; int stat_F = gsl_sf_hyperg_1F1_e(ap, bp, x, &M); int stat_U = gsl_sf_hyperg_U_e10_e(ap, bp, x, &U); int stat_FU = GSL_ERROR_SELECT_2(stat_F, stat_U); gsl_sf_result_e10 term_M; int stat_e0 = gsl_sf_exp_mult_err_e10_e(lnc1_val, lnc1_err, sg_2mbp*sg_1papmbp*M.val, M.err, &term_M); const double ombp = 1.0 - bp; const double Uee_val = U.e10*M_LN10; const double Uee_err = 2.0 * GSL_DBL_EPSILON * fabs(Uee_val); const double Mee_val = term_M.e10*M_LN10; const double Mee_err = 2.0 * GSL_DBL_EPSILON * fabs(Mee_val); int stat_e1; /* Do a little dance with the exponential prefactors * to avoid overflows in intermediate results. */ if(Uee_val > Mee_val) { const double factorM_val = exp(Mee_val-Uee_val); const double factorM_err = 2.0 * GSL_DBL_EPSILON * (fabs(Mee_val-Uee_val)+1.0) * factorM_val; const double inner_val = term_M.val*factorM_val - ombp*U.val; const double inner_err = term_M.err*factorM_val + fabs(ombp) * U.err + fabs(term_M.val) * factorM_err + GSL_DBL_EPSILON * (fabs(term_M.val*factorM_val) + fabs(ombp*U.val)); stat_e1 = gsl_sf_exp_mult_err_e(lnpre_val+Uee_val, lnpre_err+Uee_err, sg_ap*inner_val, inner_err, result); } else { const double factorU_val = exp(Uee_val - Mee_val); const double factorU_err = 2.0 * GSL_DBL_EPSILON * (fabs(Mee_val-Uee_val)+1.0) * factorU_val; const double inner_val = term_M.val - ombp*factorU_val*U.val; const double inner_err = term_M.err + fabs(ombp*factorU_val*U.err) + fabs(ombp*factorU_err*U.val) + GSL_DBL_EPSILON * (fabs(term_M.val) + fabs(ombp*factorU_val*U.val)); stat_e1 = gsl_sf_exp_mult_err_e(lnpre_val+Mee_val, lnpre_err+Mee_err, sg_ap*inner_val, inner_err, result); } return GSL_ERROR_SELECT_5(stat_e1, stat_e0, stat_FU, stat_lg5, stat_lg2); } /* Handle case of generic positive a, b. * Assumes b-a is not a negative integer. */ static int hyperg_1F1_ab_pos(const double a, const double b, const double x, gsl_sf_result * result) { const double ax = fabs(x); if( ( b < 10.0 && a < 10.0 && ax < 5.0 ) || ( b > a*ax ) || ( b > a && ax < 5.0 ) ) { return gsl_sf_hyperg_1F1_series_e(a, b, x, result); } else if( x < -100.0 && GSL_MAX_DBL(fabs(a),1.0)*GSL_MAX_DBL(fabs(1.0+a-b),1.0) < 0.7*fabs(x) ) { /* Large negative x asymptotic. */ return hyperg_1F1_asymp_negx(a, b, x, result); } else if( x > 100.0 && GSL_MAX_DBL(fabs(b-a),1.0)*GSL_MAX_DBL(fabs(1.0-a),1.0) < 0.7*fabs(x) ) { /* Large positive x asymptotic. */ return hyperg_1F1_asymp_posx(a, b, x, result); } else if(fabs(b-a) <= 1.0) { /* Directly handle b near a. */ return hyperg_1F1_beps_bgt0(a-b, b, x, result); /* a = b + eps */ } else if(b > a && b >= 2*a + x) { /* Use the Gautschi CF series, then * recurse backward to a near 0 for normalization. * This will work for either sign of x. */ double rap; int stat_CF1 = hyperg_1F1_CF1_p_ser(a, b, x, &rap); double ra = 1.0 + x/a * rap; double Ma = GSL_SQRT_DBL_MIN; double Map1 = ra * Ma; double Mnp1 = Map1; double Mn = Ma; double Mnm1; gsl_sf_result Mn_true; int stat_Mt; double n; for(n=a; n>0.5; n -= 1.0) { Mnm1 = (n * Mnp1 - (2.0*n-b+x) * Mn) / (b-n); Mnp1 = Mn; Mn = Mnm1; } stat_Mt = hyperg_1F1_small_a_bgt0(n, b, x, &Mn_true); result->val = (Ma/Mn) * Mn_true.val; result->err = fabs(Ma/Mn) * Mn_true.err; result->err += 2.0 * GSL_DBL_EPSILON * (fabs(a)+1.0) * fabs(result->val); return GSL_ERROR_SELECT_2(stat_Mt, stat_CF1); } else if(b > a && b < 2*a + x && b > x) { /* Use the Gautschi series representation of * the continued fraction. Then recurse forward * to near the a=b line for normalization. This will * work for either sign of x, although we do need * to check for b > x, which is relevant when x is positive. */ gsl_sf_result Mn_true; int stat_Mt; double rap; int stat_CF1 = hyperg_1F1_CF1_p_ser(a, b, x, &rap); double ra = 1.0 + x/a * rap; double Ma = GSL_SQRT_DBL_MIN; double Mnm1 = Ma; double Mn = ra * Mnm1; double Mnp1; double n; for(n=a+1.0; n<b-0.5; n += 1.0) { Mnp1 = ((b-n)*Mnm1 + (2*n-b+x)*Mn)/n; Mnm1 = Mn; Mn = Mnp1; } stat_Mt = hyperg_1F1_beps_bgt0(n-b, b, x, &Mn_true); result->val = Ma/Mn * Mn_true.val; result->err = fabs(Ma/Mn) * Mn_true.err; result->err += 2.0 * GSL_DBL_EPSILON * (fabs(b-a)+1.0) * fabs(result->val); return GSL_ERROR_SELECT_2(stat_Mt, stat_CF1); } else if(x >= 0.0) { if(b < a) { /* Forward recursion on a from a=b+eps-1,b+eps. */ double N = floor(a-b); double eps = a - b - N; gsl_sf_result r_M0; gsl_sf_result r_M1; int stat_0 = hyperg_1F1_beps_bgt0(eps-1.0, b, x, &r_M0); int stat_1 = hyperg_1F1_beps_bgt0(eps, b, x, &r_M1); double M0 = r_M0.val; double M1 = r_M1.val; double Mam1 = M0; double Ma = M1; double Map1; double ap; double start_pair = fabs(M0) + fabs(M1); double minim_pair = GSL_DBL_MAX; double pair_ratio; double rat_0 = fabs(r_M0.err/r_M0.val); double rat_1 = fabs(r_M1.err/r_M1.val); for(ap=b+eps; ap<a-0.1; ap += 1.0) { Map1 = ((b-ap)*Mam1 + (2.0*ap-b+x)*Ma)/ap; Mam1 = Ma; Ma = Map1; minim_pair = GSL_MIN_DBL(fabs(Mam1) + fabs(Ma), minim_pair); } pair_ratio = start_pair/minim_pair; result->val = Ma; result->err = 2.0 * (rat_0 + rat_1 + GSL_DBL_EPSILON) * (fabs(b-a)+1.0) * fabs(Ma); result->err += 2.0 * (rat_0 + rat_1) * pair_ratio*pair_ratio * fabs(Ma); result->err += 2.0 * GSL_DBL_EPSILON * fabs(Ma); return GSL_ERROR_SELECT_2(stat_0, stat_1); } else { /* b > a * b < 2a + x * b <= x * * Recurse forward on a from a=eps,eps+1. */ double eps = a - floor(a); gsl_sf_result r_Mnm1; gsl_sf_result r_Mn; int stat_0 = hyperg_1F1_small_a_bgt0(eps, b, x, &r_Mnm1); int stat_1 = hyperg_1F1_small_a_bgt0(eps+1.0, b, x, &r_Mn); double Mnm1 = r_Mnm1.val; double Mn = r_Mn.val; double Mnp1; double n; double start_pair = fabs(Mn) + fabs(Mnm1); double minim_pair = GSL_DBL_MAX; double pair_ratio; double rat_0 = fabs(r_Mnm1.err/r_Mnm1.val); double rat_1 = fabs(r_Mn.err/r_Mn.val); for(n=eps+1.0; n<a-0.1; n++) { Mnp1 = ((b-n)*Mnm1 + (2*n-b+x)*Mn)/n; Mnm1 = Mn; Mn = Mnp1; minim_pair = GSL_MIN_DBL(fabs(Mn) + fabs(Mnm1), minim_pair); } pair_ratio = start_pair/minim_pair; result->val = Mn; result->err = 2.0 * (rat_0 + rat_1 + GSL_DBL_EPSILON) * (fabs(a)+1.0) * fabs(Mn); result->err += 2.0 * (rat_0 + rat_1) * pair_ratio*pair_ratio * fabs(Mn); result->err += 2.0 * GSL_DBL_EPSILON * fabs(Mn); return GSL_ERROR_SELECT_2(stat_0, stat_1); } } else { /* x < 0 * b < a */ if(a <= 0.5*(b-x) || a >= -x) { /* Recurse down in b, from near the a=b line, b=a+eps,a+eps-1. */ double N = floor(a - b); double eps = 1.0 + N - a + b; gsl_sf_result r_Manp1; gsl_sf_result r_Man; int stat_0 = hyperg_1F1_beps_bgt0(-eps, a+eps, x, &r_Manp1); int stat_1 = hyperg_1F1_beps_bgt0(1.0-eps, a+eps-1.0, x, &r_Man); double Manp1 = r_Manp1.val; double Man = r_Man.val; double Manm1; double n; double start_pair = fabs(Manp1) + fabs(Man); double minim_pair = GSL_DBL_MAX; double pair_ratio; double rat_0 = fabs(r_Manp1.err/r_Manp1.val); double rat_1 = fabs(r_Man.err/r_Man.val); for(n=a+eps-1.0; n>b+0.1; n -= 1.0) { Manm1 = (-n*(1-n-x)*Man - x*(n-a)*Manp1)/(n*(n-1.0)); Manp1 = Man; Man = Manm1; minim_pair = GSL_MIN_DBL(fabs(Manp1) + fabs(Man), minim_pair); } /* FIXME: this is a nasty little hack; there is some (transient?) instability in this recurrence for some values. I can tell when it happens, which is when this pair_ratio is large. But I do not know how to measure the error in terms of it. I guessed quadratic below, but it is probably worse than that. */ pair_ratio = start_pair/minim_pair; result->val = Man; result->err = 2.0 * (rat_0 + rat_1 + GSL_DBL_EPSILON) * (fabs(b-a)+1.0) * fabs(Man); result->err *= pair_ratio*pair_ratio + 1.0; return GSL_ERROR_SELECT_2(stat_0, stat_1); } else { /* Pick a0 such that b ~= 2a0 + x, then * recurse down in b from a0,a0 to determine * the values near the line b=2a+x. Then recurse * forward on a from a0. */ double epsa = a - floor(a); double a0 = floor(0.5*(b-x)) + epsa; double N = floor(a0 - b); double epsb = 1.0 + N - a0 + b; double Ma0b; double Ma0bp1; double Ma0p1b; int stat_a0; double Mnm1; double Mn; double Mnp1; double n; double err_rat; { gsl_sf_result r_Ma0np1; gsl_sf_result r_Ma0n; int stat_0 = hyperg_1F1_beps_bgt0(-epsb, a0+epsb, x, &r_Ma0np1); int stat_1 = hyperg_1F1_beps_bgt0(1.0-epsb, a0+epsb-1.0, x, &r_Ma0n); double Ma0np1 = r_Ma0np1.val; double Ma0n = r_Ma0n.val; double Ma0nm1; err_rat = fabs(r_Ma0np1.err/r_Ma0np1.val) + fabs(r_Ma0n.err/r_Ma0n.val); for(n=a0+epsb-1.0; n>b+0.1; n -= 1.0) { Ma0nm1 = (-n*(1-n-x)*Ma0n - x*(n-a0)*Ma0np1)/(n*(n-1.0)); Ma0np1 = Ma0n; Ma0n = Ma0nm1; } Ma0bp1 = Ma0np1; Ma0b = Ma0n; Ma0p1b = (b*(a0+x)*Ma0b+x*(a0-b)*Ma0bp1)/(a0*b); /* right-down hook */ stat_a0 = GSL_ERROR_SELECT_2(stat_0, stat_1); } /* Initialise the recurrence correctly BJG */ if (a0 >= a - 0.1) { Mn = Ma0b; } else if (a0 + 1>= a - 0.1) { Mn = Ma0p1b; } else { Mnm1 = Ma0b; Mn = Ma0p1b; for(n=a0+1.0; n<a-0.1; n += 1.0) { Mnp1 = ((b-n)*Mnm1 + (2*n-b+x)*Mn)/n; Mnm1 = Mn; Mn = Mnp1; } } result->val = Mn; result->err = (err_rat + GSL_DBL_EPSILON) * (fabs(b-a)+1.0) * fabs(Mn); return stat_a0; } } } /* Assumes b != integer * Assumes a != integer when x > 0 * Assumes b-a != neg integer when x < 0 */ static int hyperg_1F1_ab_neg(const double a, const double b, const double x, gsl_sf_result * result) { const double bma = b - a; const double abs_x = fabs(x); const double abs_a = fabs(a); const double abs_b = fabs(b); const double size_a = GSL_MAX(abs_a, 1.0); const double size_b = GSL_MAX(abs_b, 1.0); const int bma_integer = ( bma - floor(bma+0.5) < _1F1_INT_THRESHOLD ); if( (abs_a < 10.0 && abs_b < 10.0 && abs_x < 5.0) || (b > 0.8*GSL_MAX(fabs(a),1.0)*fabs(x)) ) { return gsl_sf_hyperg_1F1_series_e(a, b, x, result); } else if( x > 0.0 && size_b > size_a && size_a*log(M_E*x/size_b) < GSL_LOG_DBL_EPSILON+7.0 ) { /* Series terms are positive definite up until * there is a sign change. But by then the * terms are small due to the last condition. */ return gsl_sf_hyperg_1F1_series_e(a, b, x, result); } else if( (abs_x < 5.0 && fabs(bma) < 10.0 && abs_b < 10.0) || (b > 0.8*GSL_MAX_DBL(fabs(bma),1.0)*abs_x) ) { /* Use Kummer transformation to render series safe. */ gsl_sf_result Kummer_1F1; int stat_K = gsl_sf_hyperg_1F1_series_e(bma, b, -x, &Kummer_1F1); int stat_e = gsl_sf_exp_mult_err_e(x, GSL_DBL_EPSILON * fabs(x), Kummer_1F1.val, Kummer_1F1.err, result); return GSL_ERROR_SELECT_2(stat_e, stat_K); } else if( x < -30.0 && GSL_MAX_DBL(fabs(a),1.0)*GSL_MAX_DBL(fabs(1.0+a-b),1.0) < 0.99*fabs(x) ) { /* Large negative x asymptotic. * Note that we do not check if b-a is a negative integer. */ return hyperg_1F1_asymp_negx(a, b, x, result); } else if( x > 100.0 && GSL_MAX_DBL(fabs(bma),1.0)*GSL_MAX_DBL(fabs(1.0-a),1.0) < 0.99*fabs(x) ) { /* Large positive x asymptotic. * Note that we do not check if a is a negative integer. */ return hyperg_1F1_asymp_posx(a, b, x, result); } else if(x > 0.0 && !(bma_integer && bma > 0.0)) { return hyperg_1F1_U(a, b, x, result); } else { /* FIXME: if all else fails, try the series... BJG */ if (x < 0.0) { /* Apply Kummer Transformation */ int status = gsl_sf_hyperg_1F1_series_e(b-a, b, -x, result); double K_factor = exp(x); result->val *= K_factor; result->err *= K_factor; return status; } else { int status = gsl_sf_hyperg_1F1_series_e(a, b, x, result); return status; } /* Sadness... */ /* result->val = 0.0; */ /* result->err = 0.0; */ /* GSL_ERROR ("error", GSL_EUNIMPL); */ } } /*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/ int gsl_sf_hyperg_1F1_int_e(const int a, const int b, const double x, gsl_sf_result * result) { /* CHECK_POINTER(result) */ if(x == 0.0) { result->val = 1.0; result->err = 0.0; return GSL_SUCCESS; } else if(a == b) { return gsl_sf_exp_e(x, result); } else if(b == 0) { DOMAIN_ERROR(result); } else if(a == 0) { result->val = 1.0; result->err = 0.0; return GSL_SUCCESS; } else if(b < 0 && (a < b || a > 0)) { /* Standard domain error due to singularity. */ DOMAIN_ERROR(result); } else if(x > 100.0 && GSL_MAX_DBL(1.0,fabs(b-a))*GSL_MAX_DBL(1.0,fabs(1-a)) < 0.5 * x) { /* x -> +Inf asymptotic */ return hyperg_1F1_asymp_posx(a, b, x, result); } else if(x < -100.0 && GSL_MAX_DBL(1.0,fabs(a))*GSL_MAX_DBL(1.0,fabs(1+a-b)) < 0.5 * fabs(x)) { /* x -> -Inf asymptotic */ return hyperg_1F1_asymp_negx(a, b, x, result); } else if(a < 0 && b < 0) { return hyperg_1F1_ab_negint(a, b, x, result); } else if(a < 0 && b > 0) { /* Use Kummer to reduce it to the positive integer case. * Note that b > a, strictly, since we already trapped b = a. */ gsl_sf_result Kummer_1F1; int stat_K = hyperg_1F1_ab_posint(b-a, b, -x, &Kummer_1F1); int stat_e = gsl_sf_exp_mult_err_e(x, GSL_DBL_EPSILON * fabs(x), Kummer_1F1.val, Kummer_1F1.err, result); return GSL_ERROR_SELECT_2(stat_e, stat_K); } else { /* a > 0 and b > 0 */ return hyperg_1F1_ab_posint(a, b, x, result); } } int gsl_sf_hyperg_1F1_e(const double a, const double b, const double x, gsl_sf_result * result ) { const double bma = b - a; const double rinta = floor(a + 0.5); const double rintb = floor(b + 0.5); const double rintbma = floor(bma + 0.5); const int a_integer = ( fabs(a-rinta) < _1F1_INT_THRESHOLD && rinta > INT_MIN && rinta < INT_MAX ); const int b_integer = ( fabs(b-rintb) < _1F1_INT_THRESHOLD && rintb > INT_MIN && rintb < INT_MAX ); const int bma_integer = ( fabs(bma-rintbma) < _1F1_INT_THRESHOLD && rintbma > INT_MIN && rintbma < INT_MAX ); const int b_neg_integer = ( b < -0.1 && b_integer ); const int a_neg_integer = ( a < -0.1 && a_integer ); const int bma_neg_integer = ( bma < -0.1 && bma_integer ); /* CHECK_POINTER(result) */ if(x == 0.0) { /* Testing for this before testing a and b * is somewhat arbitrary. The result is that * we have 1F1(a,0,0) = 1. */ result->val = 1.0; result->err = 0.0; return GSL_SUCCESS; } else if(b == 0.0) { DOMAIN_ERROR(result); } else if(a == 0.0) { result->val = 1.0; result->err = 0.0; return GSL_SUCCESS; } else if(a == b) { /* case: a==b; exp(x) * It's good to test exact equality now. * We also test approximate equality later. */ return gsl_sf_exp_e(x, result); } else if(fabs(b) < _1F1_INT_THRESHOLD) { /* Note that neither a nor b is zero, since * we eliminated that with the above tests. */ if(fabs(a) < _1F1_INT_THRESHOLD) { /* a and b near zero: 1 + a/b (exp(x)-1) */ gsl_sf_result exm1; int stat_e = gsl_sf_expm1_e(x, &exm1); double sa = ( a > 0.0 ? 1.0 : -1.0 ); double sb = ( b > 0.0 ? 1.0 : -1.0 ); double lnab = log(fabs(a/b)); /* safe */ gsl_sf_result hx; int stat_hx = gsl_sf_exp_mult_err_e(lnab, GSL_DBL_EPSILON * fabs(lnab), sa * sb * exm1.val, exm1.err, &hx); result->val = (hx.val == GSL_DBL_MAX ? hx.val : 1.0 + hx.val); /* FIXME: excessive paranoia ? what is DBL_MAX+1 ?*/ result->err = hx.err; return GSL_ERROR_SELECT_2(stat_hx, stat_e); } else { /* b near zero and a not near zero */ const double m_arg = 1.0/(0.5*b); gsl_sf_result F_renorm; int stat_F = hyperg_1F1_renorm_b0(a, x, &F_renorm); int stat_m = gsl_sf_multiply_err_e(m_arg, 2.0 * GSL_DBL_EPSILON * m_arg, 0.5*F_renorm.val, 0.5*F_renorm.err, result); return GSL_ERROR_SELECT_2(stat_m, stat_F); } } else if(a_integer && b_integer) { /* Check for reduction to the integer case. * Relies on the arbitrary "near an integer" test. */ return gsl_sf_hyperg_1F1_int_e((int)rinta, (int)rintb, x, result); } else if(b_neg_integer && !(a_neg_integer && a > b)) { /* Standard domain error due to * uncancelled singularity. */ DOMAIN_ERROR(result); } else if(a_neg_integer) { return hyperg_1F1_a_negint_lag((int)rinta, b, x, result); } else if(b > 0.0) { if(-1.0 <= a && a <= 1.0) { /* Handle small a explicitly. */ return hyperg_1F1_small_a_bgt0(a, b, x, result); } else if(bma_neg_integer) { /* Catch this now, to avoid problems in the * generic evaluation code. */ gsl_sf_result Kummer_1F1; int stat_K = hyperg_1F1_a_negint_lag((int)rintbma, b, -x, &Kummer_1F1); int stat_e = gsl_sf_exp_mult_err_e(x, GSL_DBL_EPSILON * fabs(x), Kummer_1F1.val, Kummer_1F1.err, result); return GSL_ERROR_SELECT_2(stat_e, stat_K); } else if(a < 0.0) { /* Use Kummer to reduce it to the generic positive case. * Note that b > a, strictly, since we already trapped b = a. * Also b-(b-a)=a, and a is not a negative integer here, * so the generic evaluation is safe. */ gsl_sf_result Kummer_1F1; int stat_K = hyperg_1F1_ab_pos(b-a, b, -x, &Kummer_1F1); int stat_e = gsl_sf_exp_mult_err_e(x, GSL_DBL_EPSILON * fabs(x), Kummer_1F1.val, Kummer_1F1.err, result); return GSL_ERROR_SELECT_2(stat_e, stat_K); } else { /* a > 0.0 */ return hyperg_1F1_ab_pos(a, b, x, result); } } else { /* b < 0.0 */ if(bma_neg_integer && x < 0.0) { /* Handle this now to prevent problems * in the generic evaluation. */ gsl_sf_result K; int stat_K; int stat_e; if(a < 0.0) { /* Kummer transformed version of safe polynomial. * The condition a < 0 is equivalent to b < b-a, * which is the condition required for the series * to be positive definite here. */ stat_K = hyperg_1F1_a_negint_poly((int)rintbma, b, -x, &K); } else { /* Generic eval for negative integer a. */ stat_K = hyperg_1F1_a_negint_lag((int)rintbma, b, -x, &K); } stat_e = gsl_sf_exp_mult_err_e(x, GSL_DBL_EPSILON * fabs(x), K.val, K.err, result); return GSL_ERROR_SELECT_2(stat_e, stat_K); } else if(a > 0.0) { /* Use Kummer to reduce it to the generic negative case. */ gsl_sf_result K; int stat_K = hyperg_1F1_ab_neg(b-a, b, -x, &K); int stat_e = gsl_sf_exp_mult_err_e(x, GSL_DBL_EPSILON * fabs(x), K.val, K.err, result); return GSL_ERROR_SELECT_2(stat_e, stat_K); } else { return hyperg_1F1_ab_neg(a, b, x, result); } } } #if 0 /* Luke in the canonical case. */ if(x < 0.0 && !a_neg_integer && !bma_neg_integer) { double prec; return hyperg_1F1_luke(a, b, x, result, &prec); } /* Luke with Kummer transformation. */ if(x > 0.0 && !a_neg_integer && !bma_neg_integer) { double prec; double Kummer_1F1; double ex; int stat_F = hyperg_1F1_luke(b-a, b, -x, &Kummer_1F1, &prec); int stat_e = gsl_sf_exp_e(x, &ex); if(stat_F == GSL_SUCCESS && stat_e == GSL_SUCCESS) { double lnr = log(fabs(Kummer_1F1)) + x; if(lnr < GSL_LOG_DBL_MAX) { *result = ex * Kummer_1F1; return GSL_SUCCESS; } else { *result = GSL_POSINF; GSL_ERROR ("overflow", GSL_EOVRFLW); } } else if(stat_F != GSL_SUCCESS) { *result = 0.0; return stat_F; } else { *result = 0.0; return stat_e; } } #endif /*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/ #include "eval.h" double gsl_sf_hyperg_1F1_int(const int m, const int n, double x) { EVAL_RESULT(gsl_sf_hyperg_1F1_int_e(m, n, x, &result)); } double gsl_sf_hyperg_1F1(double a, double b, double x) { EVAL_RESULT(gsl_sf_hyperg_1F1_e(a, b, x, &result)); }
{ "alphanum_fraction": 0.5646440269, "avg_line_length": 29.1214859438, "ext": "c", "hexsha": "c18fc705588837ec45f57a1bbe8522ad7558edf6", "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/hyperg_1F1.c", "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/hyperg_1F1.c", "max_line_length": 122, "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/hyperg_1F1.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": 20566, "size": 58010 }
/* * Copyright (c) 1997-1999 Massachusetts Institute of Technology * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ /* This file was automatically generated --- DO NOT EDIT */ /* Generated on Sun Nov 7 20:45:10 EST 1999 */ #include <fftw-int.h> #include <fftw.h> /* Generated by: ./genfft -magic-alignment-check -magic-twiddle-load-all -magic-variables 4 -magic-loopi -hc2hc-backward 6 */ /* * This function contains 72 FP additions, 38 FP multiplications, * (or, 54 additions, 20 multiplications, 18 fused multiply/add), * 25 stack variables, and 48 memory accesses */ static const fftw_real K500000000 = FFTW_KONST(+0.500000000000000000000000000000000000000000000); static const fftw_real K866025403 = FFTW_KONST(+0.866025403784438646763723170752936183471402627); static const fftw_real K2_000000000 = FFTW_KONST(+2.000000000000000000000000000000000000000000000); static const fftw_real K1_732050807 = FFTW_KONST(+1.732050807568877293527446341505872366942805254); /* * Generator Id's : * $Id: exprdag.ml,v 1.41 1999/05/26 15:44:14 fftw Exp $ * $Id: fft.ml,v 1.43 1999/05/17 19:44:18 fftw Exp $ * $Id: to_c.ml,v 1.25 1999/10/26 21:41:32 stevenj Exp $ */ void fftw_hc2hc_backward_6(fftw_real *A, const fftw_complex *W, int iostride, int m, int dist) { int i; fftw_real *X; fftw_real *Y; X = A; Y = A + (6 * iostride); { fftw_real tmp71; fftw_real tmp75; fftw_real tmp80; fftw_real tmp82; fftw_real tmp74; fftw_real tmp76; fftw_real tmp69; fftw_real tmp70; fftw_real tmp77; fftw_real tmp81; ASSERT_ALIGNED_DOUBLE; tmp69 = X[0]; tmp70 = X[3 * iostride]; tmp71 = tmp69 - tmp70; tmp75 = tmp69 + tmp70; { fftw_real tmp78; fftw_real tmp79; fftw_real tmp72; fftw_real tmp73; ASSERT_ALIGNED_DOUBLE; tmp78 = Y[-2 * iostride]; tmp79 = Y[-iostride]; tmp80 = K1_732050807 * (tmp78 + tmp79); tmp82 = K1_732050807 * (tmp78 - tmp79); tmp72 = X[2 * iostride]; tmp73 = X[iostride]; tmp74 = tmp72 - tmp73; tmp76 = tmp72 + tmp73; } X[3 * iostride] = tmp71 + (K2_000000000 * tmp74); tmp77 = tmp71 - tmp74; X[iostride] = tmp77 - tmp80; X[5 * iostride] = tmp77 + tmp80; X[0] = tmp75 + (K2_000000000 * tmp76); tmp81 = tmp75 - tmp76; X[2 * iostride] = tmp81 + tmp82; X[4 * iostride] = tmp81 - tmp82; } X = X + dist; Y = Y - dist; for (i = 2; i < m; i = i + 2, X = X + dist, Y = Y - dist, W = W + 5) { fftw_real tmp15; fftw_real tmp46; fftw_real tmp25; fftw_real tmp52; fftw_real tmp22; fftw_real tmp35; fftw_real tmp49; fftw_real tmp62; fftw_real tmp32; fftw_real tmp39; fftw_real tmp55; fftw_real tmp59; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp13; fftw_real tmp14; fftw_real tmp23; fftw_real tmp24; ASSERT_ALIGNED_DOUBLE; tmp13 = X[0]; tmp14 = Y[-3 * iostride]; tmp15 = tmp13 + tmp14; tmp46 = tmp13 - tmp14; tmp23 = Y[0]; tmp24 = X[3 * iostride]; tmp25 = tmp23 - tmp24; tmp52 = tmp23 + tmp24; } { fftw_real tmp18; fftw_real tmp47; fftw_real tmp21; fftw_real tmp48; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp16; fftw_real tmp17; fftw_real tmp19; fftw_real tmp20; ASSERT_ALIGNED_DOUBLE; tmp16 = X[2 * iostride]; tmp17 = Y[-5 * iostride]; tmp18 = tmp16 + tmp17; tmp47 = tmp16 - tmp17; tmp19 = Y[-4 * iostride]; tmp20 = X[iostride]; tmp21 = tmp19 + tmp20; tmp48 = tmp19 - tmp20; } tmp22 = tmp18 + tmp21; tmp35 = K866025403 * (tmp18 - tmp21); tmp49 = tmp47 + tmp48; tmp62 = K866025403 * (tmp47 - tmp48); } { fftw_real tmp28; fftw_real tmp54; fftw_real tmp31; fftw_real tmp53; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp26; fftw_real tmp27; fftw_real tmp29; fftw_real tmp30; ASSERT_ALIGNED_DOUBLE; tmp26 = Y[-2 * iostride]; tmp27 = X[5 * iostride]; tmp28 = tmp26 - tmp27; tmp54 = tmp26 + tmp27; tmp29 = Y[-iostride]; tmp30 = X[4 * iostride]; tmp31 = tmp29 - tmp30; tmp53 = tmp29 + tmp30; } tmp32 = tmp28 + tmp31; tmp39 = K866025403 * (tmp31 - tmp28); tmp55 = tmp53 - tmp54; tmp59 = K866025403 * (tmp54 + tmp53); } X[0] = tmp15 + tmp22; { fftw_real tmp36; fftw_real tmp42; fftw_real tmp40; fftw_real tmp44; fftw_real tmp34; fftw_real tmp38; ASSERT_ALIGNED_DOUBLE; tmp34 = tmp25 - (K500000000 * tmp32); tmp36 = tmp34 - tmp35; tmp42 = tmp35 + tmp34; tmp38 = tmp15 - (K500000000 * tmp22); tmp40 = tmp38 - tmp39; tmp44 = tmp38 + tmp39; { fftw_real tmp33; fftw_real tmp37; fftw_real tmp41; fftw_real tmp43; ASSERT_ALIGNED_DOUBLE; tmp33 = c_re(W[1]); tmp37 = c_im(W[1]); Y[-3 * iostride] = (tmp33 * tmp36) - (tmp37 * tmp40); X[2 * iostride] = (tmp37 * tmp36) + (tmp33 * tmp40); tmp41 = c_re(W[3]); tmp43 = c_im(W[3]); Y[-iostride] = (tmp41 * tmp42) - (tmp43 * tmp44); X[4 * iostride] = (tmp43 * tmp42) + (tmp41 * tmp44); } } Y[-5 * iostride] = tmp25 + tmp32; { fftw_real tmp50; fftw_real tmp56; fftw_real tmp45; fftw_real tmp51; ASSERT_ALIGNED_DOUBLE; tmp50 = tmp46 + tmp49; tmp56 = tmp52 - tmp55; tmp45 = c_re(W[2]); tmp51 = c_im(W[2]); X[3 * iostride] = (tmp45 * tmp50) + (tmp51 * tmp56); Y[-2 * iostride] = (tmp45 * tmp56) - (tmp51 * tmp50); } { fftw_real tmp60; fftw_real tmp66; fftw_real tmp64; fftw_real tmp68; fftw_real tmp58; fftw_real tmp63; ASSERT_ALIGNED_DOUBLE; tmp58 = tmp46 - (K500000000 * tmp49); tmp60 = tmp58 - tmp59; tmp66 = tmp58 + tmp59; tmp63 = tmp52 + (K500000000 * tmp55); tmp64 = tmp62 + tmp63; tmp68 = tmp63 - tmp62; { fftw_real tmp57; fftw_real tmp61; fftw_real tmp65; fftw_real tmp67; ASSERT_ALIGNED_DOUBLE; tmp57 = c_re(W[0]); tmp61 = c_im(W[0]); X[iostride] = (tmp57 * tmp60) + (tmp61 * tmp64); Y[-4 * iostride] = (tmp57 * tmp64) - (tmp61 * tmp60); tmp65 = c_re(W[4]); tmp67 = c_im(W[4]); X[5 * iostride] = (tmp65 * tmp66) + (tmp67 * tmp68); Y[0] = (tmp65 * tmp68) - (tmp67 * tmp66); } } } if (i == m) { fftw_real tmp1; fftw_real tmp6; fftw_real tmp4; fftw_real tmp5; fftw_real tmp9; fftw_real tmp11; fftw_real tmp12; fftw_real tmp10; ASSERT_ALIGNED_DOUBLE; tmp1 = X[iostride]; tmp6 = Y[-iostride]; { fftw_real tmp2; fftw_real tmp3; fftw_real tmp7; fftw_real tmp8; ASSERT_ALIGNED_DOUBLE; tmp2 = X[2 * iostride]; tmp3 = X[0]; tmp4 = tmp2 + tmp3; tmp5 = K1_732050807 * (tmp2 - tmp3); tmp7 = Y[-2 * iostride]; tmp8 = Y[0]; tmp9 = tmp7 + tmp8; tmp11 = K1_732050807 * (tmp7 - tmp8); } X[0] = K2_000000000 * (tmp1 + tmp4); tmp12 = (K2_000000000 * tmp1) - tmp4; X[2 * iostride] = tmp11 - tmp12; X[4 * iostride] = tmp12 + tmp11; X[3 * iostride] = K2_000000000 * (tmp6 - tmp9); tmp10 = (K2_000000000 * tmp6) + tmp9; X[iostride] = -(tmp5 + tmp10); X[5 * iostride] = tmp5 - tmp10; } } static const int twiddle_order[] = {1, 2, 3, 4, 5}; fftw_codelet_desc fftw_hc2hc_backward_6_desc = { "fftw_hc2hc_backward_6", (void (*)()) fftw_hc2hc_backward_6, 6, FFTW_BACKWARD, FFTW_HC2HC, 146, 5, twiddle_order, };
{ "alphanum_fraction": 0.5816219979, "avg_line_length": 28.5397350993, "ext": "c", "hexsha": "54e69795aac0941016378d055efa4ff5b50eb46d", "lang": "C", "max_forks_count": 8, "max_forks_repo_forks_event_max_datetime": "2022-03-29T02:59:10.000Z", "max_forks_repo_forks_event_min_datetime": "2017-11-20T07:52:01.000Z", "max_forks_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "albertsgrc/ftdock-opt", "max_forks_repo_path": "original/lib/fftw-2.1.3/rfftw/fhb_6.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232", "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": "albertsgrc/ftdock-opt", "max_issues_repo_path": "original/lib/fftw-2.1.3/rfftw/fhb_6.c", "max_line_length": 125, "max_stars_count": 9, "max_stars_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "albertsgrc/ftdock-opt", "max_stars_repo_path": "original/lib/fftw-2.1.3/rfftw/fhb_6.c", "max_stars_repo_stars_event_max_datetime": "2022-01-08T14:37:24.000Z", "max_stars_repo_stars_event_min_datetime": "2018-10-03T19:57:47.000Z", "num_tokens": 2872, "size": 8619 }
/*! @copyright (c) 2017 King Abdullah University of Science and * Technology (KAUST). All rights reserved. * * STARS-H is a software package, provided by King Abdullah * University of Science and Technology (KAUST) * * @file include/common.h * * @cond * This command in pair with endcond will prevent file from being documented. * * @version 0.3.0 * @author Aleksandr Mikhalev * @date 2020-06-09 * */ #ifndef __COMMON_H__ #define __COMMON_H__ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <complex.h> #include <limits.h> #include <stdint.h> #ifdef MKL #include <mkl.h> #else #include <cblas.h> #include <lapacke.h> #endif #ifdef OPENMP #include <omp.h> #endif #ifdef MPI #include <mpi.h> #ifndef SIZE_MAX #error "SIZE_MAX not defined" #endif #if SIZE_MAX == UCHAR_MAX #define my_MPI_SIZE_T MPI_UNSIGNED_CHAR #elif SIZE_MAX == USHRT_MAX #define my_MPI_SIZE_T MPI_UNSIGNED_SHORT #elif SIZE_MAX == UINT_MAX #define my_MPI_SIZE_T MPI_UNSIGNED #elif SIZE_MAX == ULONG_MAX #define my_MPI_SIZE_T MPI_UNSIGNED_LONG #elif SIZE_MAX == ULLONG_MAX #define my_MPI_SIZE_T MPI_UNSIGNED_LONG_LONG #else #error "No MPI data type fits size_t" #endif #endif #ifdef STARPU #include <starpu.h> #endif #ifdef GSL #include <gsl/gsl_sf_bessel.h> #include <gsl/gsl_sf_gamma.h> #endif #define STARSH_ERROR(format, ...)\ {\ fprintf(stderr, "STARSH ERROR: %s(): ", __func__);\ fprintf(stderr, format, ##__VA_ARGS__);\ fprintf(stderr, "\n");\ } #ifdef SHOW_WARNINGS #define STARSH_WARNING(format, ...)\ {\ fprintf(stderr, "STARSH WARNING: %s(): ", __func__);\ fprintf(stderr, format, ##__VA_ARGS__);\ fprintf(stderr, "\n");\ } #else #define STARSH_WARNING(...) #endif #define STARSH_MALLOC(var, expr_nitems)\ {\ var = malloc(sizeof(*var)*(expr_nitems));\ if(!var)\ {\ STARSH_ERROR("line %d: malloc() failed", __LINE__);\ return STARSH_MALLOC_ERROR;\ }\ } #define STARSH_REALLOC(var, expr_nitems)\ {\ var = realloc(var, sizeof(*var)*(expr_nitems));\ if(!var)\ {\ STARSH_ERROR("malloc() failed");\ return STARSH_MALLOC_ERROR;\ }\ } #define STARSH_PMALLOC(var, expr_nitems, var_info)\ {\ var = malloc(sizeof(*var)*(expr_nitems));\ if(!var)\ {\ STARSH_ERROR("malloc() failed");\ var_info = STARSH_MALLOC_ERROR;\ }\ } #define STARSH_PREALLOC(var, expr_nitems, var_info)\ {\ var = realloc(var, sizeof(*var)*(expr_nitems));\ if(!var)\ {\ STARSH_ERROR("malloc() failed");\ var_info = STARSH_MALLOC_ERROR;\ }\ } int cmp_size_t(const void *a, const void *b); #endif // __COMMON_H__ //! @endcond
{ "alphanum_fraction": 0.6310815541, "avg_line_length": 21.8091603053, "ext": "h", "hexsha": "90c4b846603e3aa5bb504664729fb4b2aee402ab", "lang": "C", "max_forks_count": 6, "max_forks_repo_forks_event_max_datetime": "2022-03-24T18:08:24.000Z", "max_forks_repo_forks_event_min_datetime": "2017-11-12T16:28:00.000Z", "max_forks_repo_head_hexsha": "380a5d41be2931e89629e1bdca95db1fdab066cc", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "enp1s0/stars-h", "max_forks_repo_path": "include/common.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "380a5d41be2931e89629e1bdca95db1fdab066cc", "max_issues_repo_issues_event_max_datetime": "2020-11-08T20:01:54.000Z", "max_issues_repo_issues_event_min_datetime": "2020-11-04T01:10:54.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "enp1s0/stars-h", "max_issues_repo_path": "include/common.h", "max_line_length": 77, "max_stars_count": 2, "max_stars_repo_head_hexsha": "380a5d41be2931e89629e1bdca95db1fdab066cc", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "enp1s0/stars-h", "max_stars_repo_path": "include/common.h", "max_stars_repo_stars_event_max_datetime": "2022-03-09T07:35:59.000Z", "max_stars_repo_stars_event_min_datetime": "2020-11-22T22:28:45.000Z", "num_tokens": 780, "size": 2857 }
/* * C version of Diffusive Nested Sampling (DNest4) by Brendon J. Brewer * * Yan-Rong Li, liyanrong@mail.ihep.ac.cn * Jun 30, 2016 * */ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <math.h> #include <string.h> #include <mpi.h> #include <gsl/gsl_rng.h> #include "dnest.h" #include "model2.h" int which_level_update; int num_data_points; int num_params; DNestFptrSet *fptrset_thismodel2; DataType *data; void *best_model_thismodel, *best_model_std_thismodel; void model2() { int i, argc=0, narg=6; char **argv; argv = malloc(narg*sizeof(char *)); for(i=0; i<narg; i++) { argv[i] = malloc(200*sizeof(char)); } strcpy(argv[argc++], "dnest"); strcpy(argv[argc++], "-s"); strcpy(argv[argc++], "restart_dnest2.txt"); strcpy(argv[argc++], "-l"); //level-dependnet sampling strcpy(argv[argc++], "-g"); //tag strcpy(argv[argc++], "2"); /* setup szie of modeltype, which is used for dnest */ num_params = 3; /* setup number of data points and allocate memory */ num_data_points = 30; data = (DataType *)malloc(num_data_points * sizeof(DataType)); fptrset_thismodel2 = dnest_malloc_fptrset(); /* setup functions used for dnest*/ fptrset_thismodel2->from_prior = from_prior_thismodel2; fptrset_thismodel2->log_likelihoods_cal = log_likelihoods_cal_thismodel2; fptrset_thismodel2->log_likelihoods_cal_initial = log_likelihoods_cal_thismodel2; fptrset_thismodel2->log_likelihoods_cal_restart = log_likelihoods_cal_thismodel2; fptrset_thismodel2->perturb = perturb_thismodel2; fptrset_thismodel2->print_particle = print_particle_thismodel2; fptrset_thismodel2->restart_action = restart_action_model2; /* load data */ if(thistask == 0) { data_load_thismodel2(); } MPI_Bcast(data, num_data_points*sizeof(DataType), MPI_BYTE, 0, MPI_COMM_WORLD); /* run dnest */ dnest(argc, argv, fptrset_thismodel2, num_params, NULL, NULL, NULL, "./", "OPTIONS2", NULL, NULL); /* free memory */ free(data); dnest_free_fptrset(fptrset_thismodel2); for(i=0; i<narg; i++) free(argv[i]); free(argv); } /*====================================================*/ /* users responsible for following struct definitions */ void from_prior_thismodel2(void *model) { double *params = (double *)model; params[0] = 1E3*dnest_randn(); params[1] = 1E3*dnest_randn(); // Log-uniform prior params[2] = exp(-10. + 20.*dnest_rand()); } double log_likelihoods_cal_thismodel2(const void *model) { double *params = (double *)model; double logL = 0.0; double var = params[2] * params[2]; int i; double mu; // Conventional gaussian sampling distribution for(i=0; i<num_data_points; i++) { mu = params[0] * data[i].x + params[1]; logL += -0.5*log(2*M_PI*var) - 0.5*pow(data[i].y - mu, 2.0)/var; } return logL; } double perturb_thismodel2(void *model) { double *params = (double *)model; double logH = 0.0, width, limit1, limit2; int which = dnest_rand_int(num_params), which_level; int size_levels; which_level_update = dnest_get_which_level_update(); size_levels = dnest_get_size_levels(); which_level = which_level_update > (size_levels - 20)?(size_levels-20):which_level_update; if(which_level > 0) { limit1 = limits[(which_level-1) * num_params *2 + which *2 ]; limit2 = limits[(which_level-1) * num_params *2 + which *2 + 1]; width = (limit2 - limit1); } if(which == 0) { if(which_level_update == 0) { width = 1E3; } logH -= -0.5*pow(params[0]/1E3, 2); params[0] += width*dnest_randh(); logH += -0.5*pow(params[0]/1E3, 2); } else if(which == 1) { if(which_level_update == 0) { width = 1E3; } logH -= -0.5*pow(params[1]/1E3, 2); params[1] += width*dnest_randh(); logH += -0.5*pow(params[1]/1E3, 2); } else { if(which_level_update == 0) { limit1 = -10.0; limit2 = 10.0; width = 20.0; } else { limit1 = log(limit1); limit2 = log(limit2); width = limit2 - limit1; } // Usual log-uniform prior trick params[2] = log(params[2]); params[2] += width*dnest_randh(); dnest_wrap(&(params[2]), -10.0, 10.0); params[2] = exp(params[2]); } return logH; } /*=======================================================*/ void print_particle_thismodel2(FILE *fp, const void *model) { int i; double *params = (double *)model; for(i=0; i<num_params; i++) { fprintf(fp, "%f ", params[i]); } fprintf(fp, "\n"); } void data_load_thismodel2() { FILE *fp; int i; fp = fopen("road.txt", "r"); if(fp == NULL) { fprintf(stderr, "ERROR: Cannot open file road.txt.\n"); exit(0); } for(i=0; i<num_data_points; i++) { fscanf(fp, "%lf %lf\n", &data[i].x, &data[i].y); //printf("%f %f\n", data[i].x, data[i].y); } fclose(fp); } /*========================================================*/ void restart_action_model2(int iflag) { return; }
{ "alphanum_fraction": 0.6196984925, "avg_line_length": 23.0324074074, "ext": "c", "hexsha": "227055cfbbb570056100432c82cc2181ed8b327a", "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": "afb6b869ce1c4ebd76662b20310f1d9d3db4e26e", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "LiyrAstroph/DNest_C", "max_forks_repo_path": "src/model2.c", "max_issues_count": 2, "max_issues_repo_head_hexsha": "afb6b869ce1c4ebd76662b20310f1d9d3db4e26e", "max_issues_repo_issues_event_max_datetime": "2021-01-06T02:04:19.000Z", "max_issues_repo_issues_event_min_datetime": "2020-05-14T10:04:48.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "LiyrAstroph/DNest_C", "max_issues_repo_path": "src/model2.c", "max_line_length": 100, "max_stars_count": 6, "max_stars_repo_head_hexsha": "afb6b869ce1c4ebd76662b20310f1d9d3db4e26e", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "LiyrAstroph/CDNest", "max_stars_repo_path": "src/model2.c", "max_stars_repo_stars_event_max_datetime": "2020-10-16T12:14:05.000Z", "max_stars_repo_stars_event_min_datetime": "2019-09-11T03:34:45.000Z", "num_tokens": 1560, "size": 4975 }
#ifndef VM_ALLOC_STACK_RESOURCE_H #define VM_ALLOC_STACK_RESOURCE_H #include "vm/alloc/memory_resource.h" #include <gsl/span> #include <cstddef> namespace wasm { struct StackOverflowError: public std::bad_alloc { StackOverflowError(const char* pos, std::size_t count): std::bad_alloc(), at(pos), requested(count) { } const char* const at; const std::size_t requested; }; struct BadAlignmentError: public std::bad_alloc { StackOverflowError(std::size_t req): std::bad_alloc(), requested(req) { } const std::size_t requested; }; struct StackResource: public pmr::memory_resource { static constexpr const std::size_t max_alignment = alignof(std::max_align_t); StackResource(char* base, std::size_t count): StackResource(gsl::span<char>(base, count)) { } StackResource(gsl::span<char> buff): base_(buff.data()), buffer_(buff) { assert(buffer_.data() == base_); } StackResource(const StackResource& other) = delete; void* expand(void* p, std::size_t old_size, std::size_t new_size, std::size_t alignment) { assert(pos + bytes <= buffer_.data()); assert(pos >= base_); assert((pos < buffer_.data()) or (old_size == 0u)); assert( (pos == (buffer_.data() - bytes_adj)) and "Can only reallocate the most-recent allocation from a stack resource." ); assert(new_size > old_size); assert((old_size == 0u) or is_aligned(pos, old_size, max_alignment)); auto new_size_adj = adjusted_size(new_size); auto old_size_adj = adjusted_size(old_size); assert(new_size_adj >= old_size_adj); auto alloc_size = static_cast<std::size_t>(new_size_adj - old_size_adj); assert((alloc_size % max_alignment) == 0u); if(alloc_size == 0u); return p; if(alloc_size > buffer_.size()) throw StackOverflowError(buffer_.data(), alloc_size); buffer_ = buffer.subspan(alloc_size); return p; } void* contract(void* p, std::size_t old_size, std::size_t new_size) override { _assert_invariants(); const char* pos = static_cast<const char*>(p); assert(pos + bytes <= buffer_.data()); assert(pos >= base_); assert((pos < buffer_.data()) or (old_size == 0u)); assert( (pos == (buffer_.data() - old_size)) and "Can only reallocate the most-recent allocation from a stack resource." ); assert(new_size < old_size); assert(is_aligned(pos, old_size, max_alignment)); auto new_size_adj = adjusted_size(new_size); auto old_size_adj = adjusted_size(old_size); assert(old_size_adj >= new_size_adj); std::size_t dist = old_size_adj - new_size_adj; if(dist == 0u); return p; assert(static_cast<std::ptrdiff_t>(dist) == (buffer_.data() - pos)); buffer_ = gsl::span<char>(p, buffer_.size() + dist); _assert_invariants(); return p; } std::size_t capacity() const { return (buffer_.data() + buffer_.size()) - base_; } gsl::span<const char> inspect() const { return gsl::span<const char>(base_, buffer_.data() - base_); } private: static bool is_power_of_two(std::size_t value) { assert(value > 0u); return not static_cast<bool>(value & (value - 1u)); } static bool is_aligned(const char* p, std::size_t count, std::size_t alignment) { assert(is_power_of_two(alignment)); return p == std::align(alignment, 1u, p, count); } static char* ensure_aligned(char*& base, std::size_t& count) { assert(base); assert(count); if(not std::align(alignof(std::max_align_t), 1u, base, count)) throw std::invalid_argument("Pointer-size pair could not be aligned in 'StackResource' constructor."); } static std::size_t adjust_size(std::size_t size) { auto err = size % max_alignment; if(err != 0u) size += max_alignment - err; return size; } void do_deallocate(void* p, std::size_t bytes, std::size_t alignment) override { _assert_invariants(); const char* pos = static_cast<const char*>(p); std::size_t alloc_size = adjusted_size(bytes); assert(is_aligned(pos, alloc_size, max_alignment)); assert(std::distance(base_, buffer_.data()) >= alloc_size); assert( pos + alloc_size == buffer_.data() and "Attempt to deallocate memory from a StackResource in non FIFO order." ); assert((pos < buffer_.data()) or (bytes == 0u)); assert(pos >= base_); buffer_ = gsl::span<char>(pos, buffer_.size() + alloc_size); _assert_invariants(); } void* do_allocate(std::size_t bytes, std::size_t alignment) override { _assert_invariants(); void* pos = buffer_.data(); if(alignment > max_alignment) throw BadAlignmentError(alignment); std::size_t alloc_size = adjusted_size(bytes); std::size_t len = buffer_.size(); if(buffer.size() < alloc_size) throw StackOverflowError(buffer_.data(), bytes); buffer_ = buffer_.subspan(alloc_size); _assert_invariants(); return pos; } void _assert_invariants() const { auto buff_pos = buffer_.data(); assert(base_ <= buff_pos); auto allocd = static_cast<std::size_t>(buff_pos - base_); assert(allocd == 0u or is_aligned(base_, allocd, max_alignment)); assert(buffer_.size() == 0u or is_aligned(buff_pos, buffer_.size(), max_alignment)); } bool do_is_equal(const pmr::memory_resource& other) const override { if(this == &other) return true; return false; } private: char* const base_; gsl::span<char> buffer_; }; template <class T> struct SimpleStack { using value_type = T; using size_type = std::size_t; using difference_type = std::ptrdiff_t; using reference = value_type&; using const_reference = const value_type&; using pointer = value_type*; using const_pointer = const value_type*; using iterator = std::reverse_iterator<pointer>; using const_iterator = std::reverse_iterator<const_pointer>; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; SimpleStack(StackResource& resource): resource_(resource), base_(resource_.allocate(0u, alignof(T))), count_(0u) { } ~SimpleStack() { std::destroy(begin(), end()); resource_.deallocate(data(), size() * sizeof(T), alignof(T)); } SimpleStack() = delete; SimpleStack(const SimpleStack&) = delete; SimpleStack(SimpleStack&&) = delete; SimpleStack& operator=(const SimpleStack&) = delete; SimpleStack& operator=(SimpleStack&&) = delete; /// @name Iterators /// @{ iterator begin() { return std::make_reverse_iterator(data() + size()); } const_iterator begin() const { return cbegin(); } const_iterator cbegin() const { return std::make_reverse_iterator(data() + size()); } reverse_iterator rbegin() { return std::make_reverse_iterator(end()); } const_reverse_iterator rbegin() const { return crbegin(); } const_reverse_iterator crbegin() const { return std::make_reverse_iterator(cend()); } iterator end() { return std::make_reverse_iterator(data()); } const_iterator end() const { return cend(); } const_iterator cend() const { return std::make_reverse_iterator(data()); } reverse_iterator rend() { return std::make_reverse_iterator(begin()); } const_reverse_iterator rend() const { return crend(); } const_reverse_iterator crend() const { return std::make_reverse_iterator(cbegin()); } /// @} Iterators /// @name Modifiers /// @{ void push(const T& value) { emplace(value); } void push(T&& value) { emplace(std::move(value)); } template <class ... Args> reference emplace(Args&& ... args) { alloc_n(1u); pointer p = ::new (base_ + (size() - 1)) T(std::forward<Args>(args)...); return *p; } template <class ... Args> reference replace_top(Args&& ... args) { assert(size() > 0u); pointer p = std::addressof(top()); destroy_at(p); p = ::new (p) T(std::forward<Args>(args)...); return *std::launder(p); } value_type pop() { assert(not empty()); auto v = top(); pop(1u); return v; } void pop_n(std::size_t n) { assert(n > 0u); assert(size() >= n); std::destroy(begin(), begin() + n); dealloc_n(n); } /// @} Modifiers /// @name Element Access /// @{ const_reference top() const { assert(not empty()); return base_[size() - 1]; } reference top() { assert(not empty()); return base_[size() - 1u]; } const_reference operator[](size_type i) const { assert(not empty()); assert(i < size()); return data()[((size() - 1) - i)]; } reference operator[](size_type i) { return const_cast<reference>(std::as_const(*this)[i]); } const_reference at(size_type i) const { if(i < size()) return (*this)[i]; throw std::out_of_range("Attempt to access value in stack at an out-of-range depth."); } reference at(size_type i) { return const_cast<reference>(std::as_const(*this).at(i)); } const_pointer data() const { return base_; } pointer data() { return base_; } /// @} Element Access /// @name Capacity /// @{ size_type size() const { return count_; } size_type max_size() const { return std::numeric_limits<std::size_t>::max() / sizeof(T); } bool empty() const { return size() == 0u; } /// @} Capacity const StackResource& get_resource() const { return resource_; } StackResource& get_resource() { return resource_; } private: void alloc_n(std::size_t n) { assert(n > 0u); T* pos = static_cast<T*>(resource_.expand(base_, sizeof(T) * n, alignof(T))); assert(pos == base_); base_ = pos; count_ += n; } void dealloc_n(std::size_t n) { assert(n > 0u); assert(count_ >= n); T* pos = static_cast<T*>(resource_.contract(base_, n * sizeof(T), alignof(T))); base_ = pos; count_ -= n; } StackResource& resource_; T* base_; std::size_t count_; }; } /* namespace wasm */ #endif /* VM_ALLOC_STACK_RESOURCE_H */
{ "alphanum_fraction": 0.6719636776, "avg_line_length": 23.5790754258, "ext": "h", "hexsha": "a8386c85d9b48c3454aab2a95601bbcf781086d3", "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": "8a56c1706e2723ece36e3642bae9e36792dbd7b2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "tvanslyke/wasm-cpp", "max_forks_repo_path": "include/vm/alloc/StackResource.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "8a56c1706e2723ece36e3642bae9e36792dbd7b2", "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": "tvanslyke/wasm-cpp", "max_issues_repo_path": "include/vm/alloc/StackResource.h", "max_line_length": 105, "max_stars_count": null, "max_stars_repo_head_hexsha": "8a56c1706e2723ece36e3642bae9e36792dbd7b2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "tvanslyke/wasm-cpp", "max_stars_repo_path": "include/vm/alloc/StackResource.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2630, "size": 9691 }
#include "lah.h" #ifdef HAVE_LAPACK #include <lapacke.h> #include <math.h> /* Input Matrix P has to be symmetric positive semi-definite, * e.g. real covarianz matrix */ lah_Return lah_matSqrt(lah_mat *P, lah_mat *Psqrt, lah_mat *Work) { lah_Return res = lahReturnOk; lah_index i, j; lah_value temp; lah_value *S; lah_mat *Z; if (P == NULL || P->nR != P->nC || Psqrt == NULL || P->nR != Psqrt->nR || P->nC != Psqrt->nC) { return lahReturnParameterError; } if (LAH_ISTYPE(P, lahTypeDiagonal)) { for (j = 0; j < P->nC; j++) LAH_ENTRY(P, j, j) = sqrt(LAH_ENTRY(P, j, j)); return lahReturnOk; } /* allocate space for the output parameters and workspace arrays */ S = malloc(P->nR * sizeof(lah_value)); Z = lah_matAlloc(P->nR, P->nR, 1); res = lah_eigenValue(P, S, Z); if(res != lahReturnOk) return res; /* Calculate Workspace = Z*D */ for (j = 0; j < P->nC; ++j) { temp = S[j]; if (temp < 0) return lahReturnMathError; /*Not positive semi definite*/ else temp = sqrt(temp); for (i = 0; i< P->nR; ++i) { LAH_ENTRY(Work, i, j) = LAH_ENTRY(Z, i, j) * temp; } } /* Calculate End result P_sqrt = W*Z^T */ res = lah_matMul(lahNorm, lahTrans, 0, 1, Psqrt, Work, Z); lah_matFree(Z); free(S); return res; } #endif
{ "alphanum_fraction": 0.5308474576, "avg_line_length": 25.4310344828, "ext": "c", "hexsha": "3d35e9463405b8c776904a6ff4933de7524041ab", "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": "bdac65b0714d69eb03ae73b2b09a2a84ebb5f3aa", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "maj0e/linear-algebra-helpers", "max_forks_repo_path": "Source/lah_matSqrt.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bdac65b0714d69eb03ae73b2b09a2a84ebb5f3aa", "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": "maj0e/linear-algebra-helpers", "max_issues_repo_path": "Source/lah_matSqrt.c", "max_line_length": 71, "max_stars_count": null, "max_stars_repo_head_hexsha": "bdac65b0714d69eb03ae73b2b09a2a84ebb5f3aa", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "maj0e/linear-algebra-helpers", "max_stars_repo_path": "Source/lah_matSqrt.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 469, "size": 1475 }
/* specfunc/gsl_sf_hyperg.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 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 */ #ifndef __GSL_SF_HYPERG_H__ #define __GSL_SF_HYPERG_H__ #include <gsl/gsl_sf_result.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 /* Hypergeometric function related to Bessel functions * 0F1[c,x] = * Gamma[c] x^(1/2(1-c)) I_{c-1}(2 Sqrt[x]) * Gamma[c] (-x)^(1/2(1-c)) J_{c-1}(2 Sqrt[-x]) * * exceptions: GSL_EOVRFLW, GSL_EUNDRFLW */ int gsl_sf_hyperg_0F1_e(double c, double x, gsl_sf_result * result); double gsl_sf_hyperg_0F1(const double c, const double x); /* Confluent hypergeometric function for integer parameters. * 1F1[m,n,x] = M(m,n,x) * * exceptions: */ int gsl_sf_hyperg_1F1_int_e(const int m, const int n, const double x, gsl_sf_result * result); double gsl_sf_hyperg_1F1_int(const int m, const int n, double x); /* Confluent hypergeometric function. * 1F1[a,b,x] = M(a,b,x) * * exceptions: */ int gsl_sf_hyperg_1F1_e(const double a, const double b, const double x, gsl_sf_result * result); double gsl_sf_hyperg_1F1(double a, double b, double x); /* Confluent hypergeometric function for integer parameters. * U(m,n,x) * * exceptions: */ int gsl_sf_hyperg_U_int_e(const int m, const int n, const double x, gsl_sf_result * result); double gsl_sf_hyperg_U_int(const int m, const int n, const double x); /* Confluent hypergeometric function for integer parameters. * U(m,n,x) * * exceptions: */ int gsl_sf_hyperg_U_int_e10_e(const int m, const int n, const double x, gsl_sf_result_e10 * result); /* Confluent hypergeometric function. * U(a,b,x) * * exceptions: */ int gsl_sf_hyperg_U_e(const double a, const double b, const double x, gsl_sf_result * result); double gsl_sf_hyperg_U(const double a, const double b, const double x); /* Confluent hypergeometric function. * U(a,b,x) * * exceptions: */ int gsl_sf_hyperg_U_e10_e(const double a, const double b, const double x, gsl_sf_result_e10 * result); /* Gauss hypergeometric function 2F1[a,b,c,x] * |x| < 1 * * exceptions: */ int gsl_sf_hyperg_2F1_e(double a, double b, const double c, const double x, gsl_sf_result * result); double gsl_sf_hyperg_2F1(double a, double b, double c, double x); /* Gauss hypergeometric function * 2F1[aR + I aI, aR - I aI, c, x] * |x| < 1 * * exceptions: */ int gsl_sf_hyperg_2F1_conj_e(const double aR, const double aI, const double c, const double x, gsl_sf_result * result); double gsl_sf_hyperg_2F1_conj(double aR, double aI, double c, double x); /* Renormalized Gauss hypergeometric function * 2F1[a,b,c,x] / Gamma[c] * |x| < 1 * * exceptions: */ int gsl_sf_hyperg_2F1_renorm_e(const double a, const double b, const double c, const double x, gsl_sf_result * result); double gsl_sf_hyperg_2F1_renorm(double a, double b, double c, double x); /* Renormalized Gauss hypergeometric function * 2F1[aR + I aI, aR - I aI, c, x] / Gamma[c] * |x| < 1 * * exceptions: */ int gsl_sf_hyperg_2F1_conj_renorm_e(const double aR, const double aI, const double c, const double x, gsl_sf_result * result); double gsl_sf_hyperg_2F1_conj_renorm(double aR, double aI, double c, double x); /* Mysterious hypergeometric function. The series representation * is a divergent hypergeometric series. However, for x < 0 we * have 2F0(a,b,x) = (-1/x)^a U(a,1+a-b,-1/x) * * exceptions: GSL_EDOM */ int gsl_sf_hyperg_2F0_e(const double a, const double b, const double x, gsl_sf_result * result); double gsl_sf_hyperg_2F0(const double a, const double b, const double x); __END_DECLS #endif /* __GSL_SF_HYPERG_H__ */
{ "alphanum_fraction": 0.7197254815, "avg_line_length": 29.1419354839, "ext": "h", "hexsha": "8366b88d04cd3c1048dd0f64711508bc92b33703", "lang": "C", "max_forks_count": 30, "max_forks_repo_forks_event_max_datetime": "2021-03-30T23:53:15.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-01T15:12:21.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/gsl_sf_hyperg.h", "max_issues_count": 11, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2022-02-07T08:59:52.000Z", "max_issues_repo_issues_event_min_datetime": "2020-05-29T16:26:06.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/gsl_sf_hyperg.h", "max_line_length": 126, "max_stars_count": 77, "max_stars_repo_head_hexsha": "3eb0cf4b8fcfa2c36e133e4df2b2a3e6d2d3e589", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "shi-bash-cmd/qtTest", "max_stars_repo_path": "315/gsltest/gsl/include/gsl/gsl_sf_hyperg.h", "max_stars_repo_stars_event_max_datetime": "2020-12-24T22:20:56.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-18T00:45:00.000Z", "num_tokens": 1352, "size": 4517 }
#pragma once #include <gsl/span> namespace std { using gsl::span; } // namespace std
{ "alphanum_fraction": 0.6818181818, "avg_line_length": 11, "ext": "h", "hexsha": "017ff56b5374c87a700df055eb9bcdc7583ace4c", "lang": "C", "max_forks_count": 7, "max_forks_repo_forks_event_max_datetime": "2022-01-23T00:37:50.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-28T02:16:25.000Z", "max_forks_repo_head_hexsha": "f041db04bd369d9bd7a617b48892338fc11c090c", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ut-osa/nightcore", "max_forks_repo_path": "src/base/std_span_polyfill.h", "max_issues_count": 5, "max_issues_repo_head_hexsha": "f041db04bd369d9bd7a617b48892338fc11c090c", "max_issues_repo_issues_event_max_datetime": "2021-11-15T17:41:01.000Z", "max_issues_repo_issues_event_min_datetime": "2021-04-16T05:08:10.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ut-osa/nightcore", "max_issues_repo_path": "src/base/std_span_polyfill.h", "max_line_length": 19, "max_stars_count": 34, "max_stars_repo_head_hexsha": "f041db04bd369d9bd7a617b48892338fc11c090c", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ut-osa/nightcore", "max_stars_repo_path": "src/base/std_span_polyfill.h", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:48:49.000Z", "max_stars_repo_stars_event_min_datetime": "2021-01-18T17:19:11.000Z", "num_tokens": 23, "size": 88 }
#include <gsl/gsl_interp.h> #include <unistd.h> #include <stdio.h> int main(int argc, char const *argv[]) { double x = 4096.0; int iterations = 1500; for(int i=0; i<iterations; i++){ printf("%lf\n",x); gsl_ieee_printf_double(&x); printf("---------\n"); x = x/2; } return 0; }
{ "alphanum_fraction": 0.5742574257, "avg_line_length": 18.9375, "ext": "c", "hexsha": "8fd6d00bea719bef080e6609fb82414bc4790e69", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2019-05-29T10:19:18.000Z", "max_forks_repo_forks_event_min_datetime": "2019-04-10T09:35:51.000Z", "max_forks_repo_head_hexsha": "d2a492d210d3acfa1246de82c4a9b818956b4271", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "mprzewie/MOwNiT_2", "max_forks_repo_path": "lab1/3_gsl/gsl_tryout.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "d2a492d210d3acfa1246de82c4a9b818956b4271", "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": "mprzewie/MOwNiT_2", "max_issues_repo_path": "lab1/3_gsl/gsl_tryout.c", "max_line_length": 40, "max_stars_count": null, "max_stars_repo_head_hexsha": "d2a492d210d3acfa1246de82c4a9b818956b4271", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "mprzewie/MOwNiT_2", "max_stars_repo_path": "lab1/3_gsl/gsl_tryout.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 100, "size": 303 }
#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_SIZELIMIT #undef MPI_Sendrecv int MPI_Sizelimited_Sendrecv(void *sendbuf, int sendcount, MPI_Datatype sendtype, int dest, int sendtag, void *recvbuf, int recvcount, MPI_Datatype recvtype, int source, int recvtag, MPI_Comm comm, MPI_Status * status) { int iter = 0, size_sendtype, size_recvtype, send_now, recv_now; int count_limit; if(dest != source) endrun(3); MPI_Type_size(sendtype, &size_sendtype); MPI_Type_size(recvtype, &size_recvtype); if(dest == ThisTask) { memcpy(recvbuf, sendbuf, recvcount * size_recvtype); return 0; } count_limit = (int) ((((long long) MPISENDRECV_SIZELIMIT) * 1024 * 1024) / size_sendtype); while(sendcount > 0 || recvcount > 0) { if(sendcount > count_limit) { send_now = count_limit; if(iter == 0) { printf("imposing size limit on MPI_Sendrecv() on task=%d (send of size=%d)\n", ThisTask, sendcount * size_sendtype); fflush(stdout); } iter++; } else send_now = sendcount; if(recvcount > count_limit) recv_now = count_limit; else recv_now = recvcount; MPI_Sendrecv(sendbuf, send_now, sendtype, dest, sendtag, recvbuf, recv_now, recvtype, source, recvtag, comm, status); sendcount -= send_now; recvcount -= recv_now; sendbuf += send_now * size_sendtype; recvbuf += recv_now * size_recvtype; } return 0; } #endif
{ "alphanum_fraction": 0.6557478368, "avg_line_length": 21.5733333333, "ext": "c", "hexsha": "56566cb13abba1f5339b40e9c8c42c585bf14256", "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/sizelimited_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/sizelimited_sendrecv.c", "max_line_length": 92, "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/sizelimited_sendrecv.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 458, "size": 1618 }
/* * Copyright <2012> <Vincent Le Guilloux,Peter Schmidtke, Pierre Tuffery> * Copyright <2013-2018> <Peter Schmidtke, Vincent Le Guilloux> 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 DH_UTILS #define DH_UTILS /* ------------------------------ INCLUDES ---------------------------------- */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <limits.h> #include <time.h> #ifndef _WIN32 #include <unistd.h> #endif #ifdef MD_USE_GSL /* GSL */ #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #endif /* /GSL */ #include "memhandler.h" /* ------------------------------- PUBLIC MACROS ---------------------------- */ #define M_MAX_PDB_NAME_LEN 200 /**< maximum pdb filename length*/ #define M_SIGN 1 #define M_NO_SIGN 0 #ifdef MD_USE_GSL /* GSL */ #define M_GEN_MTWISTER gsl_rng_mt19937 #define M_GEN_GFSR4 gsl_rng_gfsr4 #define M_GEN_TAUS gsl_rng_taus2 #define M_GEN_RANLXS0 gsl_rng_ranlxs0 #define M_GEN_RANLXS1 gsl_rng_ranlxs1 #endif /* /GSL */ /* ------------------------------ PUBLIC STRUCTURES ------------------------- */ typedef struct tab_str { char **t_str ; int nb_str ; } tab_str ; /* ------------------------------- PROTOTYPES ------------------------------- */ int str_is_number(const char *str, const int sign) ; int str_is_float(const char *str, const int sign) ; void str_trim(char *str) ; tab_str* str_split(const char *str, const int sep) ; short file_exists(const char * filename); tab_str* f_readl(const char *fpath, int nchar_max) ; void free_tab_str(tab_str *tstr) ; void print_tab_str(tab_str* strings) ; int in_tab(int *tab, int size, int val) ; int index_of(int *tab, int size, int val) ; void remove_ext(char *str) ; void remove_path(char *str) ; void extract_ext(char *str, char *dest) ; void extract_path(char *str, char *dest) ; void start_rand_generator(void) ; float rand_uniform(float min, float max) ; FILE* fopen_pdb_check_case(char *name, const char *mode) ; float float_get_min_in_2D_array(float **t,size_t n,int col); float float_get_max_in_2D_array(float **t,size_t n,int col); #endif
{ "alphanum_fraction": 0.6941935484, "avg_line_length": 31.9587628866, "ext": "h", "hexsha": "af89a317dbd16256627a319653e7aa381882cc0c", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-06-23T09:48:16.000Z", "max_forks_repo_forks_event_min_datetime": "2021-06-23T09:48:16.000Z", "max_forks_repo_head_hexsha": "1ce0f6040e141c8279b50707913593d69d4addf1", "max_forks_repo_licenses": [ "Qhull", "MIT" ], "max_forks_repo_name": "kencresset/fpocket", "max_forks_repo_path": "headers/utils.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "1ce0f6040e141c8279b50707913593d69d4addf1", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Qhull", "MIT" ], "max_issues_repo_name": "kencresset/fpocket", "max_issues_repo_path": "headers/utils.h", "max_line_length": 460, "max_stars_count": null, "max_stars_repo_head_hexsha": "1ce0f6040e141c8279b50707913593d69d4addf1", "max_stars_repo_licenses": [ "Qhull", "MIT" ], "max_stars_repo_name": "kencresset/fpocket", "max_stars_repo_path": "headers/utils.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 738, "size": 3100 }
// // trmm.h // Linear Algebra Template Library // // Created by Rodney James on 1/4/12. // Copyright (c) 2012 University of Colorado Denver. All rights reserved. // #ifndef _trmm_h #define _trmm_h /// @file trmm.h Performs multiplication of a triangular matrix with a rectangular matrix. #include <cctype> #include "latl.h" namespace LATL { /// @brief Performs multiplication of a real triangular matrix with a real rectangular matrix. /// /// For a real upper or lower triangular matrix A, real rectangular matrix B and real scalar alpha, /// /// B := alpha*A*B or B := alpha*A'*B or B := alpha*B*A or B := alpha*B*A' /// is computed. /// @return 0 if success. /// @return -i if the ith argument is invalid. /// @tparam real_t Floating point type. /// @param side Specifies whether the matrix A appears on the left or right side as follows: /// /// if side = 'L' or 'l' then B := alpha*A*B or alpha*A'*B /// if side = 'R' or 'r' then C := alpha*B*A or alpha*B*A' /// @param uplo Specifies whether A is stored as upper or lower triangular. /// /// if uplo = 'U' or 'u' then A is upper triangular /// if uplo = 'L' or 'l' then A is lower triangular /// @param trans Specifies wheather the transpose of A is to be used or not: /// /// if trans = 'N' or 'n' then B := alpha*A*B or alpha*B*A /// if trans = 'T' or 't' then B := alpha*A'*B or alpha*B*A' /// if trans = 'C' or 'c' then B := alpha*A'*B or alpha*B*A' /// @param diag specifies whether or not A is unit triangular as follows: /// /// if diag = 'U' or 'u' then A is assumed to be unit triangular /// if diag = 'N' or 'n' then A is not assumed to be unit triangular. /// If A is unit triangular, the diagonal elements are assumed to be unity and are not referenced. /// @param m Specifies the number of rows of the matrix B. m>=0 /// @param n Specifies the number of columns of the matrix B. n>=0 /// @param alpha Real scalar. /// @param A Pointer to real triangular matrix A. The order of A is n if side = 'L' or 'l'; /// the order of A is m is side = 'R' or 'r'. /// If uplo = 'U' or 'u, A is upper triangular and the lower triangular part is not referenced. /// If uplo = 'L' or 'l A is lower triangular and the upper triangular part is not referenced. /// @param ldA Column length of the matrix A. If side='L' or 'l' then ldA>=n; if side='R' or 'r' then lda>=m. /// @param B Pointer to real m-by-n matrix B. /// @param ldB Column length of the matrix B. ldB>=m. /// @ingroup BLAS template <typename real_t> int TRMM(char side, char uplo, char trans, char diag, int_t m, int_t n, real_t alpha, real_t *A, int_t ldA, real_t *B, int_t ldB) { using std::toupper; const real_t zero(0.0); int_t i,j,k; real_t *a,*b,*bt; real_t t; side=toupper(side); uplo=toupper(uplo); trans=toupper(trans); diag=toupper(diag); if((side!='L')&&(side!='R')) return -1; else if((uplo!='U')&&(uplo!='L')) return -2; else if((trans!='N')&&(trans!='T')&&(trans!='C')) return -3; else if((diag!='U')&&(diag!='N')) return -4; else if(m<0) return -5; else if(n<0) return -6; else if(ldA<((side=='L')?m:n)) return -9; else if(ldB<m) return -11; else if((m==0)||(n==0)) return 0; bool nounit=(diag=='N')?1:0; if(alpha==zero) { b=B; for(j=0;j<n;j++) { for(i=0;i<m;i++) b[i]=zero; b+=ldB; } } else if(side=='L') { if(trans=='N') { if(uplo=='U') { b=B; for(j=0;j<n;j++) { a=A; for(k=0;k<m;k++) { t=alpha*b[k]; for(i=0;i<k;i++) b[i]+=t*a[i]; if(nounit) t*=a[k]; b[k]=t; a+=ldA; } b+=ldB; } } else { b=B; for(j=0;j<n;j++) { a=A+m*ldA; for(k=m-1;k>=0;k--) { a-=ldA; t=alpha*b[k]; b[k]=t; if(nounit) b[k]*=a[k]; for(i=k+1;i<m;i++) b[i]+=t*a[i]; } b+=ldB; } } } else { if(uplo=='U') { b=B; for(j=0;j<n;j++) { a=A+m*ldA; for(i=m-1;i>=0;i--) { a-=ldA; t=b[i]; if(nounit) t*=a[i]; for(k=0;k<i;k++) t+=a[k]*b[k]; b[i]=alpha*t; } b+=ldB; } } else { b=B; for(j=0;j<n;j++) { a=A; for(i=0;i<m;i++) { t=b[i]; if(nounit) t*=a[i]; for(k=i+1;k<m;k++) t+=a[k]*b[k]; b[i]=alpha*t; a+=ldA; } b+=ldB; } } } } else { if(trans=='N') { if(uplo=='U') { a=A+n*ldA; b=B+n*ldB; for(j=n-1;j>=0;j--) { a-=ldA; b-=ldB; if(nounit) t=alpha*a[j]; else t=alpha; for(i=0;i<m;i++) b[i]*=t; bt=B; for(k=0;k<j;k++) { t=alpha*a[k]; for(i=0;i<m;i++) b[i]+=t*bt[i]; bt+=ldB; } } } else { a=A; b=B; for(j=0;j<n;j++) { if(nounit) t=alpha*a[j]; else t=alpha; for(i=0;i<m;i++) b[i]*=t; bt=b+ldB; for(k=j+1;k<n;k++) { t=alpha*a[k]; for(i=0;i<m;i++) b[i]+=t*bt[i]; bt+=ldB; } a+=ldA; b+=ldB; } } } else { if(uplo=='U') { a=A; bt=B; for(k=0;k<n;k++) { b=B; for(j=0;j<k;j++) { t=alpha*a[j]; for(i=0;i<m;i++) b[i]+=t*bt[i]; b+=ldB; } if(nounit) t=alpha*a[k]; else t=alpha; for(i=0;i<m;i++) b[i]*=t; a+=ldA; bt+=ldB; } } else { a=A+n*ldA; bt=B+n*ldB; for(k=n-1;k>=0;k--) { a-=ldA; bt-=ldB; b=B+(k+1)*ldB; for(j=k+1;j<n;j++) { t=alpha*a[j]; for(i=0;i<m;i++) b[i]+=t*bt[i]; b+=ldB; } if(nounit) t=alpha*a[k]; else t=alpha; for(i=0;i<m;i++) bt[i]*=t; } } } } return 0; } /// @brief Performs multiplication of a complex triangular matrix with a complex rectangular matrix. /// /// For a complex upper or lower triangular matrix A, complex rectangular matrix B and complex scalar alpha, /// /// B:=alpha*A*B or B:=alpha*A'*B or B:=alpha*A.'*B or B:=alpha*B*A or B:=alpha*B*A' or B:=alpha*B*A.' /// is computed. /// @return 0 if success. /// @return -i if the ith argument is invalid. /// @tparam real_t Floating point type. /// @param side Specifies whether the matrix A appears on the left or right side as follows: /// /// if side = 'L' or 'l' then B := alpha*A*B or alpha*A'*B or alpha*A.'*B /// if side = 'R' or 'r' then C := alpha*B*A or alpha*B*A' or alpha*B*A.' /// @param uplo Specifies whether A is stored as upper or lower triangular. /// /// if uplo = 'U' or 'u' then A is upper triangular /// if uplo = 'L' or 'l' then A is lower triangular /// @param trans Specifies wheather the transpose or conjugate transpose is applied to A as follows: /// /// if trans = 'N' or 'n' then B := alpha*A*B or alpha*B*A /// if trans = 'T' or 't' then B := alpha*A.'*B or alpha*B*A.' /// if trans = 'C' or 'c' then B := alpha*A'*B or alpha*B*A' /// @param diag specifies whether or not A is unit triangular as follows: /// /// if diag = 'U' or 'u' then A is assumed to be unit triangular /// if diag = 'N' or 'n' then A is not assumed to be unit triangular. /// If A is unit triangular, the diagonal elements are assumed to be unity and are not referenced. /// @param m Specifies the number of rows of the matrix B. m>=0 /// @param n Specifies the number of columns of the matrix B. n>=0 /// @param alpha Complex scalar. /// @param A Pointer to complex triangular matrix A. The order of A is n if side = 'L' or 'l'; /// the order of A is m is side = 'R' or 'r'. /// If uplo = 'U' or 'u, A is upper triangular and the lower triangular part is not referenced. /// If uplo = 'L' or 'l A is lower triangular and the upper triangular part is not referenced. /// @param ldA Column length of the matrix A. If side='L' or 'l' then ldA>=n; if side='R' or 'r' then lda>=m. /// @param B Pointer to complex m-by-n matrix B. /// @param ldB Column length of the matrix B. ldB>=m. /// @ingroup BLAS template <typename real_t> int TRMM(char side, char uplo, char trans, char diag, int_t m, int_t n, complex<real_t> alpha, complex<real_t> *A, int_t ldA, complex<real_t> *B, int_t ldB) { using std::conj; using std::toupper; const complex<real_t> zero(0.0,0.0); int_t i,j,k; complex<real_t> *a,*b,*bt; complex<real_t> t; side=toupper(side); uplo=toupper(uplo); trans=toupper(trans); diag=toupper(diag); if((side!='L')&&(side!='R')) return -1; else if((uplo!='U')&&(uplo!='L')) return -2; else if((trans!='N')&&(trans!='T')&&(trans!='C')) return -3; else if((diag!='U')&&(diag!='N')) return -4; else if(m<0) return -5; else if(n<0) return -6; else if(ldA<((side=='L')?m:n)) return -9; else if(ldB<m) return -11; else if((m==0)||(n==0)) return 0; bool nounit=(diag=='N')?1:0; if(alpha==zero) { b=B; for(j=0;j<n;j++) { for(i=0;i<m;i++) b[i]=zero; b+=ldB; } } else if(side=='L') { if(trans=='N') { if(uplo=='U') { b=B; for(j=0;j<n;j++) { a=A; for(k=0;k<m;k++) { t=alpha*b[k]; for(i=0;i<k;i++) b[i]+=t*a[i]; if(nounit) t*=a[k]; b[k]=t; a+=ldA; } b+=ldB; } } else { b=B; for(j=0;j<n;j++) { a=A+m*ldA; for(k=m-1;k>=0;k--) { a-=ldA; t=alpha*b[k]; b[k]=t; if(nounit) b[k]*=a[k]; for(i=k+1;i<m;i++) b[i]+=t*a[i]; } b+=ldB; } } } else if(trans=='T') { if(uplo=='U') { b=B; for(j=0;j<n;j++) { a=A+m*ldA; for(i=m-1;i>=0;i--) { a-=ldA; t=b[i]; if(nounit) t*=a[i]; for(k=0;k<i;k++) t+=a[k]*b[k]; b[i]=alpha*t; } b+=ldB; } } else { b=B; for(j=0;j<n;j++) { a=A; for(i=0;i<m;i++) { t=b[i]; if(nounit) t*=a[i]; for(k=i+1;k<m;k++) t+=a[k]*b[k]; b[i]=alpha*t; a+=ldA; } b+=ldB; } } } else if(trans=='C') { if(uplo=='U') { b=B; for(j=0;j<n;j++) { a=A+m*ldA; for(i=m-1;i>=0;i--) { a-=ldA; t=b[i]; if(nounit) t*=conj(a[i]); for(k=0;k<i;k++) t+=conj(a[k])*b[k]; b[i]=alpha*t; } b+=ldB; } } else { b=B; for(j=0;j<n;j++) { a=A; for(i=0;i<m;i++) { t=b[i]; if(nounit) t*=conj(a[i]); for(k=i+1;k<m;k++) t+=conj(a[k])*b[k]; b[i]=alpha*t; a+=ldA; } b+=ldB; } } } } else { if(trans=='N') { if(uplo=='U') { a=A+n*ldA; b=B+n*ldB; for(j=n-1;j>=0;j--) { a-=ldA; b-=ldB; if(nounit) t=alpha*a[j]; else t=alpha; for(i=0;i<m;i++) b[i]*=t; bt=B; for(k=0;k<j;k++) { t=alpha*a[k]; for(i=0;i<m;i++) b[i]+=t*bt[i]; bt+=ldB; } } } else { a=A; b=B; for(j=0;j<n;j++) { if(nounit) t=alpha*a[j]; else t=alpha; for(i=0;i<m;i++) b[i]*=t; bt=b+ldB; for(k=j+1;k<n;k++) { t=alpha*a[k]; for(i=0;i<m;i++) b[i]+=t*bt[i]; bt+=ldB; } a+=ldA; b+=ldB; } } } else if(trans=='T') { if(uplo=='U') { a=A; bt=B; for(k=0;k<n;k++) { b=B; for(j=0;j<k;j++) { t=alpha*a[j]; for(i=0;i<m;i++) b[i]+=t*bt[i]; b+=ldB; } if(nounit) t=alpha*a[k]; else t=alpha; for(i=0;i<m;i++) b[i]*=t; a+=ldA; bt+=ldB; } } else { a=A+n*ldA; bt=B+n*ldB; for(k=n-1;k>=0;k--) { a-=ldA; bt-=ldB; b=B+(k+1)*ldB; for(j=k+1;j<n;j++) { t=alpha*a[j]; for(i=0;i<m;i++) b[i]+=t*bt[i]; b+=ldB; } if(nounit) t=alpha*a[k]; else t=alpha; for(i=0;i<m;i++) bt[i]*=t; } } } else if(trans=='C') { if(uplo=='U') { a=A; bt=B; for(k=0;k<n;k++) { b=B; for(j=0;j<k;j++) { t=alpha*conj(a[j]); for(i=0;i<m;i++) b[i]+=t*bt[i]; b+=ldB; } if(nounit) t=alpha*conj(a[k]); else t=alpha; for(i=0;i<m;i++) b[i]*=t; a+=ldA; bt+=ldB; } } else { a=A+n*ldA; bt=B+n*ldB; for(k=n-1;k>=0;k--) { a-=ldA; bt-=ldB; b=B+(k+1)*ldB; for(j=k+1;j<n;j++) { t=alpha*conj(a[j]); for(i=0;i<m;i++) b[i]+=t*bt[i]; b+=ldB; } if(nounit) t=alpha*conj(a[k]); else t=alpha; for(i=0;i<m;i++) bt[i]*=t; } } } } return 0; } #ifdef __latl_cblas #include <cblas.h> template <> int TRMM<float>(char side, char uplo, char trans, char diag, int_t m, int_t n, float alpha, float *A, int_t ldA, float *B, int_t ldB) { using std::toupper; side=toupper(side); uplo=toupper(uplo); trans=toupper(trans); diag=toupper(diag); if((side!='L')&&(side!='R')) return -1; else if((uplo!='U')&&(uplo!='L')) return -2; else if((trans!='N')&&(trans!='T')&&(trans!='C')) return -3; else if((diag!='U')&&(diag!='N')) return -4; else if(m<0) return -5; else if(n<0) return -6; else if(ldA<((side=='L')?m:n)) return -9; else if(ldB<m) return -11; else if((m==0)||(n==0)) return 0; const CBLAS_SIDE Side=(side=='L')?CblasLeft:CblasRight; const CBLAS_UPLO Uplo=(uplo=='U')?CblasUpper:CblasLower; const CBLAS_DIAG Diag=(diag=='N')?CblasNonUnit:CblasUnit; const CBLAS_TRANSPOSE Trans=(trans=='N')?CblasNoTrans:CblasTrans; cblas_strmm(CblasColMajor,Side,Uplo,Trans,Diag,m,n,alpha,A,ldA,B,ldB); return 0; } template <> int TRMM<double>(char side, char uplo, char trans, char diag, int_t m, int_t n, double alpha, double *A, int_t ldA, double *B, int_t ldB) { using std::toupper; side=toupper(side); uplo=toupper(uplo); trans=toupper(trans); diag=toupper(diag); if((side!='L')&&(side!='R')) return -1; else if((uplo!='U')&&(uplo!='L')) return -2; else if((trans!='N')&&(trans!='T')&&(trans!='C')) return -3; else if((diag!='U')&&(diag!='N')) return -4; else if(m<0) return -5; else if(n<0) return -6; else if(ldA<((side=='L')?m:n)) return -9; else if(ldB<m) return -11; else if((m==0)||(n==0)) return 0; const CBLAS_SIDE Side=(side=='L')?CblasLeft:CblasRight; const CBLAS_UPLO Uplo=(uplo=='U')?CblasUpper:CblasLower; const CBLAS_DIAG Diag=(diag=='N')?CblasNonUnit:CblasUnit; const CBLAS_TRANSPOSE Trans=(trans=='N')?CblasNoTrans:CblasTrans; cblas_dtrmm(CblasColMajor,Side,Uplo,Trans,Diag,m,n,alpha,A,ldA,B,ldB); return 0; } template <> int TRMM<float>(char side, char uplo, char trans, char diag, int_t m, int_t n, complex<float> alpha, complex<float> *A, int_t ldA, complex<float> *B, int_t ldB) { using std::toupper; side=toupper(side); uplo=toupper(uplo); trans=toupper(trans); diag=toupper(diag); if((side!='L')&&(side!='R')) return -1; else if((uplo!='U')&&(uplo!='L')) return -2; else if((trans!='N')&&(trans!='T')&&(trans!='C')) return -3; else if((diag!='U')&&(diag!='N')) return -4; else if(m<0) return -5; else if(n<0) return -6; else if(ldA<((side=='L')?m:n)) return -9; else if(ldB<m) return -11; else if((m==0)||(n==0)) return 0; const CBLAS_SIDE Side=(side=='L')?CblasLeft:CblasRight; const CBLAS_UPLO Uplo=(uplo=='U')?CblasUpper:CblasLower; const CBLAS_DIAG Diag=(diag=='N')?CblasNonUnit:CblasUnit; const CBLAS_TRANSPOSE Trans=(trans=='N')?CblasNoTrans:((trans=='T')?CblasTrans:CblasConjTrans); cblas_ctrmm(CblasColMajor,Side,Uplo,Trans,Diag,m,n,&alpha,A,ldA,B,ldB); return 0; } template <> int TRMM<double>(char side, char uplo, char trans, char diag, int_t m, int_t n, complex<double> alpha, complex<double> *A, int_t ldA, complex<double> *B, int_t ldB) { using std::toupper; side=toupper(side); uplo=toupper(uplo); trans=toupper(trans); diag=toupper(diag); if((side!='L')&&(side!='R')) return -1; else if((uplo!='U')&&(uplo!='L')) return -2; else if((trans!='N')&&(trans!='T')&&(trans!='C')) return -3; else if((diag!='U')&&(diag!='N')) return -4; else if(m<0) return -5; else if(n<0) return -6; else if(ldA<((side=='L')?m:n)) return -9; else if(ldB<m) return -11; else if((m==0)||(n==0)) return 0; const CBLAS_SIDE Side=(side=='L')?CblasLeft:CblasRight; const CBLAS_UPLO Uplo=(uplo=='U')?CblasUpper:CblasLower; const CBLAS_DIAG Diag=(diag=='N')?CblasNonUnit:CblasUnit; const CBLAS_TRANSPOSE Trans=(trans=='N')?CblasNoTrans:((trans=='T')?CblasTrans:CblasConjTrans); cblas_ztrmm(CblasColMajor,Side,Uplo,Trans,Diag,m,n,&alpha,A,ldA,B,ldB); return 0; } #endif } #endif
{ "alphanum_fraction": 0.3579980942, "avg_line_length": 29.4353658537, "ext": "h", "hexsha": "f3124443bdf186f698383fc97bce95f3241d552d", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2022-02-09T23:18:24.000Z", "max_forks_repo_forks_event_min_datetime": "2019-02-01T06:46:36.000Z", "max_forks_repo_head_hexsha": "df838fb44a1ef5c77b57bf60bd46eaeff8db3492", "max_forks_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_forks_repo_name": "langou/latl", "max_forks_repo_path": "include/trmm.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "df838fb44a1ef5c77b57bf60bd46eaeff8db3492", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_issues_repo_name": "langou/latl", "max_issues_repo_path": "include/trmm.h", "max_line_length": 179, "max_stars_count": 6, "max_stars_repo_head_hexsha": "df838fb44a1ef5c77b57bf60bd46eaeff8db3492", "max_stars_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_stars_repo_name": "langou/latl", "max_stars_repo_path": "include/trmm.h", "max_stars_repo_stars_event_max_datetime": "2022-02-09T23:18:22.000Z", "max_stars_repo_stars_event_min_datetime": "2015-12-13T09:10:11.000Z", "num_tokens": 6153, "size": 24137 }
/* specfunc/bessel_I0.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 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 */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include "gsl_sf_bessel.h" #include "error.h" #include "chebyshev.h" #include "cheb_eval.c" /*-*-*-*-*-*-*-*-*-*-*-* Private Section *-*-*-*-*-*-*-*-*-*-*-*/ /* based on SLATEC besi0 */ /* chebyshev expansions series for bi0 on the interval 0. to 9.00000d+00 with weighted error 2.46e-18 log weighted error 17.61 significant figures required 17.90 decimal places required 18.15 series for ai0 on the interval 1.25000d-01 to 3.33333d-01 with weighted error 7.87e-17 log weighted error 16.10 significant figures required 14.69 decimal places required 16.76 series for ai02 on the interval 0. to 1.25000d-01 with weighted error 3.79e-17 log weighted error 16.42 significant figures required 14.86 decimal places required 17.09 */ static double bi0_data[12] = { -.07660547252839144951, 1.92733795399380827000, .22826445869203013390, .01304891466707290428, .00043442709008164874, .00000942265768600193, .00000014340062895106, .00000000161384906966, .00000000001396650044, .00000000000009579451, .00000000000000053339, .00000000000000000245 }; static cheb_series bi0_cs = { bi0_data, 11, -1, 1, 11 }; static double ai0_data[21] = { .07575994494023796, .00759138081082334, .00041531313389237, .00001070076463439, -.00000790117997921, -.00000078261435014, .00000027838499429, .00000000825247260, -.00000001204463945, .00000000155964859, .00000000022925563, -.00000000011916228, .00000000001757854, .00000000000112822, -.00000000000114684, .00000000000027155, -.00000000000002415, -.00000000000000608, .00000000000000314, -.00000000000000071, .00000000000000007 }; static cheb_series ai0_cs = { ai0_data, 20, -1, 1, 13 }; static double ai02_data[22] = { .05449041101410882, .00336911647825569, .00006889758346918, .00000289137052082, .00000020489185893, .00000002266668991, .00000000339623203, .00000000049406022, .00000000001188914, -.00000000003149915, -.00000000001321580, -.00000000000179419, .00000000000071801, .00000000000038529, .00000000000001539, -.00000000000004151, -.00000000000000954, .00000000000000382, .00000000000000176, -.00000000000000034, -.00000000000000027, .00000000000000003 }; static cheb_series ai02_cs = { ai02_data, 21, -1, 1, 11 }; /*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/ int gsl_sf_bessel_I0_scaled_e(const double x, gsl_sf_result * result) { double y = fabs(x); /* CHECK_POINTER(result) */ if(y < 2.0 * GSL_SQRT_DBL_EPSILON) { result->val = 1.0 - y; result->err = 0.5*y*y; return GSL_SUCCESS; } else if(y <= 3.0) { const double ey = exp(-y); gsl_sf_result c; cheb_eval_e(&bi0_cs, y*y/4.5-1.0, &c); result->val = ey * (2.75 + c.val); result->err = GSL_DBL_EPSILON * fabs(result->val) + ey * c.err; return GSL_SUCCESS; } else if(y <= 8.0) { const double sy = sqrt(y); gsl_sf_result c; cheb_eval_e(&ai0_cs, (48.0/y-11.0)/5.0, &c); result->val = (0.375 + c.val) / sy; result->err = 2.0 * GSL_DBL_EPSILON * (0.375 + fabs(c.val)) / sy; result->err += c.err / sy; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else { const double sy = sqrt(y); gsl_sf_result c; cheb_eval_e(&ai02_cs, 16.0/y-1.0, &c); result->val = (0.375 + c.val) / sy; result->err = 2.0 * GSL_DBL_EPSILON * (0.375 + fabs(c.val)) / sy; result->err += c.err / sy; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } } int gsl_sf_bessel_I0_e(const double x, gsl_sf_result * result) { double y = fabs(x); /* CHECK_POINTER(result) */ if(y < 2.0 * GSL_SQRT_DBL_EPSILON) { result->val = 1.0; result->err = 0.5*y*y; return GSL_SUCCESS; } else if(y <= 3.0) { gsl_sf_result c; cheb_eval_e(&bi0_cs, y*y/4.5-1.0, &c); result->val = 2.75 + c.val; result->err = GSL_DBL_EPSILON * (2.75 + fabs(c.val)); result->err += c.err; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else if(y < GSL_LOG_DBL_MAX - 1.0) { const double ey = exp(y); gsl_sf_result b_scaled; gsl_sf_bessel_I0_scaled_e(x, &b_scaled); result->val = ey * b_scaled.val; result->err = ey * b_scaled.err + y*GSL_DBL_EPSILON*fabs(result->val); result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else { OVERFLOW_ERROR(result); } } /*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/ #include "eval.h" double gsl_sf_bessel_I0_scaled(const double x) { EVAL_RESULT(gsl_sf_bessel_I0_scaled_e(x, &result); ) } double gsl_sf_bessel_I0(const double x) { EVAL_RESULT(gsl_sf_bessel_I0_e(x, &result); ) }
{ "alphanum_fraction": 0.6489434219, "avg_line_length": 25.1845493562, "ext": "c", "hexsha": "3fe0c64f94896a96584cc3039f6418c0d72fcc0a", "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/bessel_I0.c", "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/bessel_I0.c", "max_line_length": 76, "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/bessel_I0.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": 2024, "size": 5868 }
#include <stdio.h> #include <math.h> #include <stdlib.h> #include <lapacke.h> #define ABS(a) (((a) < 0) ? -(a) : (a)) int main() { /* * hbar^2/2m = 1 */ static double pi = M_PI; int n, npw; double v0, a, b, ecut, k; double *g, *e, *h, *wrk; int i, j, ij, m, lwork, info, p; char *V = "V"; char *U = "U"; FILE *out; /* Input data Potential: V(x)=-V_0 for |x|<b/2, V(x)=0 for |x|>b/2 Periodicity: V(x+a)=V(x) */ fprintf(stdout, "Parameters for potential well: V_0, a, b > "); scanf("%lf %lf %lf",&v0, &a, &b); if ( v0 <= 0 || a <= 0 || b <= 0 || a <= b ) { fprintf(stderr, "wrong input parameters\n"); exit(1); } fprintf (stdout," V_0=%f, a0=%f, b=%f\n",v0,a,b); /* Plane waves basis set: G_n=n*2pi/a, \hbar^2/2m*G^2 < Ecut */ fprintf(stdout, "Cutoff for plane waves: ecut > "); scanf("%lf",&ecut); if ( ecut <= 0) { fprintf(stderr, "wrong input parameter\n"); exit(2); } /* Number of plane waves */ npw = (int) ( sqrt ( ecut/pow( 2.0*pi/a, 2) ) + 0.5 ); npw = 2*npw+1; fprintf (stdout," ecut = %f, # of PWs=%d\n",ecut, npw); /* Assign values of G_n: n=0,+1,-1,+2,-2, etc */ n=100; g = (double *) malloc ( npw * sizeof (double) ); e = (double *) malloc ( npw * sizeof (double) ); h = (double *) malloc ( n*n * sizeof (double) ); wrk= (double *) malloc (3*npw* sizeof (double) ); g[0] = 0.0; for ( i = 1; i < npw; i+=2 ) { g[i ] = (i+1)*pi/a; g[i+1] =-(i+1)*pi/a; } for ( ij = 0; ij < n*n; ++ij ) { h[ij] = 0.0; } /* Loop on k-vectors: k runs from -pi/a to pi/a */ out = fopen("bands.out", "w"); for ( m =-n; m <= n; m++ ) { k = m*pi/n/a; /* Assign values of the matrix elements of the hamiltonian on the plane wave basis */ ij = 0; for ( i = 0; i < npw; ++i ) { for ( j = 0; j < npw; ++j ) { /* NOTA BENE: the matrix h is a vector in the calling program, while dsyev expects a (pointer to a) fortran matrix. A fortran matrix is "simulated" in the following way: if h[ij] is the C array and h(i,j) is a N*M Fortran matrix, h[ij] == h(i,j), where ij = (j-1)*N + (i-1) (i=1,N, j=1,M) */ if ( i == j ) { h[ij++] = (k+g[i])*(k+g[i]) - v0/a*b; } else { h[ij++] = -v0/a * sin( (g[j]-g[i])*b/2.0 ) / (g[j]-g[i])*2.0; } } } /* Solution [expansion coefficients are stored into h(i,j) j=basis function index, i= eigenvalue index] (beware fortran-C reversed index convention!) */ lwork = 3*npw; dsyev_ ( V, U, &npw, h, &npw, e, wrk, &lwork, &info ); if ( info != 0) { fprintf(stderr, "H-matrix diagonalization failed\n"); exit(3); } /*printf("%f ",k); for(p=0; p<npw; p++) printf("%f ",e[p]);printf("\n");*/ fprintf(out,"%12.6f ",k); for(p=0; p<npw; p++) fprintf(out,"%10.6f ",e[p]); fprintf(out,"\n"); } fclose(out); return 0; }
{ "alphanum_fraction": 0.4881627209, "avg_line_length": 24.9916666667, "ext": "c", "hexsha": "3ca18ad6bb18bd137a1956595c76c474859d6723", "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": "992f008c9d6b4ddd242b5d456950c8f2d3d32f4f", "max_forks_repo_licenses": [ "CC0-1.0" ], "max_forks_repo_name": "algebrato/Struttura", "max_forks_repo_path": "Kronig-Penney/Bands.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "992f008c9d6b4ddd242b5d456950c8f2d3d32f4f", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "CC0-1.0" ], "max_issues_repo_name": "algebrato/Struttura", "max_issues_repo_path": "Kronig-Penney/Bands.c", "max_line_length": 69, "max_stars_count": null, "max_stars_repo_head_hexsha": "992f008c9d6b4ddd242b5d456950c8f2d3d32f4f", "max_stars_repo_licenses": [ "CC0-1.0" ], "max_stars_repo_name": "algebrato/Struttura", "max_stars_repo_path": "Kronig-Penney/Bands.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1175, "size": 2999 }
/* C code for the adiabatic approximation */ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_roots.h> #include <gsl/gsl_min.h> #include <gsl/gsl_integration.h> #ifdef _OPENMP #include <omp.h> #endif #define CHUNKSIZE 10 //Potentials #include <galpy_potentials.h> #include <actionAngle.h> #ifndef M_PI #define M_PI 3.14159265358979323846 #endif /* Structure Declarations */ struct JRAdiabaticArg{ double ER; double Lz22; int nargs; struct potentialArg * actionAngleArgs; }; struct JzAdiabaticArg{ double Ez; double R; int nargs; struct potentialArg * actionAngleArgs; }; /* Function Declarations */ void actionAngleAdiabatic_actions(int,double *,double *,double *,double *, double *,int,int *,double *,double, double *,double *,int *); void calcJRAdiabatic(int,double *,double *,double *,double *,double *, int,struct potentialArg *,int); void calcJzAdiabatic(int,double *,double *,double *,double *,int, struct potentialArg *,int); void calcRapRperi(int,double *,double *,double *,double *,double *, int,struct potentialArg *); void calcZmax(int,double *,double *,double *,double *,int, struct potentialArg *); double JRAdiabaticIntegrandSquared(double,void *); double JRAdiabaticIntegrand(double,void *); double JzAdiabaticIntegrandSquared(double,void *); double JzAdiabaticIntegrand(double,void *); double evaluateVerticalPotentials(double, double,int, struct potentialArg *); /* Actual functions, inlines first */ inline void calcEREzL(int ndata, double *R, double *vR, double *vT, double *z, double *vz, double *ER, double *Ez, double *Lz, int nargs, struct potentialArg * actionAngleArgs){ int ii; UNUSED int chunk= CHUNKSIZE; #pragma omp parallel for schedule(static,chunk) private(ii) for (ii=0; ii < ndata; ii++){ *(ER+ii)= evaluatePotentials(*(R+ii),0., nargs,actionAngleArgs) + 0.5 * *(vR+ii) * *(vR+ii) + 0.5 * *(vT+ii) * *(vT+ii); *(Ez+ii)= evaluateVerticalPotentials(*(R+ii),*(z+ii), nargs,actionAngleArgs) + 0.5 * *(vz+ii) * *(vz+ii); *(Lz+ii)= *(R+ii) * *(vT+ii); } } /* MAIN FUNCTIONS */ void actionAngleAdiabatic_actions(int ndata, double *R, double *vR, double *vT, double *z, double *vz, int npot, int * pot_type, double * pot_args, double gamma, double *jr, double *jz, int * err){ int ii; //Set up the potentials struct potentialArg * actionAngleArgs= (struct potentialArg *) malloc ( npot * sizeof (struct potentialArg) ); parse_actionAngleArgs(npot,actionAngleArgs,pot_type,pot_args); //ER, Ez, Lz double *ER= (double *) malloc ( ndata * sizeof(double) ); double *Ez= (double *) malloc ( ndata * sizeof(double) ); double *Lz= (double *) malloc ( ndata * sizeof(double) ); calcEREzL(ndata,R,vR,vT,z,vz,ER,Ez,Lz,npot,actionAngleArgs); //Calculate peri and apocenters double *rperi= (double *) malloc ( ndata * sizeof(double) ); double *rap= (double *) malloc ( ndata * sizeof(double) ); double *zmax= (double *) malloc ( ndata * sizeof(double) ); calcZmax(ndata,zmax,z,R,Ez,npot,actionAngleArgs); calcJzAdiabatic(ndata,jz,zmax,R,Ez,npot,actionAngleArgs,10); //Adjust planar effective potential for gamma UNUSED int chunk= CHUNKSIZE; #pragma omp parallel for schedule(static,chunk) private(ii) for (ii=0; ii < ndata; ii++){ *(Lz+ii)= fabs( *(Lz+ii) ) + gamma * *(jz+ii); *(ER+ii)+= 0.5 * *(Lz+ii) * *(Lz+ii) / *(R+ii) / *(R+ii) - 0.5 * *(vT+ii) * *(vT+ii); } calcRapRperi(ndata,rperi,rap,R,ER,Lz,npot,actionAngleArgs); calcJRAdiabatic(ndata,jr,rperi,rap,ER,Lz,npot,actionAngleArgs,10); for (ii=0; ii < npot; ii++) { if ( (actionAngleArgs+ii)->i2d ) interp_2d_free((actionAngleArgs+ii)->i2d) ; if ((actionAngleArgs+ii)->accx ) gsl_interp_accel_free ((actionAngleArgs+ii)->accx); if ((actionAngleArgs+ii)->accy ) gsl_interp_accel_free ((actionAngleArgs+ii)->accy); free((actionAngleArgs+ii)->args); } free(actionAngleArgs); free(ER); free(Ez); free(Lz); free(rperi); free(rap); free(zmax); } void calcJRAdiabatic(int ndata, double * jr, double * rperi, double * rap, double * ER, double * Lz, int nargs, struct potentialArg * actionAngleArgs, int order){ int ii, tid, nthreads; #ifdef _OPENMP nthreads = omp_get_max_threads(); #else nthreads = 1; #endif gsl_function * JRInt= (gsl_function *) malloc ( nthreads * sizeof(gsl_function) ); struct JRAdiabaticArg * params= (struct JRAdiabaticArg *) malloc ( nthreads * sizeof (struct JRAdiabaticArg) ); for (tid=0; tid < nthreads; tid++){ (params+tid)->nargs= nargs; (params+tid)->actionAngleArgs= actionAngleArgs; } //Setup integrator gsl_integration_glfixed_table * T= gsl_integration_glfixed_table_alloc (order); UNUSED int chunk= CHUNKSIZE; #pragma omp parallel for schedule(static,chunk) \ private(tid,ii) \ shared(jr,rperi,rap,JRInt,params,T,ER,Lz) for (ii=0; ii < ndata; ii++){ #ifdef _OPENMP tid= omp_get_thread_num(); #else tid = 0; #endif if ( *(rperi+ii) == -9999.99 || *(rap+ii) == -9999.99 ){ *(jr+ii)= 9999.99; continue; } if ( (*(rap+ii) - *(rperi+ii)) / *(rap+ii) < 0.000001 ){//circular *(jr+ii) = 0.; continue; } //Setup function (params+tid)->ER= *(ER+ii); (params+tid)->Lz22= 0.5 * *(Lz+ii) * *(Lz+ii); (JRInt+tid)->function = &JRAdiabaticIntegrand; (JRInt+tid)->params = params+tid; //Integrate *(jr+ii)= gsl_integration_glfixed (JRInt+tid,*(rperi+ii),*(rap+ii),T) * sqrt(2.) / M_PI; } free(JRInt); free(params); gsl_integration_glfixed_table_free ( T ); } void calcJzAdiabatic(int ndata, double * jz, double * zmax, double * R, double * Ez, int nargs, struct potentialArg * actionAngleArgs, int order){ int ii, tid, nthreads; #ifdef _OPENMP nthreads = omp_get_max_threads(); #else nthreads = 1; #endif gsl_function * JzInt= (gsl_function *) malloc ( nthreads * sizeof(gsl_function) ); struct JzAdiabaticArg * params= (struct JzAdiabaticArg *) malloc ( nthreads * sizeof (struct JzAdiabaticArg) ); for (tid=0; tid < nthreads; tid++){ (params+tid)->nargs= nargs; (params+tid)->actionAngleArgs= actionAngleArgs; } //Setup integrator gsl_integration_glfixed_table * T= gsl_integration_glfixed_table_alloc (order); UNUSED int chunk= CHUNKSIZE; #pragma omp parallel for schedule(static,chunk) \ private(tid,ii) \ shared(jz,zmax,JzInt,params,T,Ez,R) for (ii=0; ii < ndata; ii++){ #ifdef _OPENMP tid= omp_get_thread_num(); #else tid = 0; #endif if ( *(zmax+ii) == -9999.99 ){ *(jz+ii)= 9999.99; continue; } if ( *(zmax+ii) < 0.000001 ){//circular *(jz+ii) = 0.; continue; } //Setup function (params+tid)->Ez= *(Ez+ii); (params+tid)->R= *(R+ii); (JzInt+tid)->function = &JzAdiabaticIntegrand; (JzInt+tid)->params = params+tid; //Integrate *(jz+ii)= gsl_integration_glfixed (JzInt+tid,0.,*(zmax+ii),T) * 2 * sqrt(2.) / M_PI; } free(JzInt); free(params); gsl_integration_glfixed_table_free ( T ); } void calcRapRperi(int ndata, double * rperi, double * rap, double * R, double * ER, double * Lz, int nargs, struct potentialArg * actionAngleArgs){ int ii, tid, nthreads; #ifdef _OPENMP nthreads = omp_get_max_threads(); #else nthreads = 1; #endif double peps, meps; gsl_function * JRRoot= (gsl_function *) malloc ( nthreads * sizeof(gsl_function) ); struct JRAdiabaticArg * params= (struct JRAdiabaticArg *) malloc ( nthreads * sizeof (struct JRAdiabaticArg) ); //Setup solver int status; int iter, max_iter = 100; const gsl_root_fsolver_type *T; double R_lo, R_hi; struct pragmasolver *s= (struct pragmasolver *) malloc ( nthreads * sizeof (struct pragmasolver) ); T = gsl_root_fsolver_brent; for (tid=0; tid < nthreads; tid++){ (params+tid)->nargs= nargs; (params+tid)->actionAngleArgs= actionAngleArgs; (s+tid)->s= gsl_root_fsolver_alloc (T); } UNUSED int chunk= CHUNKSIZE; gsl_set_error_handler_off(); #pragma omp parallel for schedule(static,chunk) \ private(tid,ii,iter,status,R_lo,R_hi,meps,peps) \ shared(rperi,rap,JRRoot,params,s,R,ER,Lz,max_iter) for (ii=0; ii < ndata; ii++){ #ifdef _OPENMP tid= omp_get_thread_num(); #else tid = 0; #endif //Setup function (params+tid)->ER= *(ER+ii); (params+tid)->Lz22= 0.5 * *(Lz+ii) * *(Lz+ii); (JRRoot+tid)->params = params+tid; (JRRoot+tid)->function = &JRAdiabaticIntegrandSquared; //Find starting points for minimum if ( fabs(GSL_FN_EVAL(JRRoot+tid,*(R+ii))) < 0.0000001){ //we are at rap or rperi peps= GSL_FN_EVAL(JRRoot+tid,*(R+ii)+0.0000001); meps= GSL_FN_EVAL(JRRoot+tid,*(R+ii)-0.0000001); if ( fabs(peps) < 0.00000001 && fabs(meps) < 0.00000001 && peps*meps >= 0.) {//circular *(rperi+ii) = *(R+ii); *(rap+ii) = *(R+ii); } else if ( peps < 0. && meps > 0. ) {//umax *(rap+ii)= *(R+ii); R_lo= 0.9 * (*(R+ii) - 0.0000001); R_hi= *(R+ii) - 0.00000001; while ( GSL_FN_EVAL(JRRoot+tid,R_lo) >= 0. && R_lo > 0.000000001){ R_hi= R_lo; //this makes sure that brent evaluates using previous R_lo*= 0.9; } //Find root status = gsl_root_fsolver_set ((s+tid)->s, JRRoot+tid, R_lo, R_hi); if (status == GSL_EINVAL) { *(rperi+ii) = 0.;//Assume zero if below 0.000000001 continue; } iter= 0; do { iter++; status = gsl_root_fsolver_iterate ((s+tid)->s); R_lo = gsl_root_fsolver_x_lower ((s+tid)->s); R_hi = gsl_root_fsolver_x_upper ((s+tid)->s); status = gsl_root_test_interval (R_lo, R_hi, 9.9999999999999998e-13, 4.4408920985006262e-16); } while (status == GSL_CONTINUE && iter < max_iter); // LCOV_EXCL_START if (status == GSL_EINVAL) {//Shouldn't ever get here *(rperi+ii) = -9999.99; *(rap+ii) = -9999.99; continue; } // LCOV_EXCL_STOP *(rperi+ii) = gsl_root_fsolver_root ((s+tid)->s); } else if ( peps > 0. && meps < 0. ){//umin *(rperi+ii)= *(R+ii); R_lo= *(R+ii) + 0.0000001; R_hi= 1.1 * (*(R+ii) + 0.0000001); while ( GSL_FN_EVAL(JRRoot+tid,R_hi) >= 0. && R_hi < 37.5) { R_lo= R_hi; //this makes sure that brent evaluates using previous R_hi*= 1.1; } //Find root status = gsl_root_fsolver_set ((s+tid)->s, JRRoot+tid, R_lo, R_hi); if (status == GSL_EINVAL) { *(rperi+ii) = -9999.99; *(rap+ii) = -9999.99; continue; } iter= 0; do { iter++; status = gsl_root_fsolver_iterate ((s+tid)->s); R_lo = gsl_root_fsolver_x_lower ((s+tid)->s); R_hi = gsl_root_fsolver_x_upper ((s+tid)->s); status = gsl_root_test_interval (R_lo, R_hi, 9.9999999999999998e-13, 4.4408920985006262e-16); } while (status == GSL_CONTINUE && iter < max_iter); // LCOV_EXCL_START if (status == GSL_EINVAL) {//Shouldn't ever get here *(rperi+ii) = -9999.99; *(rap+ii) = -9999.99; continue; } // LCOV_EXCL_STOP *(rap+ii) = gsl_root_fsolver_root ((s+tid)->s); } } else { R_lo= 0.9 * *(R+ii); R_hi= *(R+ii); while ( GSL_FN_EVAL(JRRoot+tid,R_lo) >= 0. && R_lo > 0.000000001){ R_hi= R_lo; //this makes sure that brent evaluates using previous R_lo*= 0.9; } R_hi= (R_lo < 0.9 * *(R+ii)) ? R_lo / 0.9 / 0.9: *(R+ii); //Find root status = gsl_root_fsolver_set ((s+tid)->s, JRRoot+tid, R_lo, R_hi); if (status == GSL_EINVAL) { *(rperi+ii) = 0.;//Assume zero if below 0.000000001 } else { iter= 0; do { iter++; status = gsl_root_fsolver_iterate ((s+tid)->s); R_lo = gsl_root_fsolver_x_lower ((s+tid)->s); R_hi = gsl_root_fsolver_x_upper ((s+tid)->s); status = gsl_root_test_interval (R_lo, R_hi, 9.9999999999999998e-13, 4.4408920985006262e-16); } while (status == GSL_CONTINUE && iter < max_iter); // LCOV_EXCL_START if (status == GSL_EINVAL) {//Shouldn't ever get here *(rperi+ii) = -9999.99; *(rap+ii) = -9999.99; continue; } // LCOV_EXCL_STOP *(rperi+ii) = gsl_root_fsolver_root ((s+tid)->s); } //Find starting points for maximum R_lo= *(R+ii); R_hi= 1.1 * *(R+ii); while ( GSL_FN_EVAL(JRRoot+tid,R_hi) > 0. && R_hi < 37.5) { R_lo= R_hi; //this makes sure that brent evaluates using previous R_hi*= 1.1; } R_lo= (R_hi > 1.1 * *(R+ii)) ? R_hi / 1.1 / 1.1: *(R+ii); //Find root status = gsl_root_fsolver_set ((s+tid)->s, JRRoot+tid, R_lo, R_hi); if (status == GSL_EINVAL) { *(rperi+ii) = -9999.99; *(rap+ii) = -9999.99; continue; } iter= 0; do { iter++; status = gsl_root_fsolver_iterate ((s+tid)->s); R_lo = gsl_root_fsolver_x_lower ((s+tid)->s); R_hi = gsl_root_fsolver_x_upper ((s+tid)->s); status = gsl_root_test_interval (R_lo, R_hi, 9.9999999999999998e-13, 4.4408920985006262e-16); } while (status == GSL_CONTINUE && iter < max_iter); // LCOV_EXCL_START if (status == GSL_EINVAL) {//Shouldn't ever get here *(rperi+ii) = -9999.99; *(rap+ii) = -9999.99; continue; } // LCOV_EXCL_STOP *(rap+ii) = gsl_root_fsolver_root ((s+tid)->s); } } gsl_set_error_handler (NULL); for (tid=0; tid < nthreads; tid++) gsl_root_fsolver_free( (s+tid)->s); free(s); free(JRRoot); free(params); } void calcZmax(int ndata, double * zmax, double * z, double * R, double * Ez, int nargs, struct potentialArg * actionAngleArgs){ int ii, tid, nthreads; #ifdef _OPENMP nthreads = omp_get_max_threads(); #else nthreads = 1; #endif gsl_function * JzRoot= (gsl_function *) malloc ( nthreads * sizeof(gsl_function) ); struct JzAdiabaticArg * params= (struct JzAdiabaticArg *) malloc ( nthreads * sizeof (struct JzAdiabaticArg) ); //Setup solver int status; int iter, max_iter = 100; const gsl_root_fsolver_type *T; double z_lo, z_hi; struct pragmasolver *s= (struct pragmasolver *) malloc ( nthreads * sizeof (struct pragmasolver) ); T = gsl_root_fsolver_brent; for (tid=0; tid < nthreads; tid++){ (params+tid)->nargs= nargs; (params+tid)->actionAngleArgs= actionAngleArgs; (s+tid)->s= gsl_root_fsolver_alloc (T); } UNUSED int chunk= CHUNKSIZE; gsl_set_error_handler_off(); #pragma omp parallel for schedule(static,chunk) \ private(tid,ii,iter,status,z_lo,z_hi) \ shared(zmax,JzRoot,params,s,z,Ez,R,max_iter) for (ii=0; ii < ndata; ii++){ #ifdef _OPENMP tid= omp_get_thread_num(); #else tid = 0; #endif //Setup function (params+tid)->Ez= *(Ez+ii); (params+tid)->R= *(R+ii); (JzRoot+tid)->function = &JzAdiabaticIntegrandSquared; (JzRoot+tid)->params = params+tid; //Find starting points for minimum if ( fabs(GSL_FN_EVAL(JzRoot+tid,*(z+ii))) < 0.0000001){ //we are at zmax *(zmax+ii)= fabs( *(z+ii) ); } else { z_lo= fabs ( *(z+ii) ); z_hi= ( *(z+ii) == 0. ) ? 0.1: 1.1 * fabs( *(z+ii) ); while ( GSL_FN_EVAL(JzRoot+tid,z_hi) >= 0. && z_hi < 37.5) { z_lo= z_hi; //this makes sure that brent evaluates using previous z_hi*= 1.1; } //Find root status = gsl_root_fsolver_set ((s+tid)->s, JzRoot+tid, z_lo, z_hi); if (status == GSL_EINVAL) { *(zmax+ii) = -9999.99; continue; } iter= 0; do { iter++; status = gsl_root_fsolver_iterate ((s+tid)->s); z_lo = gsl_root_fsolver_x_lower ((s+tid)->s); z_hi = gsl_root_fsolver_x_upper ((s+tid)->s); status = gsl_root_test_interval (z_lo, z_hi, 9.9999999999999998e-13, 4.4408920985006262e-16); } while (status == GSL_CONTINUE && iter < max_iter); // LCOV_EXCL_START if (status == GSL_EINVAL) {//Shouldn't ever get here *(zmax+ii) = -9999.99; continue; } // LCOV_EXCL_STOP *(zmax+ii) = gsl_root_fsolver_root ((s+tid)->s); } } gsl_set_error_handler (NULL); for (tid=0; tid < nthreads; tid++) gsl_root_fsolver_free( (s+tid)->s); free(s); free(JzRoot); free(params); } double JRAdiabaticIntegrand(double R, void * p){ return sqrt(JRAdiabaticIntegrandSquared(R,p)); } double JRAdiabaticIntegrandSquared(double R, void * p){ struct JRAdiabaticArg * params= (struct JRAdiabaticArg *) p; return params->ER - evaluatePotentials(R,0.,params->nargs,params->actionAngleArgs) - params->Lz22 / R / R; } double JzAdiabaticIntegrand(double z, void * p){ return sqrt(JzAdiabaticIntegrandSquared(z,p)); } double JzAdiabaticIntegrandSquared(double z, void * p){ struct JzAdiabaticArg * params= (struct JzAdiabaticArg *) p; return params->Ez - evaluateVerticalPotentials(params->R,z, params->nargs, params->actionAngleArgs); } double evaluateVerticalPotentials(double R, double z, int nargs, struct potentialArg * actionAngleArgs){ return evaluatePotentials(R,z,nargs,actionAngleArgs) -evaluatePotentials(R,0.,nargs,actionAngleArgs); }
{ "alphanum_fraction": 0.6272049043, "avg_line_length": 30.4955908289, "ext": "c", "hexsha": "81e69ac7a3542d7e1e0a27320f34dd48474cea56", "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": "93a1b6fc8d138899922127086cc66184919c8cba", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "fardal/galpy", "max_forks_repo_path": "galpy/actionAngle_src/actionAngle_c_ext/actionAngleAdiabatic.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "93a1b6fc8d138899922127086cc66184919c8cba", "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": "fardal/galpy", "max_issues_repo_path": "galpy/actionAngle_src/actionAngle_c_ext/actionAngleAdiabatic.c", "max_line_length": 113, "max_stars_count": null, "max_stars_repo_head_hexsha": "93a1b6fc8d138899922127086cc66184919c8cba", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "fardal/galpy", "max_stars_repo_path": "galpy/actionAngle_src/actionAngle_c_ext/actionAngleAdiabatic.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 5833, "size": 17291 }
// // her2k.h // Linear Algebra Template Library // // Created by Rodney James on 1/6/12. // Copyright (c) 2012 University of Colorado Denver. All rights reserved. // #ifndef _her2k_h #define _her2k_h /// @file her2k.h Performs multiplication of two complex matrices resulting in a Hermitian matrix. #include <cctype> #include "latl.h" namespace LATL { /// @brief Performs multiplcation of complex matrices resulting in a Hermitian matrix. /// /// For complex matrices A and B, complex Hermitian matrix C, and complex scalar alpha and real /// scalar beta /// /// C := alpha*A*B'+conj(alpha)*B*A'+beta*C /// or /// /// C := alpha*A'*B+conj(alpha)*B'*A+beta*C /// is computed. /// @return 0 if success. /// @return -i if the ith argument is invalid. /// @tparam real_t Floating point type. /// @param uplo Specifies whether the upper or lower triangular part of the Hermitian matrix C /// is to be referenced: /// /// if uplo = 'U' or 'u' then C is upper triangular, /// if uplo = 'L' or 'l' then C is lower triangular. /// @param trans Specifies the operation to be perfomed as follows: /// /// if trans = 'N' or 'n' then C := alpha*A*B'+conj(alpha)*B*A'+beta*C /// if trans = 'C' or 'c' then C := alpha*A'*B+conj(alpha)*B'*A+beta*C /// @param n Specifies the order of the complex Hermitian matrix C. n>=0 /// @param k Specifies the other dimension of the complex matrices A and B. /// /// if trans = 'N' or 'n' then A and B are n-by-k /// if trans = 'C' or 'c' then A and B are k-by-n /// @param alpha Complex scalar. /// @param A Pointer to complex matrix. /// @param ldA Column length of the matrix A. If trans = 'N' or 'n' ldA>=n, otherwise ldA>=k. /// @param B Pointer to complex matrix. /// @param ldB Column length of the matrix B. If trans = 'N' or 'n' ldB>=n, otherwise ldB>=k. /// @param beta Real scalar. /// @param C Pointer to complex Hermitian n-by-n matrix C. /// Only the upper or lower triangular part of C is referenced, depending on the value of uplo above. /// @param ldC Column length of the matrix C. ldC>=n /// @ingroup BLAS template <typename real_t> int HER2K(char uplo, char trans, int_t n, int_t k, complex<real_t> alpha, complex<real_t> *A, int_t ldA, complex<real_t> *B, int_t ldB, real_t beta, complex<real_t> *C, int_t ldC) { using std::toupper; uplo=toupper(uplo); trans=toupper(trans); using std::real; using std::conj; const complex<real_t> zero(0.0,0.0); const complex<real_t> one(1.0,0.0); int_t i,j,l; complex<real_t> *a,*b,*c,*at,*bt; complex<real_t> s,t; if((uplo!='U')&&(uplo!='L')) return -1; else if((trans!='N')&&(trans!='C')) return -2; else if(n<0) return -3; else if(k<0) return -4; else if(ldA<((trans=='N')?n:k)) return -7; else if(ldB<((trans=='N')?n:k)) return -9; else if(ldC<n) return -12; else if((n==0)||(((alpha==zero)||(k==0))&&(beta==one))) return 0; if(alpha==zero) { if(uplo=='U') { c=C; for(j=0;j<n;j++) { for(i=0;i<j;i++) c[i]*=beta; c[j]=beta*real(c[j]); c+=ldC; } } else { c=C; for(j=0;j<n;j++) { c[j]=beta*real(c[j]); for(i=j+1;i<n;i++) c[i]*=beta; c+=ldC; } } } else if(trans=='N') { if(uplo=='U') { c=C; for(j=0;j<n;j++) { for(i=0;i<j;i++) c[i]*=beta; c[j]=beta*real(c[j]); a=A; b=B; for(l=0;l<k;l++) { s=alpha*conj(b[j]); t=conj(alpha*a[j]); for(i=0;i<j;i++) c[i]+=s*a[i]+t*b[i]; c[j]=real(c[j])+real(a[j]*s+b[j]*t); a+=ldA; b+=ldB; } c+=ldC; } } else { c=C; for(j=0;j<n;j++) { c[j]=beta*real(c[j]); for(i=j+1;i<n;i++) c[i]*=beta; a=A; b=B; for(l=0;l<k;l++) { s=alpha*conj(b[j]); t=conj(alpha*a[j]); c[j]=real(c[j])+real(s*a[j]+t*b[j]); for(i=j+1;i<n;i++) c[i]+=s*a[i]+t*b[i]; a+=ldA; b+=ldB; } c+=ldC; } } } else { if(uplo=='U') { c=C; at=A; bt=B; for(j=0;j<n;j++) { a=A; b=B; for(i=0;i<=j;i++) { s=zero; t=zero; for(l=0;l<k;l++) { s+=conj(b[l])*at[l]; t+=conj(a[l])*bt[l]; } if(i<j) c[i]=alpha*t+conj(alpha)*s+beta*c[i]; else c[j]=real(alpha*t+conj(alpha)*s)+beta*real(c[j]); a+=ldA; b+=ldB; } at+=ldA; bt+=ldB; c+=ldC; } } else { c=C; at=A; bt=B; for(j=0;j<n;j++) { a=A+j*ldA; b=B+j*ldB; for(i=j;i<n;i++) { s=zero; t=zero; for(l=0;l<k;l++) { s+=conj(b[l])*at[l]; t+=conj(a[l])*bt[l]; } if(i>j) c[i]=alpha*t+conj(alpha)*s+beta*c[i]; else c[j]=real(alpha*t+conj(alpha)*s)+beta*real(c[j]); a+=ldA; b+=ldB; } at+=ldA; bt+=ldB; c+=ldC; } } } return 0; } #ifdef __latl_cblas #include <cblas.h> template <> int HER2K<float>(char uplo, char trans, int_t n, int_t k, complex<float> alpha, complex<float> *A, int_t ldA, complex<float> *B, int_t ldB, float beta, complex<float> *C, int_t ldC) { using std::toupper; uplo=toupper(uplo); trans=toupper(trans); if((uplo!='U')&&(uplo!='L')) return -1; else if((trans!='N')&&(trans!='C')) return -2; else if(n<0) return -3; else if(k<0) return -4; else if(ldA<((trans=='N')?n:k)) return -7; else if(ldB<((trans=='N')?n:k)) return -9; else if(ldC<n) return -12; const CBLAS_UPLO Uplo=(uplo=='U')?CblasUpper:CblasLower; const CBLAS_TRANSPOSE Trans=(trans=='N')?CblasNoTrans:((trans=='T')?CblasTrans:CblasConjTrans); cblas_cher2k(CblasColMajor,Uplo,Trans,n,k,&alpha,A,ldA,B,ldB,beta,C,ldC); return 0; } template <> int HER2K<double>(char uplo, char trans, int_t n, int_t k, complex<double> alpha, complex<double> *A, int_t ldA, complex<double> *B, int_t ldB, double beta, complex<double> *C, int_t ldC) { using std::toupper; uplo=toupper(uplo); trans=toupper(trans); if((uplo!='U')&&(uplo!='L')) return -1; else if((trans!='N')&&(trans!='C')) return -2; else if(n<0) return -3; else if(k<0) return -4; else if(ldA<((trans=='N')?n:k)) return -7; else if(ldB<((trans=='N')?n:k)) return -9; else if(ldC<n) return -12; const CBLAS_UPLO Uplo=(uplo=='U')?CblasUpper:CblasLower; const CBLAS_TRANSPOSE Trans=(trans=='N')?CblasNoTrans:((trans=='T')?CblasTrans:CblasConjTrans); cblas_zher2k(CblasColMajor,Uplo,Trans,n,k,&alpha,A,ldA,B,ldB,beta,C,ldC); return 0; } #endif } #endif
{ "alphanum_fraction": 0.4320342205, "avg_line_length": 28.8219178082, "ext": "h", "hexsha": "3bab530ee133d6b8ce15a0a570426f5416f9fa4a", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2022-02-09T23:18:24.000Z", "max_forks_repo_forks_event_min_datetime": "2019-02-01T06:46:36.000Z", "max_forks_repo_head_hexsha": "df838fb44a1ef5c77b57bf60bd46eaeff8db3492", "max_forks_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_forks_repo_name": "langou/latl", "max_forks_repo_path": "include/her2k.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "df838fb44a1ef5c77b57bf60bd46eaeff8db3492", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_issues_repo_name": "langou/latl", "max_issues_repo_path": "include/her2k.h", "max_line_length": 202, "max_stars_count": 6, "max_stars_repo_head_hexsha": "df838fb44a1ef5c77b57bf60bd46eaeff8db3492", "max_stars_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_stars_repo_name": "langou/latl", "max_stars_repo_path": "include/her2k.h", "max_stars_repo_stars_event_max_datetime": "2022-02-09T23:18:22.000Z", "max_stars_repo_stars_event_min_datetime": "2015-12-13T09:10:11.000Z", "num_tokens": 2366, "size": 8416 }
#include <bindings.cmacros.h> #include <gsl/gsl_errno.h> BC_INLINE2(GSL_ERROR_SELECT_2,int,int,int) BC_INLINE3(GSL_ERROR_SELECT_3,int,int,int,int) BC_INLINE4(GSL_ERROR_SELECT_4,int,int,int,int,int) BC_INLINE5(GSL_ERROR_SELECT_5,int,int,int,int,int,int) BC_INLINE2VOID(GSL_STATUS_UPDATE,int*,int)
{ "alphanum_fraction": 0.8282828283, "avg_line_length": 33, "ext": "c", "hexsha": "ed682a55ef036e40696571b01e6577e38754d870", "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/ErrorHandling.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/ErrorHandling.c", "max_line_length": 54, "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/ErrorHandling.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": 86, "size": 297 }
#pragma once #include "CesiumGltfReader/Library.h" #include <CesiumAsync/AsyncSystem.h> #include <CesiumAsync/Future.h> #include <CesiumAsync/HttpHeaders.h> #include <CesiumAsync/IAssetAccessor.h> #include <CesiumGltf/Model.h> #include <CesiumJsonReader/ExtensionReaderContext.h> #include <CesiumJsonReader/IExtensionJsonHandler.h> #include <gsl/span> #include <functional> #include <memory> #include <optional> #include <string> #include <vector> namespace CesiumGltfReader { /** * @brief The result of reading a glTF model with * {@link GltfReader::readModel}. */ struct CESIUMGLTFREADER_API ModelReaderResult { /** * @brief The read model, or std::nullopt if the model could not be read. */ std::optional<CesiumGltf::Model> model; /** * @brief Errors, if any, that occurred during the load process. */ std::vector<std::string> errors; /** * @brief Warnings, if any, that occurred during the load process. */ std::vector<std::string> warnings; }; /** * @brief The result of reading an image with * {@link GltfReader::readImage}. */ struct CESIUMGLTFREADER_API ImageReaderResult { /** * @brief The {@link ImageCesium} that was read. * * This will be `std::nullopt` if the image could not be read. */ std::optional<CesiumGltf::ImageCesium> image; /** * @brief Error messages that occurred while trying to read the image. */ std::vector<std::string> errors; /** * @brief Warning messages that occurred while reading the image. */ std::vector<std::string> warnings; }; /** * @brief Options for how to read a glTF. */ struct CESIUMGLTFREADER_API ReadModelOptions { /** * @brief Whether data URLs in buffers and images should be automatically * decoded as part of the load process. */ bool decodeDataUrls = true; /** * @brief Whether data URLs should be cleared after they are successfully * decoded. * * This reduces the memory usage of the model. */ bool clearDecodedDataUrls = true; /** * @brief Whether embedded images in {@link Model::buffers} should be * automatically decoded as part of the load process. * * The {@link ImageSpec::mimeType} property is ignored, and instead the * [stb_image](https://github.com/nothings/stb) library is used to decode * images in `JPG`, `PNG`, `TGA`, `BMP`, `PSD`, `GIF`, `HDR`, or `PIC` format. */ bool decodeEmbeddedImages = true; /** * @brief Whether geometry compressed using the `KHR_draco_mesh_compression` * extension should be automatically decoded as part of the load process. */ bool decodeDraco = true; }; /** * @brief Reads glTF models and images. */ class CESIUMGLTFREADER_API GltfReader { public: /** * @brief Constructs a new instance. */ GltfReader(); /** * @brief Gets the context used to control how extensions are loaded from glTF * files. */ CesiumJsonReader::ExtensionReaderContext& getExtensions(); /** * @brief Gets the context used to control how extensions are loaded from glTF * files. */ const CesiumJsonReader::ExtensionReaderContext& getExtensions() const; /** * @brief Reads a glTF or binary glTF (GLB) from a buffer. * * @param data The buffer from which to read the glTF. * @param options Options for how to read the glTF. * @return The result of reading the glTF. */ ModelReaderResult readModel( const gsl::span<const std::byte>& data, const ReadModelOptions& options = ReadModelOptions()) const; /** * @brief Accepts the result of {@link readModel} and resolves any remaining * external buffers and images. * * @param asyncSystem The async system to use for resolving external data. * @param baseUrl The base url that all the external uris are relative to. * @param headers The http headers needed to make any external data requests. * @param pAssetAccessor The asset accessor to use to request the external * buffers and images. * @param result The result of the synchronous readModel invocation. */ static CesiumAsync::Future<ModelReaderResult> resolveExternalData( CesiumAsync::AsyncSystem asyncSystem, const std::string& baseUrl, const CesiumAsync::HttpHeaders& headers, std::shared_ptr<CesiumAsync::IAssetAccessor> pAssetAccessor, ModelReaderResult&& result); /** * @brief Reads an image from a buffer. * * The [stb_image](https://github.com/nothings/stb) library is used to decode * images in `JPG`, `PNG`, `TGA`, `BMP`, `PSD`, `GIF`, `HDR`, or `PIC` format. * * @param data The buffer from which to read the image. * @return The result of reading the image. */ static ImageReaderResult readImage(const gsl::span<const std::byte>& data); private: CesiumJsonReader::ExtensionReaderContext _context; }; } // namespace CesiumGltfReader
{ "alphanum_fraction": 0.6956431964, "avg_line_length": 28.4882352941, "ext": "h", "hexsha": "a2ccbdfc5a4e00d3d8546ff97862e55e27cd2a03", "lang": "C", "max_forks_count": 66, "max_forks_repo_forks_event_max_datetime": "2022-03-31T13:38:41.000Z", "max_forks_repo_forks_event_min_datetime": "2021-03-30T15:14:32.000Z", "max_forks_repo_head_hexsha": "7fbccc0ff302f3645dc5829c3a2f3a5bdba83922", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "137734949/cesium-native", "max_forks_repo_path": "CesiumGltfReader/include/CesiumGltfReader/GltfReader.h", "max_issues_count": 256, "max_issues_repo_head_hexsha": "7fbccc0ff302f3645dc5829c3a2f3a5bdba83922", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:44:21.000Z", "max_issues_repo_issues_event_min_datetime": "2021-03-30T18:12:28.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "137734949/cesium-native", "max_issues_repo_path": "CesiumGltfReader/include/CesiumGltfReader/GltfReader.h", "max_line_length": 80, "max_stars_count": 154, "max_stars_repo_head_hexsha": "7fbccc0ff302f3645dc5829c3a2f3a5bdba83922", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "137734949/cesium-native", "max_stars_repo_path": "CesiumGltfReader/include/CesiumGltfReader/GltfReader.h", "max_stars_repo_stars_event_max_datetime": "2022-03-30T00:01:43.000Z", "max_stars_repo_stars_event_min_datetime": "2021-03-30T14:08:39.000Z", "num_tokens": 1248, "size": 4843 }
/* * BRAINS * (B)LR (R)everberation-mapping (A)nalysis (I)n AGNs with (N)ested (S)ampling * Yan-Rong Li, liyanrong@ihep.ac.cn * Thu, Aug 4, 2016 */ /*! * \file smooth.c * \brief smoothing functions using FFT provided by GSL. * * References: Press et al., Numerical Recipes, Chapter 13.1. * GSL documents */ ///////////////THIS FILE IS DEPRECATED/////////////////////////// #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <mpi.h> #include <gsl/gsl_fft_real.h> #include <gsl/gsl_fft_complex.h> #include <gsl/gsl_fft_halfcomplex.h> #include "brains.h" int nd_fft; double *resp, *data_fft; double *resp_cmp, *data_fft_cmp, *data_fft_inverse; gsl_fft_real_wavetable * real_data, *real_resp; gsl_fft_complex_wavetable * cmp_data; gsl_fft_real_workspace * work_data, *work_resp; gsl_fft_complex_workspace * work_cmp; /*! * This function initiates workspace for FFT. */ void smooth_init(int nv, const double *transv) { //nd_fft = parset.n_vel_recon>=n_vel_data? parset.n_vel_recon : n_vel_data; nd_fft = nv; //printf("%d\n", nd_fft); real_data = gsl_fft_real_wavetable_alloc (nd_fft); real_resp = gsl_fft_real_wavetable_alloc (nd_fft); cmp_data = gsl_fft_complex_wavetable_alloc (nd_fft); work_data = gsl_fft_real_workspace_alloc (nd_fft); work_resp = gsl_fft_real_workspace_alloc (nd_fft); work_cmp = gsl_fft_complex_workspace_alloc (nd_fft); resp = malloc(nd_fft * sizeof(double)); data_fft = malloc(nd_fft * sizeof(double)); resp_cmp = malloc(nd_fft * 2 * sizeof(double)); data_fft_cmp = malloc(nd_fft *2 * sizeof(double)); data_fft_inverse = malloc(nd_fft *2 * sizeof(double)); // initialize response and its fft. int i; double sigV, dV, tot; sigV = parset.InstRes / VelUnit; dV = transv[1] - transv[0]; /* setup response, whose negective-time part is wrapped around and stored at the right hand*/ tot = 0.0; for (i = 0; i<nd_fft/2; i++) { resp[i] = 1.0/sqrt(2.0*M_PI)/sigV * exp(-0.5*(i*dV)*(i*dV)/sigV/sigV); tot += resp[i]; } for (i = nd_fft-1; i>= nd_fft/2; i--) { resp[i] = 1.0/sqrt(2.0*M_PI)/sigV * exp(-0.5*((i-nd_fft)*dV)*((i-nd_fft)*dV)/sigV/sigV); tot += resp[i]; } /* normalize response */ for(i=0; i<nd_fft; i++) { //resp[i] /= (tot * dV); resp[i] /= (tot); } /* FFT of response */ gsl_fft_real_transform(resp, 1, nd_fft, real_resp, work_resp); gsl_fft_halfcomplex_unpack(resp, resp_cmp, 1, nd_fft); } /*! * This function finalizes FFT. */ void smooth_end() { gsl_fft_real_wavetable_free(real_data); gsl_fft_real_wavetable_free(real_resp); gsl_fft_complex_wavetable_free(cmp_data); gsl_fft_real_workspace_free(work_data); gsl_fft_real_workspace_free(work_resp); gsl_fft_complex_workspace_free(work_cmp); free(resp); free(data_fft); free(resp_cmp); free(data_fft_cmp); free(data_fft_inverse); } /*! * This function performs FFT-smoothing to 2d line. */ void line_gaussian_smooth_2D_FFT(const double *transv, double *fl2d, int nl, int nv) { int i, j; double dV; dV = transv[1] - transv[0]; for(j=0; j<nl; j++) { memcpy(data_fft, &fl2d[j*nv], nv*sizeof(double)); /* FFT of line */ gsl_fft_real_transform(data_fft, 1, nd_fft, real_data, work_data); gsl_fft_halfcomplex_unpack(data_fft, data_fft_cmp, 1, nd_fft); /* complex multiply and inverse FFT */ for(i=0; i<nd_fft; i++) { data_fft_inverse[i*2] = data_fft_cmp[i*2]*resp_cmp[i*2] - data_fft_cmp[i*2+1]*resp_cmp[i*2+1]; data_fft_inverse[i*2+1] = data_fft_cmp[i*2]*resp_cmp[i*2+1] + data_fft_cmp[i*2+1]*resp_cmp[i*2]; } gsl_fft_complex_inverse(data_fft_inverse, 1, nd_fft, cmp_data, work_cmp); for(i=0; i<nv; i++) { /* take into account the velocity grid width */ //fl2d[j*nv + i] = data_fft_inverse[i*2] * dV; fl2d[j*nv + i] = data_fft_inverse[i*2]; } } return; } /*! * test smoothing function, assumed line profile. */ void line_gaussian_smooth_2D_FFT_test(const double *transv, double *fl2d, int nl, int nv) { int i, j; double sigV, dV, tot; sigV = parset.InstRes / VelUnit; dV = transv[1] - transv[0]; tot = 0.0; for (i = 0; i<nd_fft/2; i++) { resp[i] = 1.0/sqrt(2.0*M_PI)/sigV * exp(-0.5*(i*dV)*(i*dV)/sigV/sigV); tot += resp[i]; } for (i = nd_fft-1; i>= nd_fft/2; i--) { resp[i] = 1.0/sqrt(2.0*M_PI)/sigV * exp(-0.5*((i-nd_fft)*dV)*((i-nd_fft)*dV)/sigV/sigV); tot += resp[i]; } for(i=0; i<nd_fft; i++) { resp[i] /= (tot * dV); } gsl_fft_real_transform(resp, 1, nd_fft, real_resp, work_resp); gsl_fft_halfcomplex_unpack(resp, resp_cmp, 1, nd_fft); for(j=0; j<nl; j++) { //memcpy(data_fft, &fl2d[j*nv], nv*sizeof(double)); for(i=0; i<nv; i++) { data_fft[i] = exp( - 0.5 * pow(transv[i]/(1500.0/VelUnit), 2.0)); } gsl_fft_real_transform(data_fft, 1, nd_fft, real_data, work_data); gsl_fft_halfcomplex_unpack(data_fft, data_fft_cmp, 1, nd_fft); for(i=0; i<nd_fft; i++) { data_fft_inverse[i*2] = data_fft_cmp[i*2]*resp_cmp[i*2] - data_fft_cmp[i*2+1]*resp_cmp[i*2+1]; data_fft_inverse[i*2+1] = data_fft_cmp[i*2]*resp_cmp[i*2+1] + data_fft_cmp[i*2+1]*resp_cmp[i*2]; } gsl_fft_complex_inverse(data_fft_inverse, 1, nd_fft, cmp_data, work_cmp); for(i=0; i<nv; i++) { // take into account the velocity grid width fl2d[j*nv + i] = data_fft_inverse[i*2] * dV; } } return; } /*! * convolution test. */ void smooth_test() { int i, n = 205; double data[n], resp[n]; double data_cmp[n*2], resp_cmp[n*2]; double ans[n*2]; gsl_fft_real_wavetable * real, *real_resp; gsl_fft_complex_wavetable * hc; gsl_fft_real_workspace * work, *work_resp; gsl_fft_complex_workspace * work_cmp; for (i = 0; i < n; i++) { data[i] = 1.0/sqrt(2.0*M_PI)/6.0 * exp(-0.5*(i-50.0)*(i-50.0)/6.0/6.0); } for (i = 0; i < n/2; i++) { resp[i] = 1.0/sqrt(2.0*M_PI)/10.0 * exp(-0.5*(i-0.0)*(i-0.0)/10.0/10.0); } for (i = n-1; i >= n/2; i--) { resp[i] = 1.0/sqrt(2.0*M_PI)/10.0 * exp(-0.5*(i-n)*(i-n)/10.0/10.0); } for (i = 0; i < n; i++) { printf ("%d: %e\n", i, data[i]); } printf ("\n"); work = gsl_fft_real_workspace_alloc (n); real = gsl_fft_real_wavetable_alloc (n); work_resp = gsl_fft_real_workspace_alloc (n); real_resp = gsl_fft_real_wavetable_alloc (n); work_cmp = gsl_fft_complex_workspace_alloc(n); hc = gsl_fft_complex_wavetable_alloc (n); gsl_fft_real_transform (data, 1, n, real, work); gsl_fft_real_transform (resp, 1, n, real_resp, work_resp); gsl_fft_halfcomplex_unpack(data, data_cmp, 1, n); gsl_fft_halfcomplex_unpack(resp, resp_cmp, 1, n); for(i=0; i<n; i++) { ans[i*2] = data_cmp[i*2]*resp_cmp[i*2] - data_cmp[i*2+1]*resp_cmp[i*2+1]; ans[i*2+1] = data_cmp[i*2]*resp_cmp[i*2+1] + data_cmp[i*2+1]*resp_cmp[i*2]; } gsl_fft_complex_inverse(ans, 1, n, hc, work_cmp); for (i = 0; i < n; i++) { printf ("%d: %e %e\n", i, ans[i*2], ans[i*2+1]); } gsl_fft_real_wavetable_free (real); gsl_fft_real_wavetable_free (real_resp); gsl_fft_real_workspace_free (work); gsl_fft_real_workspace_free (work_resp); gsl_fft_complex_wavetable_free (hc); gsl_fft_complex_workspace_free(work_cmp); return; }
{ "alphanum_fraction": 0.6383297062, "avg_line_length": 26.0709219858, "ext": "c", "hexsha": "ce8bb9d8b3f3bdb8eb011cb214a2e1ed228fa9dd", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2020-11-22T12:54:58.000Z", "max_forks_repo_forks_event_min_datetime": "2019-06-12T13:51:29.000Z", "max_forks_repo_head_hexsha": "b81cec02a1902df1e544542a970b66d9916a7496", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "yzxamos/BRAINS", "max_forks_repo_path": "src/smooth.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "b81cec02a1902df1e544542a970b66d9916a7496", "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": "yzxamos/BRAINS", "max_issues_repo_path": "src/smooth.c", "max_line_length": 102, "max_stars_count": 6, "max_stars_repo_head_hexsha": "b81cec02a1902df1e544542a970b66d9916a7496", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "yzxamos/BRAINS", "max_stars_repo_path": "src/smooth.c", "max_stars_repo_stars_event_max_datetime": "2021-05-18T07:46:45.000Z", "max_stars_repo_stars_event_min_datetime": "2018-11-16T13:37:42.000Z", "num_tokens": 2527, "size": 7352 }
#include <petsc.h> #include <petscvec.h> #include <petscmat.h> #include <petscksp.h> #include "del2mat.h" #define DEL2MAT_MULT ((void(*)(void))Del2Mat_mult) #define DEL2MAT_DIAG ((void(*)(void))Del2Mat_diag) int main(int argc,char **argv) { PetscInt n; PetscScalar h; Del2Mat shell; Mat A; Vec x,b; KSP ksp; PC pc; /* PETSc initialization */ PetscInitialize(&argc, &argv, PETSC_NULL, PETSC_NULL); /* number of nodes in each direction * excluding those at the boundary */ n = 32; h = 1.0/(n+1); /* grid spacing */ /* setup linear system (shell) matrix */ MatCreate(PETSC_COMM_SELF, &A); MatSetSizes(A, n*n*n, n*n*n, n*n*n, n*n*n); MatSetType(A, MATSHELL); shell.N = n; PetscMalloc((n+2)*(n+2)*(n+2)*sizeof(PetscScalar),&shell.F); PetscMemzero(shell.F, (n+2)*(n+2)*(n+2)*sizeof(PetscScalar)); MatShellSetContext(A, (void**)&shell); MatShellSetOperation(A, MATOP_MULT, DEL2MAT_MULT); MatShellSetOperation(A, MATOP_MULT_TRANSPOSE, DEL2MAT_MULT); MatShellSetOperation(A, MATOP_GET_DIAGONAL, DEL2MAT_DIAG); MatSetUp(A); /* setup linear system vectors */ MatCreateVecs(A, &x, &b); VecSet(x, 0); VecSet(b, 1); /* setup Krylov linear solver */ KSPCreate(PETSC_COMM_SELF, &ksp); KSPGetPC(ksp, &pc); KSPSetType(ksp, KSPCG); /* use conjugate gradients */ PCSetType(pc, PCNONE); /* with no preconditioning */ KSPSetFromOptions(ksp); /* iteratively solve linear system of equations A*x=b */ KSPSetOperators(ksp,A,A); KSPSolve(ksp, b, x); /* scale solution vector to account for grid spacing */ VecScale(x, h*h); /* free memory and destroy objects */ PetscFree(shell.F); VecDestroy(&x); VecDestroy(&b); MatDestroy(&A); KSPDestroy(&ksp); /* finalize PETSc */ PetscFinalize(); return 0; }
{ "alphanum_fraction": 0.6649972176, "avg_line_length": 28.9838709677, "ext": "c", "hexsha": "a6315f7a01e5ba75d59872409a9527cf5bad0ea9", "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": "33408c70b4211b801c24f8c3cdb859f5aaf59367", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "zonca/petsc4py", "max_forks_repo_path": "demo/poisson3d/poisson3d.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "33408c70b4211b801c24f8c3cdb859f5aaf59367", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "zonca/petsc4py", "max_issues_repo_path": "demo/poisson3d/poisson3d.c", "max_line_length": 63, "max_stars_count": 1, "max_stars_repo_head_hexsha": "33408c70b4211b801c24f8c3cdb859f5aaf59367", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "zonca/petsc4py", "max_stars_repo_path": "demo/poisson3d/poisson3d.c", "max_stars_repo_stars_event_max_datetime": "2018-11-11T05:00:53.000Z", "max_stars_repo_stars_event_min_datetime": "2018-11-11T05:00:53.000Z", "num_tokens": 586, "size": 1797 }
#ifndef TESTING_COMMON #define TESTING_COMMON #define MIN(a, b) ((a) < (b) ? (a) : (b)) #define MAX(a, b) ((a) > (b) ? (a) : (b)) // header ------------------------------------------ #include "testing_setting.h" #undef _IEEE_ #define __STDC_WANT_IEC_60559_TYPES_EXT__ #include <cstdio> #include <cstdlib> #include <cmath> #include <string.h> #include <stdint.h> #include <float.h> #define __STDC_FORMAT_MACROS #include <inttypes.h> #include <sys/time.h> #include <unistd.h> #include <getopt.h> #include <ctype.h> #include <sys/utsname.h> #if defined (MKL) //#include <mkl.h> #include <mkl_cblas.h> #include <mkl_trans.h> //#include <mkl_spblas.h> // conflict with Bebop SMC #else #include <cblas.h> #endif #if defined (ARM) #define __float128 long double #endif #if defined (CUBLAS) #include <cublas_v2.h> #elif defined (CUOZBLAS) #include <cuozblas.h> #elif defined (OZBLAS) #include <ozblas.h> #endif #if defined (CUDA) #include <cuda.h> #include <cuda_runtime_api.h> #include <cublas_v2.h> #include <cusparse_v2.h> #endif #if defined (CSRMV) || defined (CG) extern "C" { #include <bebop/smc/sparse_matrix.h> #include <bebop/smc/sparse_matrix_ops.h> #include <bebop/smc/csr_matrix.h> } #endif #if !defined (MPLAPACK) #define mpreal double #endif // =========================================================== // common for FP_TYPE #if defined (PREC_Q_D) || defined (PREC_Q_S) #define PREC_Q #elif defined (PREC_D_D) || defined (PREC_D_S) #define PREC_D #elif defined (PREC_S_S) || defined (PREC_S_D) #define PREC_S #elif defined (PREC_32F_PDT_32F) #define PREC_S #elif defined (PREC_32F_TC_32F) #define PREC_S #elif defined (PREC_32F_TC_32TF) #define PREC_S #elif defined (PREC_16F_TC_32F) #define PREC_H #elif defined (PREC_16F_PDT_32F) #define PREC_H #elif defined (PREC_16F_TC_16F) #define PREC_H #elif defined (PREC_16F_PDT_16F) #define PREC_H #elif defined (PREC_64F_PDT_64F) #define PREC_D #elif defined (PREC_64F_TC_64F) #define PREC_D #endif // =========================================================== #if defined (MPLAPACK) #if defined (PREC_Q) #define MPFR_WANT_FLOAT128 #define _Float128 __float128 // this is needed if MPFR is >= 4.1.0 #endif #include <mplapack/mpblas_mpfr.h> #include <mpfr.h> // this is after above #endif #undef _Float128 // +++++++++++++++++++++ // FP_TYPE == binary128 // +++++++++++++++++++++ #if defined (PREC_Q) #define FP_TYPE __float128 #if defined (ARM) #define FABS fabs #define FP_MAX LDBL_MAX #define FP_MIN LDBL_MIN #define F_PI 3.1415926535897932384626433832795029L; #else #include <quadmath.h> #define FABS fabsq #define FP_MAX FLT128_MAX #define FP_MIN FLT128_MIN #define F_PI M_PIq #endif #if defined (MPLAPACK) #include <mplapack/mpblas__Float128.h> #endif // +++++++++++++++++++++ // FP_TYPE == double-double // +++++++++++++++++++++ #elif defined (PREC_DD) #define FP_TYPE dd_real #define FABS fabs #if defined (MPLAPACK) #include <qd/dd_real.h> #include <mplapack/mpblas_dd.h> #endif #define FP_MAX DBL_MAX #define FP_MIN DBL_MIN #define F_PI dd_real::_pi // +++++++++++++++++++++ // FP_TYPE == binary64 // +++++++++++++++++++++ #elif defined (PREC_D) #define FP_TYPE double #define FABS fabs #define FP_MAX DBL_MAX #define FP_MIN DBL_MIN #define F_PI M_PI // +++++++++++++++++++++ // FP_TYPE == binary32 // +++++++++++++++++++++ #elif defined (PREC_S) #define FP_TYPE float #define FABS fabs #define FP_MAX FLT_MAX #define FP_MIN FLT_MIN #define F_PI M_PI // +++++++++++++++++++++ // FP_TYPE == binary16 // +++++++++++++++++++++ #elif defined (PREC_H) #include "half-2.1.0/half.hpp" using half_float::half; #define FP_TYPE half #define FABS fabs #define FP_MAX 65504. #define FP_MIN (2.e-14)-1 #define F_PI M_PI #endif // =========================================================== // reference BLAS #if defined (MPLAPACK) #define refRdot Rdot #define refRgemv(tran,m,n,al,A,lda,X,ix,bt,Y,iy) Rgemv(&tran,m,n,al,A,lda,X,ix,bt,Y,iy) #define refRgemm(tranA,tranB,m,n,k,al,A,lda,B,ldb,bt,C,ldc) Rgemm(&tranA,&tranB,m,n,k,al,A,lda,B,ldb,bt,C,ldc) #else #define refRdot cblas_ddot #define refRgemv(tran,m,n,al,A,lda,X,ix,bt,Y,iy) cblas_dgemv(CblasColMajor,ToCblasOp(tran),m,n,al,A,lda,X,ix,bt,Y,iy) #define refRgemm(tranA,tranB,m,n,k,al,A,lda,B,ldb,bt,C,ldc) cblas_dgemm(CblasColMajor,ToCblasOp(tranA),ToCblasOp(tranB),m,n,k,al,A,lda,B,ldb,bt,C,ldc) #endif // =========================================================== // argment transformation #if defined (OZBLAS) #define trgRdot(ha,n,x,ix,y,iy) rdot(&ha,n,x,ix,y,iy) #define trgRnrm2(ha,n,x,ix) rnrm2(&ha,n,x,ix) #define trgRaxpy(ha,n,a,x,ix,y,iy) raxpy(&ha,n,a,x,ix,y,iy) #define trgRgemv(ha,ta,m,n,al,a,la,x,ix,bt,y,iy) rgemv(&ha,ta,m,n,al,a,la,x,ix,bt,y,iy) #define trgRgemm(ha,ta,tb,m,n,k,al,A,lda,B,ldb,bt,C,ldc) rgemm(&ha,ta,tb,m,n,k,al,A,lda,B,ldb,bt,C,ldc) #define trgRcsrmv(ha,ta,m,n,nnz,al,da,a,ci,rp,x,bt,y) rcsrmv(&ha,ta,m,n,nnz,al,da,a,ci,rp,x,bt,y) #define trgRcg(ha,ta,n,nnz,da,a,ci,rp,b,x,itr,tol) rcg(&ha,ta,n,nnz,da,a,ci,rp,b,x,itr,tol) #elif defined (CUOZBLAS) #define trgRdot(ha,n,x,ix,y,iy,r) rdot(&ha,n,x,ix,y,iy,r) #define trgRnrm2(ha,n,x,ix,r) rnrm2(&ha,n,x,ix,r) #define trgRaxpy(ha,n,a,x,ix,y,iy) raxpy(&ha,n,a,x,ix,y,iy) #define trgRgemv(ha,ta,m,n,al,a,la,x,ix,bt,y,iy) rgemv(&ha,ta,m,n,al,a,la,x,ix,bt,y,iy) #define trgRgemm(ha,ta,tb,m,n,k,al,A,lda,B,ldb,bt,C,ldc) rgemm(&ha,ta,tb,m,n,k,al,A,lda,B,ldb,bt,C,ldc) #define trgRcsrmv(ha,ta,m,n,nnz,al,da,a,ci,rp,x,bt,y) rcsrmv(&ha,ta,m,n,nnz,al,da,a,ci,rp,x,bt,y) #define trgRcg(ha,ta,n,nnz,da,a,ci,rp,b,x,itr,tol) rcg(&ha,ta,n,nnz,da,a,ci,rp,b,x,itr,tol) #elif defined (CUBLAS) && defined (GEMMEX) #define trgRgemm(ha,ta,tb,m,n,k,al,A,lda,B,ldb,bt,C,ldc) cublasGemmEx(ha,ToCublasOp(ta),ToCublasOp(tb),m,n,k,&al,A,DATA_TYPE_A,lda,B,DATA_TYPE_B,ldb,&bt,C,DATA_TYPE_C,ldc,COMP_TYPE,ALGO_TYPE) #elif defined (CUBLAS) #define trgRdot(ha,n,x,ix,y,iy,r) rdot(ha,n,x,ix,y,iy,r) #define trgRnrm2(ha,n,x,ix) rnrm2(ha,n,x,ix) #define trgRaxpy(ha,n,a,x,ix,y,iy) raxpy(ha,n,a,x,ix,y,iy) #define trgRgemv(ha,ta,m,n,al,a,la,x,ix,bt,y,iy) rgemv(ha,ToCublasOp(ta),m,n,&al,a,la,x,ix,&bt,y,iy) #define trgRgemm(ha,ta,tb,m,n,k,al,A,lda,B,ldb,bt,C,ldc) rgemm(ha,ToCublasOp(ta),ToCublasOp(tb),m,n,k,&al,A,lda,B,ldb,&bt,C,ldc) #define trgRcsrmv(ha,ta,m,n,nnz,al,da,a,ci,rp,x,bt,y) rcsrmv(ha,ToCusparseOp(ta),m,n,nnz,al,da,a,ci,rp,x,bt,y) //#define trgRcg(ha,ta,n,nnz,da,a,ci,rp,b,x,itr,tol) rcg(&ha,ta,n,nnz,da,a,ci,rp,b,x,itr,tol) #elif defined (MPBLAS) #define trgRdot(ha,n,x,ix,y,iy) rdot(n,x,ix,y,iy) #define trgRnrm2(ha,n,x,ix) rnrm2(n,x,ix) #define trgRaxpy(ha,n,a,x,ix,y,iy) raxpy(ha,n,a,x,ix,y,iy) #define trgRgemv(ha,ta,m,n,al,a,la,x,ix,bt,y,iy) rgemv(&ta,m,n,al,a,la,x,ix,bt,y,iy) #define trgRgemm(ha,ta,tb,m,n,k,al,A,lda,B,ldb,bt,C,ldc) rgemm(&ta,&tb,m,n,k,al,A,lda,B,ldb,bt,C,ldc) //#define trgRcg(ha,ta,n,nnz,da,a,ci,rp,b,x,itr,tol) rcg(&ha,ta,n,nnz,da,a,ci,rp,b,x,itr,tol) #endif // =========================================================== #if defined (CUOZBLAS) #define ozblasHandle_t cuozblasHandle_t #define ozblasCreate cuozblasCreate #define ozblasDestroy cuozblasDestroy #endif // ================================================ #if defined (PREC_Q_D) #if defined (CUOZBLAS) #define rcg cuozblasRcg<__float128,double> #define rdot cuozblasRdot<__float128,double> #define rnrm2 cuozblasRnrm2<__float128,double> #define raxpy cuozblasRaxpy<__float128> #define rgemv cuozblasRgemv<__float128,double> #define rgemm cuozblasRgemm<__float128,double> #define rcsrmv cuozblasRcsrmv<__float128,double> #define rcsrmvSplitA cuozblasRcsrmvSplitA<__float128,double> #elif defined (OZBLAS) #define rcg ozblasRcg<__float128,double> #define rdot ozblasRdot<__float128,double> #define rnrm2 ozblasRnrm2<__float128,double> #define rgemv ozblasRgemv<__float128,double> #define rgemm ozblasRgemm<__float128,double> #define rcsrmv ozblasRcsrmv<__float128,double> #define rcsrmvSplitA ozblasRcsrmvSplitA<__float128,double> #elif defined (MPBLAS) #define rdot Rdot #define rgemv Rgemv #define rgemm Rgemm #endif // ================================================ #elif defined (PREC_Q_S) #if defined (CUOZBLAS) #define rcg cuozblasRcg<__float128,float> #define rdot cuozblasRdot<__float128,float> #define rnrm2 cuozblasRnrm2<__float128,float> #define raxpy cuozblasRaxpy<__float128> #define rgemv cuozblasRgemv<__float128,float> #define rgemm cuozblasRgemm<__float128,float> #define rcsrmv cuozblasRcsrmv<__float128,float> #define rcsrmvSplitA cuozblasRcsrmvSplitA<__float128,float> #elif defined (OZBLAS) #define rcg ozblasRcg<__float128,float> #define rdot ozblasRdot<__float128,float> #define rnrm2 ozblasRnrm2<__float128,float> #define rgemv ozblasRgemv<__float128,float> #define rgemm ozblasRgemm<__float128,float> #define rcsrmv ozblasRcsrmv<__float128,float> #define rcsrmvSplitA ozblasRcsrmvSplitA<__float128,float> #endif // ================================================ #elif defined (PREC_D_S) #if defined (CUOZBLAS) #define rcg cuozblasRcg<double,float> #define rdot cuozblasRdot<double,float> #define rnrm2 cuozblasRnrm2<double,float> #define raxpy cuozblasRaxpy<double> #define rgemv cuozblasRgemv<double,float> #define rgemm cuozblasRgemm<double,float> #define rcsrmv cuozblasRcsrmv<double,float> #define rcsrmvSplitA cuozblasRcsrmvSplitA<double,float> #elif defined (OZBLAS) #define rcg ozblasRcg<double,float> #define rdot ozblasRdot<double,float> #define rnrm2 ozblasRnrm2<double,float> #define rgemv ozblasRgemv<double,float> #define rgemm ozblasRgemm<double,float> #define rcsrmv ozblasRcsrmv<double,float> #define rcsrmvSplitA ozblasRcsrmvSplitA<double,float> #endif // ================================================ #elif defined (PREC_D_D) #if defined (CUOZBLAS) #define rcg cuozblasRcg<double,double> #define rdot cuozblasRdot<double,double> #define rnrm2 cuozblasRnrm2<double,double> #define raxpy cuozblasRaxpy<double> #define rgemv cuozblasRgemv<double,double> //#define rgemm cuozblasDgemm #define rgemm cuozblasRgemm<double,double> #define rcsrmv cuozblasRcsrmv<double,double> #define rcsrmvSplitA cuozblasRcsrmvSplitA<double,double> #elif defined (OZBLAS) #define rcg ozblasRcg<double,double> #define rdot ozblasRdot<double,double> #define rnrm2 ozblasRnrm2<double,double> #define rgemv ozblasRgemv<double,double> //#define rgemv ozblasDgemv #define rgemm ozblasRgemm<double,double> #define rcsrmv ozblasRcsrmv<double,double> #define rcsrmvSplitA ozblasRcsrmvSplitA<double,double> #elif defined (CUBLAS) //#define rcg cublasDcg #define rdot cublasDdot #define rnrm2 cublasDnrm2 #define rgemv cublasDgemv #define rgemm cublasDgemm //#define rcsrmv cublasDcsrmv #endif // ================================================ #elif defined (PREC_S_S) #if defined (CUOZBLAS) #define rcg cuozblasRcg<float,float> #define rdot cuozblasRdot<float,float> #define rnrm2 cuozblasRnrm2<float,float> #define raxpy cuozblasRaxpy<float> #define rgemv cuozblasRgemv<float,float> #define rgemm cuozblasRgemm<float,float> #define rcsrmv cuozblasRcsrmv<float,float> #define rcsrmvSplitA cuozblasRcsrmvSplitA<float,float> #elif defined (OZBLAS) #define rcg ozblasRcg<float,float> #define rdot ozblasRdot<float,float> #define rnrm2 ozblasRnrm2<float,float> #define rgemv ozblasRgemv<float,float> #define rgemm ozblasRgemm<float,float> #define rcsrmv ozblasRcsrmv<float,float> #define rcsrmvSplitA ozblasRcsrmvSplitA<float,float> #elif defined (CUBLAS) //#define rcg cublasScg #define rdot cublasSdot #define rnrm2 cublasSnrm2 #define rgemv cublasSgemv #define rgemm cublasSgemm //#define rcsrmv cublasScsrmv #endif // ================================================ #elif defined (PREC_S_D) #if defined (CUOZBLAS) #define rcg cuozblasRcg<float,double> #define rdot cuozblasRdot<float,double> #define rnrm2 cuozblasRnrm2<float,double> #define raxpy cuozblasRaxpy<float> #define rgemv cuozblasRgemv<float,double> #define rgemm cuozblasRgemm<float,double> #define rcsrmv cuozblasRcsrmv<float,double> #define rcsrmvSplitA cuozblasRcsrmvSplitA<float,double> #elif defined (OZBLAS) #define rcg ozblasRcg<float,double> #define rdot ozblasRdot<float,double> #define rnrm2 ozblasRnrm2<float,double> #define rgemv ozblasRgemv<float,double> #define rgemm ozblasRgemm<float,double> #define rcsrmv ozblasRcsrmv<float,double> #define rcsrmvSplitA ozblasRcsrmvSplitA<float,double> #endif // ================================================ #elif defined (PREC_DD) #if defined (MPBLAS) #define rdot Rdot #define rgemv Rgemv #define rgemm Rgemm #endif #endif // ================================================ // GemmEx #if defined (CUBLAS) && defined (GEMMEX) #define rgemm cublasGemmEx // ---------------------------- #if defined (PREC_32F_PDT_32F) #define DATA_TYPE_A CUDA_R_32F #define DATA_TYPE_B CUDA_R_32F #define DATA_TYPE_C CUDA_R_32F #define COMP_TYPE CUBLAS_COMPUTE_32F_PEDANTIC #define ALGO_TYPE CUBLAS_GEMM_DEFAULT // ---------------------------- #elif defined (PREC_32F_TC_32F) #define DATA_TYPE_A CUDA_R_32F #define DATA_TYPE_B CUDA_R_32F #define DATA_TYPE_C CUDA_R_32F #define COMP_TYPE CUBLAS_COMPUTE_32F #define ALGO_TYPE CUBLAS_GEMM_DEFAULT // ---------------------------- #elif defined (PREC_32F_TC_32TF) #define DATA_TYPE_A CUDA_R_32F #define DATA_TYPE_B CUDA_R_32F #define DATA_TYPE_C CUDA_R_32F #define COMP_TYPE CUBLAS_COMPUTE_32F_FAST_TF32 #define ALGO_TYPE CUBLAS_GEMM_DEFAULT // ---------------------------- #elif defined (PREC_16F_TC_32F) #define DATA_TYPE_A CUDA_R_16F #define DATA_TYPE_B CUDA_R_16F #define DATA_TYPE_C CUDA_R_16F #define COMP_TYPE CUBLAS_COMPUTE_32F #define ALGO_TYPE CUBLAS_GEMM_DEFAULT // ---------------------------- #elif defined (PREC_16F_PDT_32F) #define DATA_TYPE_A CUDA_R_16F #define DATA_TYPE_B CUDA_R_16F #define DATA_TYPE_C CUDA_R_16F #define COMP_TYPE CUBLAS_COMPUTE_32F_PEDANTIC #define ALGO_TYPE CUBLAS_GEMM_DEFAULT // ---------------------------- #elif defined (PREC_16F_TC_16F) #define DATA_TYPE_A CUDA_R_16F #define DATA_TYPE_B CUDA_R_16F #define DATA_TYPE_C CUDA_R_16F #define COMP_TYPE CUBLAS_COMPUTE_16F #define ALGO_TYPE CUBLAS_GEMM_DEFAULT // ---------------------------- #elif defined (PREC_16F_PDT_16F) #define DATA_TYPE_A CUDA_R_16F #define DATA_TYPE_B CUDA_R_16F #define DATA_TYPE_C CUDA_R_16F #define COMP_TYPE CUBLAS_COMPUTE_16F_PEDANTIC #define ALGO_TYPE CUBLAS_GEMM_DEFAULT // ---------------------------- #elif defined (PREC_64F_PDT_64F) #define DATA_TYPE_A CUDA_R_64F #define DATA_TYPE_B CUDA_R_64F #define DATA_TYPE_C CUDA_R_64F #define COMP_TYPE CUBLAS_COMPUTE_64F_PEDANTIC #define ALGO_TYPE CUBLAS_GEMM_DEFAULT // ---------------------------- #elif defined (PREC_64F_TC_64F) #define DATA_TYPE_A CUDA_R_64F #define DATA_TYPE_B CUDA_R_64F #define DATA_TYPE_C CUDA_R_64F #define COMP_TYPE CUBLAS_COMPUTE_64F #define ALGO_TYPE CUBLAS_GEMM_DEFAULT // ---------------------------- #endif #endif #endif
{ "alphanum_fraction": 0.6920433518, "avg_line_length": 32.8956521739, "ext": "h", "hexsha": "08f9672e01f356d3d0179f8a5aa6b20b499434f6", "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": "97c20aa5d8e186790aa505f6be4d1f48eee352e3", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "wsmoses/Riken-blas", "max_forks_repo_path": "testing/testing_common.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "97c20aa5d8e186790aa505f6be4d1f48eee352e3", "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": "wsmoses/Riken-blas", "max_issues_repo_path": "testing/testing_common.h", "max_line_length": 191, "max_stars_count": null, "max_stars_repo_head_hexsha": "97c20aa5d8e186790aa505f6be4d1f48eee352e3", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "wsmoses/Riken-blas", "max_stars_repo_path": "testing/testing_common.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 5254, "size": 15132 }
/** * * @file testing_sgemm.c * * PLASMA testing routines * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author Emmanuel Agullo * @author Mathieu Faverge * @date 2010-11-15 * @generated s Tue Jan 7 11:45:19 2014 * **/ #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> #include "testing_smain.h" #undef COMPLEX #define REAL int testing_slange(int argc, char **argv) { /* Check for number of arguments*/ if ( argc != 3) { USAGE("LANGE", "M N LDA", " - M : number of rows of matrices A and C\n" " - N : number of columns of matrices B and C\n" " - LDA : leading dimension of matrix A\n"); return -1; } int M = atoi(argv[0]); int N = atoi(argv[1]); int LDA = atoi(argv[2]); int LDAxN = LDA*N; int n, u; float eps; float *A = (float *)malloc(LDAxN*sizeof(float)); float *work = (float*) malloc(max(M,N)*sizeof(float)); float normplasma, normlapack, result; eps = LAPACKE_slamch_work('e'); printf("\n"); printf("------ TESTS FOR PLASMA SLANGE ROUTINE ------- \n"); printf(" Size of the Matrix %d by %d\n", M, N); printf("\n"); printf(" The matrix A is randomly generated for each test.\n"); printf("============\n"); printf(" The relative machine precision (eps) is to be %e \n",eps); printf(" Computational tests pass if scaled residuals are less than 10.\n"); /*---------------------------------------------------------- * TESTING SLANGE */ /* Initialize A, B, C */ PLASMA_splrnt( M, N, A, LDA, 3436 ); /* PLASMA SLANGE */ for(n=0; n<4; n++) { normplasma = PLASMA_slange(norm[n], M, N, A, LDA); normlapack = LAPACKE_slange_work(LAPACK_COL_MAJOR, lapack_const(norm[n]), M, N, A, LDA, work); printf("Lapack %e, Plasma %e\n", normlapack, normplasma); result = fabs(normplasma - normlapack) / (normlapack * eps); switch(norm[n]) { case PlasmaMaxNorm: /* result should be perfectly equal */ break; case PlasmaInfNorm: /* Sum order on the line can differ */ result = result / (float)N; break; case PlasmaOneNorm: /* Sum order on the column can differ */ result = result / (float)M; break; case PlasmaFrobeniusNorm: /* Sum oreder on every element can differ */ result = result / ((float)M * (float)N); break; } printf("***************************************************\n"); if ( result < 1. ) { printf(" ---- TESTING SLANGE (%s)............... PASSED !\n", normstr[n]); } else { printf(" - TESTING SLANGE (%s)... FAILED !\n", normstr[n]); } printf("***************************************************\n"); } /* Don't perform real tests while lapacke is not correct */ #ifdef COMPLEX /* PLASMA SLANTR */ for(n=0; n<4; n++) { for(u=0; u<2; u++) { int d; for(d=0; d<2; d++) { normplasma = PLASMA_slantr(norm[n], uplo[u], diag[d], M, N, A, LDA); normlapack = LAPACKE_slantr_work(LAPACK_COL_MAJOR, lapack_const(norm[n]), lapack_const(uplo[u]), lapack_const(diag[d]), M, N, A, LDA, work); printf("Lapack %e, Plasma %e\n", normlapack, normplasma); result = fabs(normplasma - normlapack) / (normlapack * eps); switch(norm[n]) { case PlasmaMaxNorm: /* result should be perfectly equal */ break; case PlasmaInfNorm: /* Sum order on the line can differ */ result = result / (float)N; break; case PlasmaOneNorm: /* Sum order on the column can differ */ result = result / (float)M; break; case PlasmaFrobeniusNorm: /* Sum oreder on every element can differ */ result = result / ((float)M * (float)N); break; } printf("***************************************************\n"); if ( result < 1. ) { printf(" ---- TESTING SLANTR (%s, %s, %s)......... PASSED !\n", normstr[n], uplostr[u], diagstr[d]); } else { printf(" - TESTING SLANTR (%s, %s, %s)... FAILED !\n", normstr[n], uplostr[u], diagstr[d]); } printf("***************************************************\n"); } } } #endif /* PLASMA SLANSY */ for(n=0; n<4; n++) { for(u=0; u<2; u++) { normplasma = PLASMA_slansy(norm[n], uplo[u], min(M,N), A, LDA); normlapack = LAPACKE_slansy_work(LAPACK_COL_MAJOR, lapack_const(norm[n]), lapack_const(uplo[u]), min(M,N), A, LDA, work); printf("Lapack %e, Plasma %e\n", normlapack, normplasma); result = fabs(normplasma - normlapack) / (normlapack * eps); switch(norm[n]) { case PlasmaMaxNorm: /* result should be perfectly equal */ break; case PlasmaInfNorm: /* Sum order on the line can differ */ result = result / (float)N; break; case PlasmaOneNorm: /* Sum order on the column can differ */ result = result / (float)M; break; case PlasmaFrobeniusNorm: /* Sum oreder on every element can differ */ result = result / ((float)M * (float)N); break; } printf("***************************************************\n"); if ( result < 1. ) { printf(" ---- TESTING SLANSY (%s, %s)......... PASSED !\n", normstr[n], uplostr[u]); } else { printf(" - TESTING SLANSY (%s, %s)... FAILED !\n", normstr[n], uplostr[u]); } printf("***************************************************\n"); } } #ifdef COMPLEX /* PLASMA SLANSY */ { int j; for (j=0; j<min(M,N); j++) { A[j*LDA+j] -= I*cimagf(A[j*LDA+j]); } } for(n=0; n<4; n++) { for(u=0; u<2; u++) { normplasma = PLASMA_slansy(norm[n], uplo[u], min(M,N), A, LDA); normlapack = LAPACKE_slansy_work(LAPACK_COL_MAJOR, lapack_const(norm[n]), lapack_const(uplo[u]), min(M,N), A, LDA, work); printf("Lapack %e, Plasma %e\n", normlapack, normplasma); result = fabs(normplasma - normlapack) / (normlapack * eps); switch(norm[n]) { case PlasmaMaxNorm: /* result should be perfectly equal */ break; case PlasmaInfNorm: /* Sum order on the line can differ */ result = result / (float)N; break; case PlasmaOneNorm: /* Sum order on the column can differ */ result = result / (float)M; break; case PlasmaFrobeniusNorm: /* Sum oreder on every element can differ */ result = result / ((float)M * (float)N); break; } printf("***************************************************\n"); if ( result < 1. ) { printf(" ---- TESTING SLANSY (%s, %s)......... PASSED !\n", normstr[n], uplostr[u]); } else { printf(" - TESTING SLANSY (%s, %s)... FAILED !\n", normstr[n], uplostr[u]); } printf("***************************************************\n"); } } #endif free(A); free(work); return 0; }
{ "alphanum_fraction": 0.4462869503, "avg_line_length": 34.531120332, "ext": "c", "hexsha": "120434f05f83bd967aba811f2a8d5a07f15fe800", "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": "testing/testing_slange.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": "testing/testing_slange.c", "max_line_length": 133, "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": "testing/testing_slange.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2059, "size": 8322 }
/* * testnonsymm.c * Patrick Alken * * Compile: gcc -g -O2 -Wall -o testnonsymm testnonsymm.c -lm -lgsl -lcblas -latlas * * Usage: testnonsymm [options] * * -i : incremental matrices * -b : balance the matrices * -z : compute Schur vectors and test them * -n size : size of matrices * -l lower-bound : lower bound for matrix elements * -u upper-bound : upper bound for matrix elements * -c num : number of matrices to solve */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <math.h> #include <getopt.h> #include <sys/times.h> #include <gsl/gsl_eigen.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_ieee_utils.h> #include <gsl/gsl_math.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_complex_math.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_test.h> typedef struct { gsl_eigen_nonsymm_workspace *nonsymm_p; gsl_eigen_nonsymmv_workspace *nonsymmv_p; gsl_matrix *A; gsl_matrix *Av; gsl_vector_complex *eval; gsl_vector_complex *evalv; gsl_matrix_complex *evec; int compute_z; gsl_matrix *Z; gsl_matrix *Zv; size_t n_evals; } nonsymm_workspace; nonsymm_workspace *nonsymm_alloc(size_t n, int compute_z, int do_balance); void nonsymm_free(nonsymm_workspace *w); int nonsymm_proc(nonsymm_workspace *w); /* * Global variables */ unsigned long count = 0; /* * Prototypes */ void make_random_matrix(gsl_matrix *m, gsl_rng *r, int lower, int upper); void make_start_matrix(gsl_matrix *m, int lower); int inc_matrix (gsl_matrix *m, int lower, int upper); void output_matrix(gsl_matrix *m); void print_octave(gsl_matrix *m, const char *str); void print_matrix(gsl_matrix *m, const char *str); void print_hess(gsl_matrix *H, const char *str); void print_vector(gsl_vector_complex *eval, const char *str); int cmp(double a, double b); int compare(const void *a, const void *b); void sort_complex_vector(gsl_vector_complex *v); int test_evals(gsl_vector_complex *obs, gsl_vector_complex *expected, gsl_matrix *A, const char *obsname, const char *expname); int test_Z(gsl_matrix *A, gsl_matrix *Z, gsl_matrix *T); int test_eigenvectors(gsl_matrix *A, gsl_vector_complex *eval, gsl_matrix_complex *evec); void my_error_handler(const char *reason, const char *file, int line, int err); nonsymm_workspace * nonsymm_alloc(size_t n, int compute_z, int do_balance) { nonsymm_workspace *w; w = (nonsymm_workspace *) malloc(sizeof(nonsymm_workspace)); memset(w, '\0', sizeof(nonsymm_workspace)); w->nonsymm_p = gsl_eigen_nonsymm_alloc(n); w->nonsymmv_p = gsl_eigen_nonsymmv_alloc(n); w->A = gsl_matrix_alloc(n, n); w->Av = gsl_matrix_alloc(n, n); if (compute_z) { w->Z = gsl_matrix_alloc(n, n); w->Zv = gsl_matrix_alloc(n, n); w->compute_z = 1; gsl_eigen_nonsymm_params(1, do_balance, w->nonsymm_p); } else gsl_eigen_nonsymm_params(0, do_balance, w->nonsymm_p); w->eval = gsl_vector_complex_alloc(n); w->evalv = gsl_vector_complex_alloc(n); w->evec = gsl_matrix_complex_alloc(n, n); return (w); } /* nonsymm_alloc() */ void nonsymm_free(nonsymm_workspace *w) { if (w->nonsymm_p) gsl_eigen_nonsymm_free(w->nonsymm_p); if (w->nonsymmv_p) gsl_eigen_nonsymmv_free(w->nonsymmv_p); if (w->A) gsl_matrix_free(w->A); if (w->Av) gsl_matrix_free(w->Av); if (w->Z) gsl_matrix_free(w->Z); if (w->Zv) gsl_matrix_free(w->Zv); if (w->eval) gsl_vector_complex_free(w->eval); if (w->evalv) gsl_vector_complex_free(w->evalv); if (w->evec) gsl_matrix_complex_free(w->evec); free(w); } /* nonsymm_free() */ int nonsymm_proc(nonsymm_workspace *w) { int s1, s2, s; if (w->compute_z) { s1 = gsl_eigen_nonsymm_Z(w->A, w->eval, w->Z, w->nonsymm_p); s2 = gsl_eigen_nonsymmv_Z(w->Av, w->evalv, w->evec, w->Zv, w->nonsymmv_p); } else { s1 = gsl_eigen_nonsymm(w->A, w->eval, w->nonsymm_p); s2 = gsl_eigen_nonsymmv(w->Av, w->evalv, w->evec, w->nonsymmv_p); } w->n_evals = w->nonsymm_p->n_evals; s = 0; if (s1) s = s1; else if (s2) s = s2; return s; } /* nonsymm_proc() */ /********************************************** * General routines **********************************************/ void make_random_matrix(gsl_matrix *m, gsl_rng *r, int lower, int upper) { size_t i, j; size_t N = m->size1; for (i = 0; i < N; ++i) { for (j = 0; j < N; ++j) { gsl_matrix_set(m, i, j, gsl_rng_uniform(r) * (upper - lower) + lower); } } } /* make_random_matrix() */ void make_start_matrix(gsl_matrix *m, int lower) { size_t i, j; size_t N = m->size1; for (i = 0; i < N; ++i) for (j = 0; j < N; ++j) gsl_matrix_set(m, i, j, (double)lower); } /* make_start_matrix() */ int inc_matrix (gsl_matrix *m, int lower, int upper) { size_t i = 0; size_t N = m->size1 * m->size2; int carry = 1; for (i = 0; carry > 0 && i < N; i++) { double v = m->data[i] + carry; carry = (v > upper) ? 1 : 0; m->data[i] = (v > upper) ? lower : v; } return carry; } /* inc_matrix() */ void output_matrix(gsl_matrix *m) { size_t i, j; size_t N = m->size1; size_t M = m->size2; for (i = 0; i < N; ++i) { for (j = 0; j < M; ++j) { /*printf("%10.9f%s",*/ printf("%10.18e%s", gsl_matrix_get(m, i, j), (j < M - 1) ? "," : ";\n"); } } } void print_octave(gsl_matrix *m, const char *str) { FILE *fp; size_t i, j; const size_t N = m->size1; const size_t M = m->size2; fp = fopen(str, "w"); if (!fp) return; fprintf(fp, "# Created by Octave 2.1.73, Tue Aug 01 15:00:27 2006 MDT <blah@blah>\n"); fprintf(fp, "# name: %s\n", str); fprintf(fp, "# type: matrix\n"); fprintf(fp, "# rows: %u\n", N); fprintf(fp, "# columns: %u\n", N); for (i = 0; i < N; ++i) { for (j = 0; j < M; ++j) { fprintf(fp, "%10.9f%s", gsl_matrix_get(m, i, j), (j < M - 1) ? " " : "\n"); } } fclose(fp); } void print_matrix(gsl_matrix *m, const char *str) { size_t i, j; size_t N = m->size1; size_t M = m->size2; gsl_matrix_view v; size_t rows, cols; size_t r, c; char buf[100]; /*print_octave(m, str); return;*/ /*rows = GSL_MIN(15, N);*/ rows = N; cols = GSL_MIN(15, N); /*cols = N;*/ for (i = 0; i < N; i += rows) { for (j = 0; j < M; j += cols) { r = GSL_MIN(rows, N - i); c = GSL_MIN(cols, N - j); v = gsl_matrix_submatrix(m, i, j, r, c); sprintf(buf, "%s(%u:%u,%u:%u)", str, i + 1, i + r, j + 1, j + c); printf("%s = [\n", buf); output_matrix(&v.matrix); printf("]\n"); } } } /* print_matrix() */ void print_vector(gsl_vector_complex *eval, const char *str) { size_t N = eval->size; size_t i; gsl_complex z; printf("%s = [\n", str); for (i = 0; i < N; ++i) { z = gsl_vector_complex_get(eval, i); printf("%.18e %.18e;\n", GSL_REAL(z), GSL_IMAG(z)); } printf("\n]\n"); } /* print_vector() */ int cmp(double a, double b) { return ((a > b) ? 1 : ((a < b) ? -1 : 0)); } /* cmp() */ int compare(const void *a, const void *b) { const double *x = a; const double *y = b; int r1 = cmp(y[0], x[0]); int r2 = cmp(y[1], x[1]); if (fabs(x[0] - y[0]) < 1.0e-8) { /* real parts are very close to each other */ return r2; } else { return r1 ? r1 : r2; } } /* compare() */ void sort_complex_vector(gsl_vector_complex *v) { qsort(v->data, v->size, 2 * sizeof(double), &compare); } /* sort_complex_vector() */ int test_evals(gsl_vector_complex *obs, gsl_vector_complex *expected, gsl_matrix *A, const char *obsname, const char *expname) { size_t N = expected->size; size_t i, k; double max, max_abserr, max_relerr; max = 0.0; max_abserr = 0.0; max_relerr = 0.0; k = 0; for (i = 0; i < N; ++i) { gsl_complex z = gsl_vector_complex_get(expected, i); max = GSL_MAX_DBL(max, gsl_complex_abs(z)); } for (i = 0; i < N; ++i) { gsl_complex z_obs = gsl_vector_complex_get(obs, i); gsl_complex z_exp = gsl_vector_complex_get(expected, i); double x_obs = GSL_REAL(z_obs); double y_obs = GSL_IMAG(z_obs); double x_exp = GSL_REAL(z_exp); double y_exp = GSL_IMAG(z_exp); double abserr_x = fabs(x_obs - x_exp); double abserr_y = fabs(y_obs - y_exp); double noise = max * GSL_DBL_EPSILON * N * N; max_abserr = GSL_MAX_DBL(max_abserr, abserr_x + abserr_y); if (abserr_x < noise && abserr_y < noise) continue; if (abserr_x > 1.0e-6 || abserr_y > 1.0e-6) ++k; } if (k) { printf("==== CASE %lu ===========================\n\n", count); print_matrix(A, "A"); printf("=== eval - %s ===\n", expname); print_vector(expected, expname); printf("=== eval - %s ===\n", obsname); print_vector(obs, obsname); printf("max abserr = %g max relerr = %g\n", max_abserr, max_relerr); printf("=========================================\n\n"); } return k; } /* test_evals() */ /* test if A = ZTZ^t (or AZ = ZT) */ int test_Z(gsl_matrix *A, gsl_matrix *Z, gsl_matrix *T) { size_t N = A->size1; size_t i, j, k; double rhs, lhs; double abserr; gsl_matrix *T1, *T2; T1 = gsl_matrix_alloc(N, N); T2 = gsl_matrix_alloc(N, N); /* zero the lower triangle of T */ if (N > 3) { for (i = 2; i < N; ++i) { for (j = 0; j < (i - 1); ++j) { gsl_matrix_set(T, i, j, 0.0); } } } else if (N == 3) { gsl_matrix_set(T, 2, 0, 0.0); } /* compute T1 = A Z */ gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, A, Z, 0.0, T1); /* compute T2 = Z T */ gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, Z, T, 0.0, T2); k = 0; for (i = 0; i < N; ++i) { for (j = 0; j < N; ++j) { lhs = gsl_matrix_get(T1, i, j); rhs = gsl_matrix_get(T2, i, j); abserr = fabs(lhs - rhs); if (abserr > 1.0e-6) ++k; } } if (k) { printf("==== CASE %lu ===========================\n\n", count); print_matrix(A, "A"); printf("=== Schur Form matrix ===\n"); print_matrix(T, "T"); printf("=== Similarity matrix ===\n"); print_matrix(Z, "Z"); printf("=== A Z ===\n"); print_matrix(T1, "A Z"); printf("=== Z T ===\n"); print_matrix(T2, "Z T"); printf("=== A Z - Z T ===\n"); gsl_matrix_sub(T1, T2); print_matrix(T1, "A Z - Z T"); printf("=========================================\n\n"); } gsl_matrix_free(T1); gsl_matrix_free(T2); return k; } /* test_Z() */ int test_eigenvectors(gsl_matrix *A, gsl_vector_complex *eval, gsl_matrix_complex *evec) { const size_t N = A->size1; size_t i, j; int k, s; gsl_matrix_complex *m; gsl_vector_complex *x, *y; gsl_complex z_one, z_zero; m = gsl_matrix_complex_alloc(N, N); y = gsl_vector_complex_alloc(N); x = gsl_vector_complex_alloc(N); /* m <- A */ for (i = 0; i < N; ++i) { for (j = 0; j < N; ++j) { gsl_complex z; GSL_SET_COMPLEX(&z, gsl_matrix_get(A, i, j), 0.0); gsl_matrix_complex_set(m, i, j, z); } } GSL_SET_COMPLEX(&z_one, 1.0, 0.0); GSL_SET_COMPLEX(&z_zero, 0.0, 0.0); s = 0; /* check eigenvalues */ for (i = 0; i < N; ++i) { gsl_vector_complex_view vi = gsl_matrix_complex_column(evec, i); gsl_complex ei = gsl_vector_complex_get(eval, i); double norm = gsl_blas_dznrm2(&vi.vector); /* check that eigenvector is normalized */ gsl_test_rel(norm, 1.0, N * GSL_DBL_EPSILON, "case %u, normalized", count); /* compute x = lambda * v */ gsl_vector_complex_memcpy(x, &vi.vector); gsl_blas_zscal(ei, x); /* compute y = A v */ gsl_blas_zgemv(CblasNoTrans, z_one, m, &vi.vector, z_zero, y); k = 0; /* now test if y = x */ for (j = 0; j < N; ++j) { gsl_complex z; double lhs_r, lhs_i; double rhs_r, rhs_i; z = gsl_vector_complex_get(y, j); lhs_r = GSL_REAL(z); lhs_i = GSL_IMAG(z); z = gsl_vector_complex_get(x, j); rhs_r = GSL_REAL(z); rhs_i = GSL_IMAG(z); if (fabs(lhs_r - rhs_r) > 1e8 * GSL_DBL_EPSILON) ++k; if (fabs(lhs_i - rhs_i) > 1e8 * GSL_DBL_EPSILON) ++k; } if (k) { s++; printf("==== CASE %lu ===========================\n\n", count); print_matrix(A, "A"); printf("eval = %f + %fi\n", GSL_REAL(ei), GSL_IMAG(ei)); print_vector(&vi.vector, "v"); print_vector(y, "Av"); print_vector(x, "ev_v"); printf("=========================================\n\n"); } } gsl_matrix_complex_free(m); gsl_vector_complex_free(y); gsl_vector_complex_free(x); return s; } /* test_eigenvectors() */ void my_error_handler(const char *reason, const char *file, int line, int err) { printf("[caught: %s:%d: errno=%d %s]\n", file, line, err, reason); } /* my_error_handler() */ int main(int argc, char *argv[]) { nonsymm_workspace *nonsymm_workspace_p; size_t N; int c; gsl_matrix *A; gsl_rng *r; int incremental; /* incremental/random matrices */ int lower; /* lower bound */ int upper; /* upper bound */ unsigned int nmat; /* number of matrices to solve */ int status; int compute_z; int do_balance; gsl_ieee_env_setup(); gsl_rng_env_setup(); /*gsl_set_error_handler(&my_error_handler);*/ N = 30; incremental = 0; compute_z = 0; do_balance = 0; lower = -10; upper = 10; nmat = 0; while ((c = getopt(argc, argv, "izbc:n:l:u:t:")) != (-1)) { switch (c) { case 'i': incremental = 1; break; case 'n': N = strtol(optarg, NULL, 0); break; case 'l': lower = strtol(optarg, NULL, 0); break; case 'u': upper = strtol(optarg, NULL, 0); break; case 'c': nmat = strtoul(optarg, NULL, 0); break; case 'b': do_balance = 1; break; case 'z': compute_z = 1; break; case '?': default: printf("usage: %s [-i] [-b] [-z] [-n size] [-l lower-bound] [-u upper-bound] [-c num]\n", argv[0]); exit(1); break; } /* switch (c) */ } A = gsl_matrix_alloc(N, N); nonsymm_workspace_p = nonsymm_alloc(N, compute_z, do_balance); if (!incremental) r = gsl_rng_alloc(gsl_rng_default); else { r = 0; make_start_matrix(A, lower); } fprintf(stderr, "testing N = %d", N); if (incremental) fprintf(stderr, " incrementally"); else fprintf(stderr, " randomly"); fprintf(stderr, " on element range [%d, %d]", lower, upper); if (compute_z) fprintf(stderr, ", with Schur vectors"); if (do_balance) fprintf(stderr, ", with balancing"); fprintf(stderr, "\n"); while (1) { if (nmat && (count >= nmat)) break; ++count; if (!incremental) make_random_matrix(A, r, lower, upper); else { status = inc_matrix(A, lower, upper); if (status) break; /* all done */ } /* make copies of the matrix */ gsl_matrix_memcpy(nonsymm_workspace_p->A, A); gsl_matrix_memcpy(nonsymm_workspace_p->Av, A); status = nonsymm_proc(nonsymm_workspace_p); if (status) { printf("=========== CASE %lu ============\n", count); printf("Failed to converge: found %u eigenvalues\n", nonsymm_workspace_p->n_evals); print_matrix(A, "A"); } gsl_eigen_nonsymmv_sort(nonsymm_workspace_p->evalv, nonsymm_workspace_p->evec, GSL_EIGEN_SORT_ABS_ASC); status = test_eigenvectors(A, nonsymm_workspace_p->evalv, nonsymm_workspace_p->evec); sort_complex_vector(nonsymm_workspace_p->eval); sort_complex_vector(nonsymm_workspace_p->evalv); status = test_evals(nonsymm_workspace_p->eval, nonsymm_workspace_p->evalv, A, "nonsymm", "nonsymmv"); if (compute_z) { test_Z(A, nonsymm_workspace_p->Z, nonsymm_workspace_p->A); test_Z(A, nonsymm_workspace_p->Zv, nonsymm_workspace_p->Av); } } gsl_matrix_free(A); nonsymm_free(nonsymm_workspace_p); if (r) gsl_rng_free(r); return 0; } /* main() */
{ "alphanum_fraction": 0.5281682222, "avg_line_length": 21.8233128834, "ext": "c", "hexsha": "4dc926771b0273e02efa61578d1e46e21c612be7", "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/eigen/testnonsymm.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/eigen/testnonsymm.c", "max_line_length": 111, "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/eigen/testnonsymm.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": 5378, "size": 17786 }
#ifndef BASIC_DATA_STRUCTURE_H #define BASIC_DATA_STRUCTURE_H #include <vector> #include <array> #include <string> #include <fstream> #include <iostream> #include <petsc.h> #include <petscksp.h> #include "petscsys.h" #include "petscmat.h" using namespace std; ///////////////////////////////// // const int degree = 3; // const int dim = 3; const int phydim = 3; // const int bzpt_num = (dim == 3) ? 64 : 16; // const int dof_all = 3; class Vertex3D { public: double coor[3]; int label; //ID for inlet and outlet Vertex3D(); }; class Element3D { public: int degree; int order; int nbf; int type; //0 for interior and 1 for boundary, for visualization purpose int bzflag; //0 for spline element, 1 for Bezier element int label; vector<int> IEN; vector<array<double, 3>> pts; //tmp vector<array<double, 64>> cmat; vector<int> IDBC; double velocity[3]; Element3D(int p = 3); void BezierPolyn(double u, vector<double> &Nu, vector<double> &dNdu) const; void Basis(double u, double v, double w, vector<double> &Nt, vector<array<double, 3>> &dNdt) const; void Para2Phys(double u, double v, double w, double pt[3]) const; }; class Vertex2D { public: double coor[3]; int label; //ID for inlet and outlet Vertex2D(); }; class Element2D { public: int degree; int order; int nbf; int type; //0 for interior and 1 for boundary, for visualization purpose int bzflag; //0 for spline element, 1 for Bezier element int label; vector<int> IEN; vector<array<double, phydim>> pts; //tmp vector<array<double, 16>> cmat; vector<int> IDBC; double velocity[2]; Element2D(int p = 3); void BezierPolyn(double u, vector<double> &Nu, vector<double> &dNdu) const; void Basis(double u, double v, vector<double> &Nt, vector<array<double, 2>> &dNdt) const; void Para2Phys(double u, double v, double pt[phydim]) const; }; //mesh format conversion void Raw2Vtk_hex(string fn); void Rawn2Vtk_hex(string fn); #endif
{ "alphanum_fraction": 0.692746114, "avg_line_length": 21.6853932584, "ext": "h", "hexsha": "d6be863d09137854c48267ead8d1783ed0cf23c3", "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": "3e71d6ffc99c2f5ce021608d800024d35b128763", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "CMU-CBML/NeuronTransportOptimization", "max_forks_repo_path": "nsvms_src/BasicDataStructure.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "3e71d6ffc99c2f5ce021608d800024d35b128763", "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": "CMU-CBML/NeuronTransportOptimization", "max_issues_repo_path": "nsvms_src/BasicDataStructure.h", "max_line_length": 100, "max_stars_count": null, "max_stars_repo_head_hexsha": "3e71d6ffc99c2f5ce021608d800024d35b128763", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "CMU-CBML/NeuronTransportOptimization", "max_stars_repo_path": "nsvms_src/BasicDataStructure.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 566, "size": 1930 }
/* Copyright 2017 International Business Machines Corporation 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. */ #pragma once #include "kernelpp/config.h" #include <gsl.h> #include <memory> #if defined(kernelpp_WITH_CUDA) # define checkCudaErrors(err) __checkCudaErrors (err, __FILE__, __LINE__) # define checkCudaLastError() __checkLastCudaError (__FILE__, __LINE__) #endif namespace kernelpp { /* Initialize the cuda runtime, and ensure at least * one device is available. */ bool init_cudart(); /* `device_ptr<T>` is a smart pointer which owns and manages one * or more objects of type `T` in contiguous memory on a CUDA device, * and disposes of these objects when it goes out of scope. */ template<typename T> class device_ptr final { struct cuda_deleter; std::unique_ptr<T, cuda_deleter> m_ptr; size_t m_size; public: device_ptr(); device_ptr(size_t n); device_ptr(device_ptr<T>&& other); device_ptr(gsl::span<T> span); gsl::span<T> span(); const gsl::span<T> span() const; T* get(); void copy_from(const gsl::span<T> from); void copy_to(gsl::span<T> to) const; }; } #if defined(kernelpp_WITH_CUDA) && defined(__CUDACC__) # include "cuda_util-inl.cuh" #endif
{ "alphanum_fraction": 0.6910390324, "avg_line_length": 28.873015873, "ext": "h", "hexsha": "2756a4fe34687579943e680f7741310d5a50468c", "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": "68644a71be2849cc0ef0b241fc68f195b9def5ce", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "rayglover-ibm/kernelpp", "max_forks_repo_path": "include/kernelpp/cuda_util.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "68644a71be2849cc0ef0b241fc68f195b9def5ce", "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": "rayglover-ibm/kernelpp", "max_issues_repo_path": "include/kernelpp/cuda_util.h", "max_line_length": 76, "max_stars_count": 5, "max_stars_repo_head_hexsha": "68644a71be2849cc0ef0b241fc68f195b9def5ce", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "rayglover-ibm/kernelpp", "max_stars_repo_path": "include/kernelpp/cuda_util.h", "max_stars_repo_stars_event_max_datetime": "2022-01-03T06:07:39.000Z", "max_stars_repo_stars_event_min_datetime": "2017-06-23T09:18:55.000Z", "num_tokens": 440, "size": 1819 }
#pragma once #include <gsl/span> #include <rapidjson/fwd.h> #include <spdlog/fwd.h> #include <memory> namespace CesiumGltf { struct Model; } namespace Cesium3DTilesSelection { /** * @brief Parses the provided B3DM batch table and adds an equivalent * EXT_feature_metadata extension to the provided glTF. * * @param pLogger * @param gltf * @param featureTable * @param batchTableJson * @param batchTableBinaryData */ void upgradeBatchTableToFeatureMetadata( const std::shared_ptr<spdlog::logger>& pLogger, CesiumGltf::Model& gltf, const rapidjson::Document& featureTable, const rapidjson::Document& batchTableJson, const gsl::span<const std::byte>& batchTableBinaryData); } // namespace Cesium3DTilesSelection
{ "alphanum_fraction": 0.748655914, "avg_line_length": 22.5454545455, "ext": "h", "hexsha": "d0f0b919fa95362de2c23cbb9f34d0160ccf5869", "lang": "C", "max_forks_count": 66, "max_forks_repo_forks_event_max_datetime": "2022-03-31T13:38:41.000Z", "max_forks_repo_forks_event_min_datetime": "2021-03-30T15:14:32.000Z", "max_forks_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "yieryi/cesium-native", "max_forks_repo_path": "Cesium3DTilesSelection/src/upgradeBatchTableToFeatureMetadata.h", "max_issues_count": 256, "max_issues_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:44:21.000Z", "max_issues_repo_issues_event_min_datetime": "2021-03-30T18:12:28.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "yieryi/cesium-native", "max_issues_repo_path": "Cesium3DTilesSelection/src/upgradeBatchTableToFeatureMetadata.h", "max_line_length": 69, "max_stars_count": 154, "max_stars_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "yieryi/cesium-native", "max_stars_repo_path": "Cesium3DTilesSelection/src/upgradeBatchTableToFeatureMetadata.h", "max_stars_repo_stars_event_max_datetime": "2022-03-30T00:01:43.000Z", "max_stars_repo_stars_event_min_datetime": "2021-03-30T14:08:39.000Z", "num_tokens": 192, "size": 744 }
#include <stdio.h> #include <math.h> #include <stdlib.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_blas.h> #include "mathfunctions.h" #include "globals.h" #include "constitutive_equations.h" /*****************************************************************************/ /***************************************************************************/ /************ Compute the spatial discretization of the equation ***********/ /***************************************************************************/ extern const double g; extern void Compute_InnerProducts(double IP1[], double IP2[], double IP3[], double IP4[], double IP5[], double IP6[], double IP7[], double IP8[], double IP9[], double IP10[]); extern void RoeFlux( double *Fhat, double A_L, double A_R, double Q_L, double Q_R, double b, double m1val, double m2val, double g); extern void LF(double *Fhat, double A_L, double A_R, double Q_L, double Q_R, double b, double g); extern void* xcalloc(int items, int size); extern void GetLGLWeights(int N, double *w); void computeL() { double* Fhat1L = xcalloc(NumNodes, sizeof(double)); double* Fhat2L = xcalloc(NumNodes, sizeof(double)); double* Fhat1R = xcalloc(NumNodes, sizeof(double)); double* Fhat2R = xcalloc(NumNodes, sizeof(double)); #ifdef WDON /**** Compute the mass over an element to use later for ensuring ********/ /**** positive mass with the flux in a wetting and drying treatment *************/ double mass[NumEl]; double LGLWeight[Np]; GetLGLWeights(P, LGLWeight); for (int i = 0; i < NumEl; ++i) { double avgArea = 0; int begNode = i*Np + 1; for (int j =0; j < Np; j++) { avgArea += LGLWeight[j]*A[begNode+1]; } mass[i] = avgArea; } #endif /************** Compute the numerical flux at the faces *****************/ for (int i=0; i < NumEdges; ++i) { double A_L, Q_L, A_R, Q_R, m1val, m2val; int leftNode = i*Np; int rightNode = leftNode+1; m1val = m1[i]; m2val = m2[i]; double tmpF[2]; #ifdef WDON // Check to see if the elements separated by this boundary are both dry if (i > 0 && i < NumNodes-1) { if (WD[i-1] == 0 && WD[i] == 0) { // Reflection flux for the left element A_L = A[leftNode]; A_R = A_L; Q_L = Q[leftNode]; Q_R = -Q_L; //LF(tmpF, A_L, A_R, Q_L, Q_R,b[i], m1val, m2val, 0); RoeFlux(tmpF, A_L, A_R, Q_L, Q_R,b[i], m1val, m2val,0); Fhat1L[i] = tmpF[0]; Fhat2L[i] = tmpF[1]; // Reflection flux for the right element A_R = A[rightNode]; A_L = A_R; Q_R = Q[rightNode]; Q_L = -Q_R; //LF(tmpF, A_L, A_R, Q_L, Q_R, b[i], m1val, m2val, 0); RoeFlux(tmpF, A_L, A_R, Q_L, Q_R, b[i], m1val, m2val, 0); Fhat1R[i] = tmpF[0]; Fhat2R[i] = tmpF[1]; if (isnan(tmpF[0]) || isnan(tmpF[1])) { printf("both elements dry flux not a number, edge %d \n",i); exit(EXIT_FAILURE); } } } // if the elements are not both dry if ((i == 0) || (i == NumEl) || WD[i-1] == 1 || WD[i] == 1) { A_L = A[leftNode]; A_R = A[rightNode]; Q_L = Q[leftNode]; Q_R = Q[rightNode]; RoeFlux(tmpF, A_L, A_R, Q_L,Q_R,b[i], m1val, m2val, g); //LF(tmpF, A_L, A_R, Q_L,Q_R,b[i], m1val, m2val, g); if (isnan(tmpF[0]) || isnan(tmpF[1])) { printf(" both elements wet flux not a number, edge %d \n",i); exit(EXIT_FAILURE); } if (i==0 || WD[i-1] == 1) { Fhat1L[i] = tmpF[0]; Fhat2L[i] = tmpF[1]; } else { double newtmpF[2]; //LF(newtmpF, A_L, A_R, Q_L, Q_R, b[i], m1val, m2val, 0); RoeFlux(newtmpF, A_L, A_R, Q_L, Q_R, b[i], m1val, m2val, 0); Fhat1L[i] = newtmpF[0]; Fhat2L[i] = newtmpF[1]; if (isnan(newtmpF[0]) || isnan(newtmpF[1])) { printf("left element dry flux not a number, edge %d \n",i); exit(EXIT_FAILURE); } } if (i == NumEl || WD[i]==1) { Fhat1R[i] = tmpF[0]; Fhat2R[i] = tmpF[1]; } else { //LF(tmpF, A_L,A_R,Q_L,Q_R,b[i], m1val, m2val, 0); RoeFlux(tmpF, A_L,A_R,Q_L,Q_R,b[i], m1val, m2val, 0); Fhat1R[i] = tmpF[0]; Fhat2R[i] = tmpF[1]; if (isnan(tmpF[0]) || isnan(tmpF[1])) { printf("right element dry flux not a number, edge %d \n",i); exit(EXIT_FAILURE); } } } #else A_L = A[leftNode]; A_R = A[rightNode]; Q_L = Q[leftNode]; Q_R = Q[rightNode]; RoeFlux(tmpF, A_L, A_R, Q_L,Q_R,b[i],m1val,m2val,g); //LF(tmpF, A_L, A_R, Q_L,Q_R,b[i],m1val,m2val,g); if (isnan(tmpF[0]) || isnan(tmpF[1])) { printf("flux not a number, edge %d \n",i); printf("A_L = %lf A_R = %lf Q_L = %lf Q_R = %lf, b = %lf, m1 = %lf, m2 = %lf \n", A_L, A_R, Q_L, Q_R, b[i], m1val, m2val); exit(EXIT_FAILURE); } Fhat1L[i] = tmpF[0]; Fhat2L[i] = tmpF[1]; Fhat1R[i] = tmpF[0]; Fhat2R[i] = tmpF[1]; #endif /**************************************************************************************************/ double u_L = Q_L/A_L; double u_R = Q_R/A_R; double c_L = sqrt(g*A_L/b[i]); double c_R = sqrt(g*A_R/b[i]); if (i==0) max_lambda = fmax((fabs(u_L)+c_L), (fabs(u_R)+c_R)); // Compute maximum eigenvalue for the next time step double current_max =fmax((fabs(u_L) + c_L), (fabs(u_R) + c_R)); max_lambda = max((max_lambda),(current_max)); } printf("max_lambda = %lf\n", max_lambda); #ifdef WDON for (int i =1; i < NumNodes-1; ++i) { int leftNode = i*Np; int rightNode = leftNode+1; double maxBetaOverAlpha = 2; // Check to see if this flux might possibly result in negative mass // If the mass will be negative on the left side if (Fhat1L[i]*maxBetaOverAlpha*dt > mass[i-1]) { double A_L = A[leftNode]; double A_R = A_L; double Q_L = Q[leftNode]; double Q_R = -Q_L; double tmpF[2]; double localG = g; if (WD[i] == 0) localG = 0; //LF(tmpF, A_L, A_R, Q_L, Q_R, b[i],m1val,m2val,localG); RoeFlux(tmpF, A_L, A_R, Q_L, Q_R, b[i],m1val,m2val,localG); Fhat1L[i] = tmpF[0]; Fhat2L[i] = tmpF[1]; printf("element %d will be dry\n",i); } // If the mass will be negative on the right side if (-Fhat1R[i]*maxBetaOverAlpha*dt > mass[i]) { double A_R = A[rightNode]; double A_L = A_R; double Q_R = Q[rightNode]; double Q_L = -Q_R; double tmpF[2]; double localG = g; if (WD[i] == 0) localG = 0; //LF(tmpF, A_L, A_R, Q_L, Q_R, b[i],m1val,m2val,localG); RoeFlux(tmpF, A_L, A_R, Q_L, Q_R, b[i],m1val,m2val,localG); Fhat1R[i] = tmpF[0]; Fhat2R[i] = tmpF[1]; printf("element %d will be dry \n",i); } } #endif // Compute the right hand side // double IP1[NumEl], IP2[NumEl], IP3[NumEl], IP4[NumEl], IP5[NumEl], IP6[NumEl], IP7[NumEl], IP8[NumEl], IP9[NumEl], IP10[NumEl]; // Compute_InnerProducts(IP1, IP2, IP3, IP4, IP5, IP6, IP7, IP8, IP9, IP10); int k; for (k=0; k < NumEl; ++k) { double h = dh[k]; gsl_vector *F1 = gsl_vector_alloc(Np); gsl_vector *F2 = gsl_vector_alloc(Np); gsl_vector *ST21 = gsl_vector_alloc(Np); gsl_vector *ST22 = gsl_vector_alloc(Np); gsl_vector *ST23 = gsl_vector_alloc(Np); int begNode = k*Np; for (int i = 0; i < Np; i++) { double Aval = A[begNode+i+1]; double Qval = Q[begNode+i+1]; double bval = NodalB[begNode+i]; double S0 = dz[begNode+i]; double m1val = Nodalm1[begNode+i]; double m2val = Nodalm2[begNode+i]; double dm1val = dm1[begNode+i]; double dm2val = dm2[begNode+i]; double hval = getH(Aval, bval, m1val, m2val); double I1val = getI1(Aval, bval, m1val, m2val); double I2val = getI2(Aval, bval, db[k*Np+i], m1val, dm1val, m2val, dm2val); double Sfval = getS_f(Aval, Qval, bval, m1val, m2val, NodalnFriction[begNode+i]); double beta = 1.0; double localG; #ifdef WDON if(WD[k]==1) localG = g; else localG = 0; #else localG = g; #endif gsl_vector_set(F1, i, Qval); gsl_vector_set(F2, i, beta*Qval*Qval/Aval + g*I1val); gsl_vector_set(ST21, i, g*I2val); //gsl_vector_set(ST22, i, g*hval*bval*S0); gsl_vector_set(ST22, i, g*Aval*S0); gsl_vector_set(ST23, i, g*Aval*Sfval); } gsl_vector *localFhat1 = gsl_vector_alloc(2); gsl_vector_set(localFhat1, 0, Fhat1R[k]); gsl_vector_set(localFhat1, 1, Fhat1L[k+1]); gsl_vector *localFhat2 = gsl_vector_alloc(2); gsl_vector_set(localFhat2, 0, Fhat2R[k]); gsl_vector_set(localFhat2, 1, Fhat2L[k+1]); // cacluate the volume integral of the flux gsl_vector *localRHS1 = gsl_vector_calloc(Np); gsl_vector *localRHS2 = gsl_vector_calloc(Np); gsl_blas_dgemv(CblasNoTrans, 2.0/h, VolMat, F1, 1.0, localRHS1); gsl_blas_dgemv(CblasNoTrans, 2.0/h, VolMat, F2, 1.0, localRHS2); // calculate the surface integral of the flux gsl_vector *SurfPart1 = gsl_vector_calloc(Np); gsl_vector *SurfPart2 = gsl_vector_calloc(Np); gsl_blas_dgemv(CblasNoTrans, 2.0/h, LIFT, localFhat1, 1.0, SurfPart1); gsl_blas_dgemv(CblasNoTrans, 2.0/h, LIFT, localFhat2, 1.0, SurfPart2); // calculate the RHS gsl_vector_add(localRHS1, SurfPart1); gsl_vector_add(localRHS2, SurfPart2); gsl_vector_add(localRHS2, ST21); gsl_vector_add(localRHS2, ST22); gsl_vector_sub(localRHS2, ST23); gsl_vector_free(F1); gsl_vector_free(F2); gsl_vector_free(localFhat1); gsl_vector_free(localFhat2); gsl_vector_free(SurfPart1); gsl_vector_free(SurfPart2); gsl_vector_free(ST21); gsl_vector_free(ST22); gsl_vector_free(ST23); for(int i = 0; i < Np; i++) { RHSA[begNode+i+1] = gsl_vector_get(localRHS1, i); RHSQ[begNode+i+1] = gsl_vector_get(localRHS2, i); } gsl_vector_free(localRHS1); gsl_vector_free(localRHS2); /* double F_el1[2] = {Fhat1R[k], Fhat1L[k+1]}; double F_el2[2] = {Fhat2R[k], Fhat2L[k+1]}; double invMrow1[2] = {4/h, -2/h}; double invMrow2[2] = {-2/h, 4/h}; //double invM[2][2] = {{4/(b-a), 2/(a-b)},{2/(a-b), 4/(b-a)}}; double S1 = IP1[k] + F_el1[0]; double S2 = IP2[k] - F_el1[1]; double S3 = IP3[k] + F_el2[0] + IP4[k] + IP5[k] - IP6[k]; double S4 = IP7[k] - F_el2[1] + IP8[k] + IP9[k] - IP10[k]; // Compute RHSA = invM*[S1;S2] and RHSQ = invM*[S3;S4] RHSA[2*k + 1] = invMrow1[0]*S1 + invMrow1[1]*S2; RHSA[2*k + 2] = invMrow2[0]*S1 + invMrow2[1]*S2; RHSQ[2*k + 1] = invMrow1[0]*S3 + invMrow1[1]*S4; RHSQ[2*k + 2] = invMrow2[0]*S3 + invMrow2[1]*S4; */ } // The value at the ghost nodes will be the same as the values at the other side of the face RHSA[0] = RHSA[1]; RHSA[NumNodes - 1] = RHSA[NumNodes - 2]; RHSQ[0] = RHSQ[1]; RHSQ[NumNodes - 1] = RHSQ[NumNodes - 2]; free(Fhat1L); free(Fhat1R); free(Fhat2L); free(Fhat2R); }
{ "alphanum_fraction": 0.5892135676, "avg_line_length": 27.8612565445, "ext": "c", "hexsha": "e4458da3afdf60d29c9700c88931488eb2f679bb", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-04-03T20:59:00.000Z", "max_forks_repo_forks_event_min_datetime": "2019-06-18T02:50:05.000Z", "max_forks_repo_head_hexsha": "f4765de2050adedfbe57ea25437c54de1f05ca9c", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "evalseth/DG-RAIN", "max_forks_repo_path": "1DCode/computeL.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "f4765de2050adedfbe57ea25437c54de1f05ca9c", "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": "evalseth/DG-RAIN", "max_issues_repo_path": "1DCode/computeL.c", "max_line_length": 175, "max_stars_count": 1, "max_stars_repo_head_hexsha": "f4765de2050adedfbe57ea25437c54de1f05ca9c", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "evalseth/DG-RAIN", "max_stars_repo_path": "1DCode/computeL.c", "max_stars_repo_stars_event_max_datetime": "2021-10-05T12:23:11.000Z", "max_stars_repo_stars_event_min_datetime": "2021-10-05T12:23:11.000Z", "num_tokens": 4136, "size": 10643 }
/** * * @file testing_dtrsm.c * * PLASMA testing routines * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author Mathieu Faverge * @date 2010-11-15 * @generated d Tue Jan 7 11:45:18 2014 * **/ #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> #include "testing_dmain.h" #undef COMPLEX #define REAL static int check_solution(PLASMA_enum side, PLASMA_enum uplo, PLASMA_enum trans, PLASMA_enum diag, int M, int N, double alpha, double *A, int LDA, double *Bref, double *Bplasma, int LDB); int testing_dtrsm(int argc, char **argv) { /* Check for number of arguments*/ if ( argc != 5 ) { USAGE("TRSM", "alpha M N LDA LDB", " - alpha : alpha coefficient\n" " - M : number of rows of matrices B\n" " - N : number of columns of matrices B\n" " - LDA : leading dimension of matrix A\n" " - LDB : leading dimension of matrix B\n"); return -1; } double alpha = (double) atol(argv[0]); int M = atoi(argv[1]); int N = atoi(argv[2]); int LDA = atoi(argv[3]); int LDB = atoi(argv[4]); double eps; int info_solution; int s, u, t, d, i; int LDAxM = LDA*max(M,N); int LDBxN = LDB*max(M,N); double *A = (double *)malloc(LDAxM*sizeof(double)); #pragma omp register([LDAxM]A) double *B = (double *)malloc(LDBxN*sizeof(double)); #pragma omp register([LDBxN]B) double *Binit = (double *)malloc(LDBxN*sizeof(double)); #pragma omp register([LDBxN]Binit) double *Bfinal = (double *)malloc(LDBxN*sizeof(double)); #pragma omp register([LDBxN]Bfinal) /* Check if unable to allocate memory */ if ( (!A) || (!B) || (!Binit) || (!Bfinal)){ printf("Out of Memory \n "); return -2; } eps = LAPACKE_dlamch_work('e'); printf("\n"); printf("------ TESTS FOR PLASMA DTRSM ROUTINE ------- \n"); printf(" Size of the Matrix B : %d by %d\n", M, N); printf("\n"); printf(" The matrix A is randomly generated for each test.\n"); printf("============\n"); printf(" The relative machine precision (eps) is to be %e \n",eps); printf(" Computational tests pass if scaled residuals are less than 10.\n"); /*---------------------------------------------------------- * TESTING DTRSM */ /* Initialize A, B, C */ LAPACKE_dlarnv_work(IONE, ISEED, LDAxM, A); LAPACKE_dlarnv_work(IONE, ISEED, LDBxN, B); for(i=0;i<max(M,N);i++) A[LDA*i+i] = A[LDA*i+i] + 2.0; for (s=0; s<2; s++) { for (u=0; u<2; u++) { #ifdef COMPLEX for (t=0; t<3; t++) { #else for (t=0; t<2; t++) { #endif for (d=0; d<2; d++) { memcpy(Binit, B, LDBxN*sizeof(double)); memcpy(Bfinal, B, LDBxN*sizeof(double)); /* PLASMA DTRSM */ PLASMA_dtrsm(side[s], uplo[u], trans[t], diag[d], M, N, alpha, A, LDA, Bfinal, LDB); /* Check the solution */ info_solution = check_solution(side[s], uplo[u], trans[t], diag[d], M, N, alpha, A, LDA, Binit, Bfinal, LDB); printf("***************************************************\n"); if (info_solution == 0) { printf(" ---- TESTING DTRSM (%s, %s, %s, %s) ...... PASSED !\n", sidestr[s], uplostr[u], transstr[t], diagstr[d]); } else { printf(" ---- TESTING DTRSM (%s, %s, %s, %s) ... FAILED !\n", sidestr[s], uplostr[u], transstr[t], diagstr[d]); } printf("***************************************************\n"); } } } } free(A); free(B); free(Binit); free(Bfinal); return 0; } /*-------------------------------------------------------------- * Check the solution */ static int check_solution(PLASMA_enum side, PLASMA_enum uplo, PLASMA_enum trans, PLASMA_enum diag, int M, int N, double alpha, double *A, int LDA, double *Bref, double *Bplasma, int LDB) { int info_solution; double Anorm, Binitnorm, Bplasmanorm, Blapacknorm, Rnorm, result; double eps; double mzone = (double)-1.0; double *work = (double *)malloc(max(M, N)* sizeof(double)); int Am, An; if (side == PlasmaLeft) { Am = M; An = M; } else { Am = N; An = N; } Anorm = LAPACKE_dlantr_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), lapack_const(uplo), lapack_const(diag), Am, An, A, LDA, work); Binitnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), M, N, Bref, LDB, work); Bplasmanorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), M, N, Bplasma, LDB, work); cblas_dtrsm(CblasColMajor, (CBLAS_SIDE)side, (CBLAS_UPLO)uplo, (CBLAS_TRANSPOSE)trans, (CBLAS_DIAG)diag, M, N, (alpha), A, LDA, Bref, LDB); Blapacknorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), M, N, Bref, LDB, work); cblas_daxpy(LDB * N, (mzone), Bplasma, 1, Bref, 1); Rnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), M, N, Bref, LDB, work); eps = LAPACKE_dlamch_work('e'); printf("Rnorm %e, Anorm %e, Binitnorm %e, Bplasmanorm %e, Blapacknorm %e\n", Rnorm, Anorm, Binitnorm, Bplasmanorm, Blapacknorm); result = Rnorm / ((Anorm + Blapacknorm) * max(M,N) * eps); printf("============\n"); printf("Checking the norm of the difference against reference DTRSM \n"); printf("-- ||Cplasma - Clapack||_oo/((||A||_oo+||B||_oo).N.eps) = %e \n", result); if ( isinf(Blapacknorm) || isinf(Bplasmanorm) || isnan(result) || isinf(result) || (result > 10.0) ) { printf("-- The solution is suspicious ! \n"); info_solution = 1; } else { printf("-- The solution is CORRECT ! \n"); info_solution= 0 ; } free(work); return info_solution; }
{ "alphanum_fraction": 0.5150826133, "avg_line_length": 33.8307692308, "ext": "c", "hexsha": "af8b4a6231a73548a1abbba0042e781fdaf52ef9", "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": "testing/testing_dtrsm.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": "testing/testing_dtrsm.c", "max_line_length": 124, "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": "testing/testing_dtrsm.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1922, "size": 6597 }
#pragma once #include <vector> #include <chrono> #include <complex> #include <boost/circular_buffer.hpp> #include <gsl/gsl_odeiv.h> #include "Tract.h" class SpeechSynthesizer { public: double h_min; private: // vocal chord const double m1; // mass 1 of vocal cords const double m2; // mass 2 of vocal cords const double d1; // thickness of m1 const double d2; // thickness of m2 const double lg; // effective length of vocal chords const double es; // nonlinear spring coeff. const double eh; const double ks1; // linear spring coeff. const double ks2; const double kh1; const double kh2; const double kc; // coupling spring coeff. const double om1; double Ag0; double p_s; double x1, x2, v1, v2; boost::circular_buffer<double> ug_buf; // front : current (latest) value double dydt[5]; // vocal tract const double toVelum; const double toSinus; const double toConstr; const double R_sin; const double L_sin; const double C_sin; Tract oral, nasal; double *z_in_curr, *h_out_curr; double *z_in_prev, *h_out_prev; // other params const double r_N; const double r_vib; // simulation params const double dt, df; const int N; const double calcSpan; double lastCalcSpan; double lastCalcTime; gsl_odeiv_system system; gsl_odeiv_step *step; double t; public: SpeechSynthesizer(int sampling, int freqResolution, std::vector<double> &tractArea, double dl); ~SpeechSynthesizer(void); double Step(void); double GetTime(void); private: static int Differentiate(double t, const double y[], double dydt[], void *params); void CalcTract(void); void CalcResponse(double res[], const std::complex<double> spec[]); void GetTractImpedance(double res[], double t); void GetOutputImpedance(double res[], double t); };
{ "alphanum_fraction": 0.6935483871, "avg_line_length": 26.1971830986, "ext": "h", "hexsha": "2566245854d4e5ffe626a2b09dc568fb875cf4b2", "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": "4f9ce82c59419b0a54c38607521fa30fe3ad22af", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "kinoh/VoiceSynthesis", "max_forks_repo_path": "SpeechSynthesizer.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "4f9ce82c59419b0a54c38607521fa30fe3ad22af", "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": "kinoh/VoiceSynthesis", "max_issues_repo_path": "SpeechSynthesizer.h", "max_line_length": 97, "max_stars_count": 4, "max_stars_repo_head_hexsha": "4f9ce82c59419b0a54c38607521fa30fe3ad22af", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "kinoh/VoiceSynthesis", "max_stars_repo_path": "SpeechSynthesizer.h", "max_stars_repo_stars_event_max_datetime": "2018-12-27T04:58:04.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-01T16:36:25.000Z", "num_tokens": 483, "size": 1860 }
#ifndef matops_h #define matops_h #include <ceed.h> #include <petsc.h> #include <petscdmplex.h> #include "structs.h" PetscErrorCode MatGetDiag(Mat A, Vec D); PetscErrorCode ApplyLocal_Ceed(Vec X, Vec Y, UserO user); PetscErrorCode MatMult_Ceed(Mat A, Vec X, Vec Y); PetscErrorCode FormResidual_Ceed(SNES snes, Vec X, Vec Y, void *ctx); PetscErrorCode MatMult_Prolong(Mat A, Vec X, Vec Y); PetscErrorCode MatMult_Restrict(Mat A, Vec X, Vec Y); PetscErrorCode ComputeErrorMax(UserO user, CeedOperator op_error, Vec X, CeedVector target, PetscReal *max_error); #endif // matops_h
{ "alphanum_fraction": 0.7336601307, "avg_line_length": 30.6, "ext": "h", "hexsha": "fa416e730e006952e3e7f4f0f77e00b7b1d62132", "lang": "C", "max_forks_count": 41, "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:02:07.000Z", "max_forks_repo_forks_event_min_datetime": "2017-12-27T22:35:13.000Z", "max_forks_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "AdelekeBankole/libCEED", "max_forks_repo_path": "examples/petsc/include/matops.h", "max_issues_count": 781, "max_issues_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_issues_repo_issues_event_max_datetime": "2022-03-29T21:34:34.000Z", "max_issues_repo_issues_event_min_datetime": "2017-12-22T17:20:35.000Z", "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "AdelekeBankole/libCEED", "max_issues_repo_path": "examples/petsc/include/matops.h", "max_line_length": 79, "max_stars_count": 123, "max_stars_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "AdelekeBankole/libCEED", "max_stars_repo_path": "examples/petsc/include/matops.h", "max_stars_repo_stars_event_max_datetime": "2022-03-21T18:13:48.000Z", "max_stars_repo_stars_event_min_datetime": "2018-01-29T02:04:05.000Z", "num_tokens": 175, "size": 612 }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include "compearth.h" #ifdef COMPEARTH_USE_MKL #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wreserved-id-macro" #pragma clang diagnostic ignored "-Wstrict-prototypes" #endif #include <mkl_cblas.h> #ifdef __clang__ #pragma clang diagnostic pop #endif #else #include <cblas.h> #endif /*! * @brief Computes the angle between moment tensors. This is from * Equation 15 of Tape and Tape 2016 - A confidence parameter for * seismic moment tensors * * @param[in] n Number of moment tensors. * @param[in] M1in First moment tensor packed {m11, m22, m33, m12, m13, m23}. * This is an array of dimension [6 x n] with leading * dimension 6. * @param[in] M2in Second moment tensor packed {m11, m22, m33, m12, m13, m23}. * This is an array of dimension [6 x n] with leading * dimension 6. * * @param[out] theta Angle between moment tensors M1 and M2 in radians. * This is an array of dimension [n]. * * @result 0 indicates success. * * @author Ben Baker * * @copyright MIT * */ int compearth_angleMT(const int n, const double *__restrict__ M1in, const double *__restrict__ M2in, double *__restrict__ theta) { double M1[9*CE_CHUNKSIZE] __attribute__((aligned(64))); double M2[9*CE_CHUNKSIZE] __attribute__((aligned(64))); double M1_mag[CE_CHUNKSIZE] __attribute__((aligned(64))); double M2_mag[CE_CHUNKSIZE] __attribute__((aligned(64))); double xden[CE_CHUNKSIZE] __attribute__((aligned(64))); double arg[CE_CHUNKSIZE] __attribute__((aligned(64))); double xnum[CE_CHUNKSIZE] __attribute__((aligned(64))); int i, ierr, imt, nmtLoc; ierr = 0; for (imt=0; imt<n; imt=imt+CE_CHUNKSIZE) { nmtLoc = MIN(CE_CHUNKSIZE, n - imt); // Convert to 3x3 matrices compearth_Mvec2Mmat(nmtLoc, &M1in[6*imt], 1, M1); compearth_Mvec2Mmat(nmtLoc, &M2in[6*imt], 1, M2); // Compute norms ierr = compearth_normMat(nmtLoc, M1, CE_TWO_NORM, 2.0, M1_mag); ierr = compearth_normMat(nmtLoc, M2, CE_TWO_NORM, 2.0, M2_mag); // Compute the denomimators for (i=0; i<nmtLoc; i++) { xden[i] = M1_mag[i]*M2_mag[i]; } // Compute the numerators for (i=0; i<nmtLoc; i++) { xnum[i] = cblas_ddot(9, &M1[9*i], 1, &M2[9*i], 1); } // Compute argument and do all checks for (i=0; i<nmtLoc; i++) { // Can't divide by zero - force this to work b/c M1 or M2 is // equivalently 0. if (xden[i] == 0.0) { xnum[i] = 0.0; xden[i] = 1.0; fprintf(stderr, "%s: Denominator is 0\n", __func__); } arg[i] = xnum[i]/xden[i]; // Correct for numerical errors if (arg[i] <-1.0) { fprintf(stdout, "%s: Warning arg is %f setting to -1\n", __func__, arg[i]); arg[i] =-1.0; } if (arg[i] > 1.0) { fprintf(stdout, "%s: Warning arg is %f setting to +1\n", __func__, arg[i]); arg[i] = 1.0; } } // Finally compute the angle for (i=0; i<nmtLoc; i++) { theta[imt+i] = acos(arg[i]); } } return ierr; }
{ "alphanum_fraction": 0.5429125138, "avg_line_length": 33.1376146789, "ext": "c", "hexsha": "cf066095cbf0b58a98ca91884025bb368bd67791", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2022-02-28T13:42:40.000Z", "max_forks_repo_forks_event_min_datetime": "2021-07-08T00:13:50.000Z", "max_forks_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "carltape/mtbeach", "max_forks_repo_path": "c_src/angleMT.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655", "max_issues_repo_issues_event_max_datetime": "2017-11-02T17:30:53.000Z", "max_issues_repo_issues_event_min_datetime": "2017-11-02T17:30:53.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "carltape/mtbeach", "max_issues_repo_path": "c_src/angleMT.c", "max_line_length": 81, "max_stars_count": 9, "max_stars_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "OUCyf/mtbeach", "max_stars_repo_path": "c_src/angleMT.c", "max_stars_repo_stars_event_max_datetime": "2022-02-28T23:55:36.000Z", "max_stars_repo_stars_event_min_datetime": "2021-03-13T01:18:12.000Z", "num_tokens": 1030, "size": 3612 }
//CELL (~soma) stage: IIR filtering of each row or col of X according to dim. //The IIR filters are specified by an Nx(Q+1) or (Q+1)xN matrix A, //where Q is the IIR filter order (Q=0 means only a0; Q=1 means a0 and a1; etc.). //The calling program must ensure that the sizes are correct, the filter is stable, etc. //I just started this... finish later!! (Or skip.) #include <stdio.h> #include <cblas.h> #ifdef __cplusplus namespace ov { extern "C" { #endif int iir_s (float *Y, const float *X, const float *A, const size_t N, const size_t T, const int Q, const char iscolmajor, const size_t dim); int iir_d (double *Y, const double *X, const double *A, const size_t N, const size_t T, const int Q, const char iscolmajor, const size_t dim); int iir_c (float *Y, const float *X, const float *A, const size_t N, const size_t T, const int Q, const char iscolmajor, const size_t dim); int iir_z (double *Y, const double *X, const double *A, const size_t N, const size_t T, const int Q, const char iscolmajor, const size_t dim); int iir_inplace_s (float *X, const float *A, const size_t N, const size_t T, const int Q, const char iscolmajor, const size_t dim); int iir_inplace_d (double *X, const double *A, const size_t N, const size_t T, const int Q, const char iscolmajor, const size_t dim); int iir_inplace_c (float *X, const float *A, const size_t N, const size_t T, const int Q, const char iscolmajor, const size_t dim); int iir_inplace_z (double *X, const double *A, const size_t N, const size_t T, const int Q, const char iscolmajor, const size_t dim); int iir_inplace_s (float *X, const float *A, const size_t N, const size_t T, const int Q, const char iscolmajor, const size_t dim) { const size_t M = Q - 1; int n, t; //Checks if (N<1) { fprintf(stderr,"error in iir_s: N (num neurons) must be positive\n"); return 1; } if (T<1) { fprintf(stderr,"error in iir_s: T (num time points) must be positive\n"); return 1; } if (Q<0) { fprintf(stderr,"error in iir_s: Q (filter order) must be nonnegative\n"); return 1; } if (N==1u) { if (A[0]!=1.0f) { cblas_sscal((int)T,1.0f/A[0],A,1); cblas_sscal((int)(N*T),1.0f/A[0],X,1); } for (size_t t=1; t<M; ++t) { X[t] -= cblas_sdot(t,&A[M-t],1,&X[0],1); } for (size_t t=M; t<T; ++t) { X[t] -= cblas_sdot(M,&A[0],1,&X[t-M],1); } } else if (dim==0u) { if (N<3) { if (iscolmajor) { for (size_t n=0u; n<N; ++n) { if (A[n*Q1]!=1.0f) { cblas_sscal((int)T,1.0f/A[n*Q1],&A[n*Q1],1); } } for (size_t n=1; n<M; ++n) { X[n] -= cblas_sdot(n,&A[M-n],1,&X[0],1); X[n+R] -= cblas_sdot(n,&A[M-n],1,&X[R],1); } for (size_t n=M; n<R; ++n) { X[n] -= cblas_sdot(M,&A[0],1,&X[n-M],1); X[n+R] -= cblas_sdot(M,&A[0],1,&X[n-M+R],1); } } else { for (size_t n=1; n<M; ++n) { X[n*C] -= cblas_sdot(n,&A[M-n],1,&X[0],(int)C); X[1+n*C] -= cblas_sdot(n,&A[M-n],1,&X[1],(int)C); } for (size_t n=M; n<R; ++n) { X[n*C] -= cblas_sdot(M,&A[0],1,&X[(n-M)*C],(int)C); X[1+n*C] -= cblas_sdot(M,&A[0],1,&X[1+(n-M)*C],(int)C); } } } else { if (iscolmajor) { for (size_t n=1; n<M; ++n) { cblas_sgemv(CblasColMajor,CblasTrans,n,(int)C,-1.0f,&X[0],(int)R,&A[M-n],1,1.0f,&X[n],(int)R); } for (size_t n=M; n<R; ++n) { cblas_sgemv(CblasColMajor,CblasTrans,M,(int)C,-1.0f,&X[n-M],(int)R,&A[0],1,1.0f,&X[n],(int)R); } } else { for (size_t n=1; n<M; ++n) { cblas_sgemv(CblasRowMajor,CblasTrans,n,(int)C,-1.0f,&X[0],(int)C,&A[M-n],1,1.0f,&X[n*C],1); } for (size_t n=M; n<R; ++n) { cblas_sgemv(CblasRowMajor,CblasTrans,M,(int)C,-1.0f,&X[(n-M)*C],(int)C,&A[0],1,1.0f,&X[n*C],1); } } } } else if (dim==1u) { if (R==1) { for (size_t n=1; n<M; ++n) { X[n] -= cblas_sdot(n,&A[M-n],1,&X[0],1); } for (size_t n=M; n<C; ++n) { X[n] -= cblas_sdot(M,&A[0],1,&X[n-M],1); } } else if (R==2) { if (iscolmajor) { for (size_t n=1; n<M; ++n) { X[n*R] -= cblas_sdot(n,&A[M-n],1,&X[0],(int)R); X[1+n*R] -= cblas_sdot(n,&A[M-n],1,&X[1],(int)R); } for (size_t n=M; n<C; ++n) { X[n*R] -= cblas_sdot(M,&A[0],1,&X[(n-M)*R],(int)R); X[1+n*R] -= cblas_sdot(M,&A[0],1,&X[1+(n-M)*R],(int)R); } } else { for (size_t n=1; n<M; ++n) { X[n] -= cblas_sdot(n,&A[M-n],1,&X[0],1); X[n+C] -= cblas_sdot(n,&A[M-n],1,&X[C],1); } for (size_t n=M; n<C; ++n) { X[n] -= cblas_sdot(M,&A[0],1,&X[n-M],1); X[n+C] -= cblas_sdot(M,&A[0],1,&X[n-M+C],1); } } } else { if (iscolmajor) { for (size_t n=1; n<M; ++n) { cblas_sgemv(CblasColMajor,CblasNoTrans,(int)R,n,-1.0f,&X[0],(int)R,&A[M-n],1,1.0f,&X[n*R],1); } for (size_t n=M; n<C; ++n) { cblas_sgemv(CblasColMajor,CblasNoTrans,(int)R,M,-1.0f,&X[(n-M)*R],(int)R,&A[0],1,1.0f,&X[n*R],1); } } else { for (size_t n=1; n<M; ++n) { cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)R,n,-1.0f,&X[0],(int)C,&A[M-n],1,1.0f,&X[n],(int)C); } for (size_t n=M; n<C; ++n) { cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)R,M,-1.0f,&X[n-M],(int)C,&A[0],1,1.0f,&X[n],(int)C); } } } } else { fprintf(stderr,"error in iir_s: dim must be 0 or 1.\n"); return 1; } return 0; } int iir_d (double *X, const char iscolmajor, const size_t R, const size_t C, const double *A, const size_t N, const size_t dim) { const size_t M = N - 1; int n; //Checks if (R<1) { fprintf(stderr,"error in iir_d: R (nrows X) must be positive\n"); return 1; } if (C<1) { fprintf(stderr,"error in iir_d: C (ncols X) must be positive\n"); return 1; } if (N<1) { fprintf(stderr,"error in iir_d: N (filter order) must be positive\n"); return 1; } if (dim==0u) { if (C==1) { for (size_t n=1; n<M; ++n) { X[n] -= cblas_ddot(n,&A[M-n],1,&X[0],1); } for (size_t n=M; n<R; ++n) { X[n] -= cblas_ddot(M,&A[0],1,&X[n-M],1); } } else if (C==2) { if (iscolmajor) { for (size_t n=1; n<M; ++n) { X[n] -= cblas_ddot(n,&A[M-n],1,&X[0],1); X[n+R] -= cblas_ddot(n,&A[M-n],1,&X[R],1); } for (size_t n=M; n<R; ++n) { X[n] -= cblas_ddot(M,&A[0],1,&X[n-M],1); X[n+R] -= cblas_ddot(M,&A[0],1,&X[n-M+R],1); } } else { for (size_t n=1; n<M; ++n) { X[n*C] -= cblas_ddot(n,&A[M-n],1,&X[0],(int)C); X[1+n*C] -= cblas_ddot(n,&A[M-n],1,&X[1],(int)C); } for (size_t n=M; n<R; ++n) { X[n*C] -= cblas_ddot(M,&A[0],1,&X[(n-M)*C],(int)C); X[1+n*C] -= cblas_ddot(M,&A[0],1,&X[1+(n-M)*C],(int)C); } } } else { if (iscolmajor) { for (size_t n=1; n<M; ++n) { cblas_dgemv(CblasColMajor,CblasTrans,n,(int)C,-1.0,&X[0],(int)R,&A[M-n],1,1.0,&X[n],(int)R); } for (size_t n=M; n<R; ++n) { cblas_dgemv(CblasColMajor,CblasTrans,M,(int)C,-1.0,&X[n-M],(int)R,&A[0],1,1.0,&X[n],(int)R); } } else { for (size_t n=1; n<M; ++n) { cblas_dgemv(CblasRowMajor,CblasTrans,n,(int)C,-1.0,&X[0],(int)C,&A[M-n],1,1.0,&X[n*C],1); } for (size_t n=M; n<R; ++n) { cblas_dgemv(CblasRowMajor,CblasTrans,M,(int)C,-1.0,&X[(n-M)*C],(int)C,&A[0],1,1.0,&X[n*C],1); } } } } else if (dim==1u) { if (R==1) { for (size_t n=1; n<M; ++n) { X[n] -= cblas_ddot(n,&A[M-n],1,&X[0],1); } for (size_t n=M; n<C; ++n) { X[n] -= cblas_ddot(M,&A[0],1,&X[n-M],1); } } else if (R==2) { if (iscolmajor) { for (size_t n=1; n<M; ++n) { X[n*R] -= cblas_ddot(n,&A[M-n],1,&X[0],(int)R); X[1+n*R] -= cblas_ddot(n,&A[M-n],1,&X[1],(int)R); } for (size_t n=M; n<C; ++n) { X[n*R] -= cblas_ddot(M,&A[0],1,&X[(n-M)*R],(int)R); X[1+n*R] -= cblas_ddot(M,&A[0],1,&X[1+(n-M)*R],(int)R); } } else { for (size_t n=1; n<M; ++n) { X[n] -= cblas_ddot(n,&A[M-n],1,&X[0],1); X[n+C] -= cblas_ddot(n,&A[M-n],1,&X[C],1); } for (size_t n=M; n<C; ++n) { X[n] -= cblas_ddot(M,&A[0],1,&X[n-M],1); X[n+C] -= cblas_ddot(M,&A[0],1,&X[n-M+C],1); } } } else { if (iscolmajor) { for (size_t n=1; n<M; ++n) { cblas_dgemv(CblasColMajor,CblasNoTrans,(int)R,n,-1.0,&X[0],(int)R,&A[M-n],1,1.0,&X[n*R],1); } for (size_t n=M; n<C; ++n) { cblas_dgemv(CblasColMajor,CblasNoTrans,(int)R,M,-1.0,&X[(n-M)*R],(int)R,&A[0],1,1.0,&X[n*R],1); } } else { for (size_t n=1; n<M; ++n) { cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)R,n,-1.0,&X[0],(int)C,&A[M-n],1,1.0,&X[n],(int)C); } for (size_t n=M; n<C; ++n) { cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)R,M,-1.0,&X[n-M],(int)C,&A[0],1,1.0,&X[n],(int)C); } } } } else { fprintf(stderr,"error in iir_d: dim must be 0 or 1.\n"); return 1; } return 0; } int iir_c (float *X, const char iscolmajor, const size_t R, const size_t C, const float *A, const size_t N, const size_t dim) { const float a[2] = {-1.0f,0.0f}, b[2] = {1.0f,0.0f}; const size_t M = N - 1; int n; //Checks if (R<1) { fprintf(stderr,"error in iir_c: R (nrows X) must be positive\n"); return 1; } if (C<1) { fprintf(stderr,"error in iir_c: C (ncols X) must be positive\n"); return 1; } if (N<1) { fprintf(stderr,"error in iir_c: N (filter order) must be positive\n"); return 1; } if (dim==0u) { if (iscolmajor) { for (size_t n=1; n<M; ++n) { cblas_cgemv(CblasColMajor,CblasTrans,n,(int)C,&a[0],&X[0],(int)R,&A[2*(M-n)],1,&b[0],&X[2*n],(int)R); } for (size_t n=M; n<R; ++n) { cblas_cgemv(CblasColMajor,CblasTrans,M,(int)C,&a[0],&X[2*(n-M)],(int)R,&A[0],1,&b[0],&X[2*n],(int)R); } } else { for (size_t n=1; n<M; ++n) { cblas_cgemv(CblasRowMajor,CblasTrans,n,(int)C,&a[0],&X[0],(int)C,&A[2*(M-n)],1,&b[0],&X[2*n*C],1); } for (size_t n=M; n<R; ++n) { cblas_cgemv(CblasRowMajor,CblasTrans,M,(int)C,&a[0],&X[2*(n-M)*C],(int)C,&A[0],1,&b[0],&X[2*n*C],1); } } } else if (dim==1u) { if (iscolmajor) { for (size_t n=1; n<M; ++n) { cblas_cgemv(CblasColMajor,CblasNoTrans,(int)R,n,&a[0],&X[0],(int)R,&A[2*(M-n)],1,&b[0],&X[2*n*R],1); } for (size_t n=M; n<C; ++n) { cblas_cgemv(CblasColMajor,CblasNoTrans,(int)R,M,&a[0],&X[2*(n-M)*R],(int)R,&A[0],1,&b[0],&X[2*n*R],1); } } else { for (size_t n=1; n<M; ++n) { cblas_cgemv(CblasRowMajor,CblasNoTrans,(int)R,n,&a[0],&X[0],(int)C,&A[2*(M-n)],1,&b[0],&X[2*n],(int)C); } for (size_t n=M; n<C; ++n) { cblas_cgemv(CblasRowMajor,CblasNoTrans,(int)R,M,&a[0],&X[2*(n-M)],(int)C,&A[0],1,&b[0],&X[2*n],(int)C); } } } else { fprintf(stderr,"error in iir_c: dim must be 0 or 1.\n"); return 1; } return 0; } int iir_z (double *X, const char iscolmajor, const size_t R, const size_t C, const double *A, const size_t N, const size_t dim) { const double a[2] = {-1.0,0.0}, b[2] = {1.0,0.0}; const size_t M = N - 1; int n; //Checks if (R<1) { fprintf(stderr,"error in iir_z: R (nrows X) must be positive\n"); return 1; } if (C<1) { fprintf(stderr,"error in iir_z: C (ncols X) must be positive\n"); return 1; } if (N<1) { fprintf(stderr,"error in iir_z: N (filter order) must be positive\n"); return 1; } if (dim==0u) { if (iscolmajor) { for (size_t n=1; n<M; ++n) { cblas_zgemv(CblasColMajor,CblasTrans,n,(int)C,&a[0],&X[0],(int)R,&A[2*(M-n)],1,&b[0],&X[2*n],(int)R); } for (size_t n=M; n<R; ++n) { cblas_zgemv(CblasColMajor,CblasTrans,M,(int)C,&a[0],&X[2*(n-M)],(int)R,&A[0],1,&b[0],&X[2*n],(int)R); } } else { for (size_t n=1; n<M; ++n) { cblas_zgemv(CblasRowMajor,CblasTrans,n,(int)C,&a[0],&X[0],(int)C,&A[2*(M-n)],1,&b[0],&X[2*n*C],1); } for (size_t n=M; n<R; ++n) { cblas_zgemv(CblasRowMajor,CblasTrans,M,(int)C,&a[0],&X[2*(n-M)*C],(int)C,&A[0],1,&b[0],&X[2*n*C],1); } } } else if (dim==1u) { if (iscolmajor) { for (size_t n=1; n<M; ++n) { cblas_zgemv(CblasColMajor,CblasNoTrans,(int)R,n,&a[0],&X[0],(int)R,&A[2*(M-n)],1,&b[0],&X[2*n*R],1); } for (size_t n=M; n<C; ++n) { cblas_zgemv(CblasColMajor,CblasNoTrans,(int)R,M,&a[0],&X[2*(n-M)*R],(int)R,&A[0],1,&b[0],&X[2*n*R],1); } } else { for (size_t n=1; n<M; ++n) { cblas_zgemv(CblasRowMajor,CblasNoTrans,(int)R,n,&a[0],&X[0],(int)C,&A[2*(M-n)],1,&b[0],&X[2*n],(int)C); } for (size_t n=M; n<C; ++n) { cblas_zgemv(CblasRowMajor,CblasNoTrans,(int)R,M,&a[0],&X[2*(n-M)],(int)C,&A[0],1,&b[0],&X[2*n],(int)C); } } } else { fprintf(stderr,"error in iir_z: dim must be 0 or 1.\n"); return 1; } return 0; } #ifdef __cplusplus } } #endif
{ "alphanum_fraction": 0.4530954312, "avg_line_length": 40.2065217391, "ext": "c", "hexsha": "70803d683e9474b510312a9d2f1b444d95b93675", "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": "c4b8317a38a72a16fd0bf905791b6c19e49c0aa7", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "erikedwards4/nn", "max_forks_repo_path": "c/iir.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "c4b8317a38a72a16fd0bf905791b6c19e49c0aa7", "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/nn", "max_issues_repo_path": "c/iir.c", "max_line_length": 146, "max_stars_count": 1, "max_stars_repo_head_hexsha": "c4b8317a38a72a16fd0bf905791b6c19e49c0aa7", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "erikedwards4/nn", "max_stars_repo_path": "c/iir.c", "max_stars_repo_stars_event_max_datetime": "2020-08-26T09:28:40.000Z", "max_stars_repo_stars_event_min_datetime": "2020-08-26T09:28:40.000Z", "num_tokens": 5553, "size": 14796 }
/* specfunc/trig.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 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. */ /* Author: G. Jungman */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_sf_log.h> #include <gsl/gsl_sf_trig.h> #include "error.h" #include "chebyshev.h" #include "cheb_eval.c" /* sinh(x) series * double-precision for |x| < 1.0 */ inline static int sinh_series(const double x, double * result) { const double y = x*x; const double c0 = 1.0/6.0; const double c1 = 1.0/120.0; const double c2 = 1.0/5040.0; const double c3 = 1.0/362880.0; const double c4 = 1.0/39916800.0; const double c5 = 1.0/6227020800.0; const double c6 = 1.0/1307674368000.0; const double c7 = 1.0/355687428096000.0; *result = x*(1.0 + y*(c0+y*(c1+y*(c2+y*(c3+y*(c4+y*(c5+y*(c6+y*c7)))))))); return GSL_SUCCESS; } /* cosh(x)-1 series * double-precision for |x| < 1.0 */ inline static int cosh_m1_series(const double x, double * result) { const double y = x*x; const double c0 = 0.5; const double c1 = 1.0/24.0; const double c2 = 1.0/720.0; const double c3 = 1.0/40320.0; const double c4 = 1.0/3628800.0; const double c5 = 1.0/479001600.0; const double c6 = 1.0/87178291200.0; const double c7 = 1.0/20922789888000.0; const double c8 = 1.0/6402373705728000.0; *result = y*(c0+y*(c1+y*(c2+y*(c3+y*(c4+y*(c5+y*(c6+y*(c7+y*c8)))))))); return GSL_SUCCESS; } /* Chebyshev expansion for f(t) = sinc((t+1)/2), -1 < t < 1 */ static double sinc_data[17] = { 1.133648177811747875422, -0.532677564732557348781, -0.068293048346633177859, 0.033403684226353715020, 0.001485679893925747818, -0.000734421305768455295, -0.000016837282388837229, 0.000008359950146618018, 0.000000117382095601192, -0.000000058413665922724, -0.000000000554763755743, 0.000000000276434190426, 0.000000000001895374892, -0.000000000000945237101, -0.000000000000004900690, 0.000000000000002445383, 0.000000000000000009925 }; static cheb_series sinc_cs = { sinc_data, 16, -1, 1, 10 }; /* Chebyshev expansion for f(t) = g((t+1)Pi/8), -1<t<1 * g(x) = (sin(x)/x - 1)/(x*x) */ static double sin_data[12] = { -0.3295190160663511504173, 0.0025374284671667991990, 0.0006261928782647355874, -4.6495547521854042157541e-06, -5.6917531549379706526677e-07, 3.7283335140973803627866e-09, 3.0267376484747473727186e-10, -1.7400875016436622322022e-12, -1.0554678305790849834462e-13, 5.3701981409132410797062e-16, 2.5984137983099020336115e-17, -1.1821555255364833468288e-19 }; static cheb_series sin_cs = { sin_data, 11, -1, 1, 11 }; /* Chebyshev expansion for f(t) = g((t+1)Pi/8), -1<t<1 * g(x) = (2(cos(x) - 1)/(x^2) + 1) / x^2 */ static double cos_data[11] = { 0.165391825637921473505668118136, -0.00084852883845000173671196530195, -0.000210086507222940730213625768083, 1.16582269619760204299639757584e-6, 1.43319375856259870334412701165e-7, -7.4770883429007141617951330184e-10, -6.0969994944584252706997438007e-11, 2.90748249201909353949854872638e-13, 1.77126739876261435667156490461e-14, -7.6896421502815579078577263149e-17, -3.7363121133079412079201377318e-18 }; static cheb_series cos_cs = { cos_data, 10, -1, 1, 10 }; /*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/ /* I would have prefered just using the library sin() function. * But after some experimentation I decided that there was * no good way to understand the error; library sin() is just a black box. * So we have to roll our own. */ int gsl_sf_sin_e(double x, gsl_sf_result * result) { /* CHECK_POINTER(result) */ { const double P1 = 7.85398125648498535156e-1; const double P2 = 3.77489470793079817668e-8; const double P3 = 2.69515142907905952645e-15; const double sgn_x = GSL_SIGN(x); const double abs_x = fabs(x); if(abs_x < GSL_ROOT4_DBL_EPSILON) { const double x2 = x*x; result->val = x * (1.0 - x2/6.0); result->err = fabs(x*x2*x2 / 100.0); return GSL_SUCCESS; } else { double sgn_result = sgn_x; double y = floor(abs_x/(0.25*M_PI)); int octant = y - ldexp(floor(ldexp(y,-3)),3); int stat_cs; double z; if(GSL_IS_ODD(octant)) { octant += 1; octant &= 07; y += 1.0; } if(octant > 3) { octant -= 4; sgn_result = -sgn_result; } z = ((abs_x - y * P1) - y * P2) - y * P3; if(octant == 0) { gsl_sf_result sin_cs_result; const double t = 8.0*fabs(z)/M_PI - 1.0; stat_cs = cheb_eval_e(&sin_cs, t, &sin_cs_result); result->val = z * (1.0 + z*z * sin_cs_result.val); } else { /* octant == 2 */ gsl_sf_result cos_cs_result; const double t = 8.0*fabs(z)/M_PI - 1.0; stat_cs = cheb_eval_e(&cos_cs, t, &cos_cs_result); result->val = 1.0 - 0.5*z*z * (1.0 - z*z * cos_cs_result.val); } result->val *= sgn_result; if(abs_x > 1.0/GSL_DBL_EPSILON) { result->err = fabs(result->val); } else if(abs_x > 100.0/GSL_SQRT_DBL_EPSILON) { result->err = 2.0 * abs_x * GSL_DBL_EPSILON * fabs(result->val); } else if(abs_x > 0.1/GSL_SQRT_DBL_EPSILON) { result->err = 2.0 * GSL_SQRT_DBL_EPSILON * fabs(result->val); } else { result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val); } return stat_cs; } } } int gsl_sf_cos_e(double x, gsl_sf_result * result) { /* CHECK_POINTER(result) */ { const double P1 = 7.85398125648498535156e-1; const double P2 = 3.77489470793079817668e-8; const double P3 = 2.69515142907905952645e-15; const double abs_x = fabs(x); if(abs_x < GSL_ROOT4_DBL_EPSILON) { const double x2 = x*x; result->val = 1.0 - 0.5*x2; result->err = fabs(x2*x2/12.0); return GSL_SUCCESS; } else { double sgn_result = 1.0; double y = floor(abs_x/(0.25*M_PI)); int octant = y - ldexp(floor(ldexp(y,-3)),3); int stat_cs; double z; if(GSL_IS_ODD(octant)) { octant += 1; octant &= 07; y += 1.0; } if(octant > 3) { octant -= 4; sgn_result = -sgn_result; } if(octant > 1) { sgn_result = -sgn_result; } z = ((abs_x - y * P1) - y * P2) - y * P3; if(octant == 0) { gsl_sf_result cos_cs_result; const double t = 8.0*fabs(z)/M_PI - 1.0; stat_cs = cheb_eval_e(&cos_cs, t, &cos_cs_result); result->val = 1.0 - 0.5*z*z * (1.0 - z*z * cos_cs_result.val); } else { /* octant == 2 */ gsl_sf_result sin_cs_result; const double t = 8.0*fabs(z)/M_PI - 1.0; stat_cs = cheb_eval_e(&sin_cs, t, &sin_cs_result); result->val = z * (1.0 + z*z * sin_cs_result.val); } result->val *= sgn_result; if(abs_x > 1.0/GSL_DBL_EPSILON) { result->err = fabs(result->val); } else if(abs_x > 100.0/GSL_SQRT_DBL_EPSILON) { result->err = 2.0 * abs_x * GSL_DBL_EPSILON * fabs(result->val); } else if(abs_x > 0.1/GSL_SQRT_DBL_EPSILON) { result->err = 2.0 * GSL_SQRT_DBL_EPSILON * fabs(result->val); } else { result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val); } return stat_cs; } } } int gsl_sf_hypot_e(const double x, const double y, gsl_sf_result * result) { /* CHECK_POINTER(result) */ if(x == 0.0 && y == 0.0) { result->val = 0.0; result->err = 0.0; return GSL_SUCCESS; } else { const double a = fabs(x); const double b = fabs(y); const double min = GSL_MIN_DBL(a,b); const double max = GSL_MAX_DBL(a,b); const double rat = min/max; const double root_term = sqrt(1.0 + rat*rat); if(max < GSL_DBL_MAX/root_term) { result->val = max * root_term; result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else { OVERFLOW_ERROR(result); } } } int gsl_sf_complex_sin_e(const double zr, const double zi, gsl_sf_result * szr, gsl_sf_result * szi) { /* CHECK_POINTER(szr) */ /* CHECK_POINTER(szi) */ if(fabs(zi) < 1.0) { double ch_m1, sh; sinh_series(zi, &sh); cosh_m1_series(zi, &ch_m1); szr->val = sin(zr)*(ch_m1 + 1.0); szi->val = cos(zr)*sh; szr->err = 2.0 * GSL_DBL_EPSILON * fabs(szr->val); szi->err = 2.0 * GSL_DBL_EPSILON * fabs(szi->val); return GSL_SUCCESS; } else if(fabs(zi) < GSL_LOG_DBL_MAX) { double ex = exp(zi); double ch = 0.5*(ex+1.0/ex); double sh = 0.5*(ex-1.0/ex); szr->val = sin(zr)*ch; szi->val = cos(zr)*sh; szr->err = 2.0 * GSL_DBL_EPSILON * fabs(szr->val); szi->err = 2.0 * GSL_DBL_EPSILON * fabs(szi->val); return GSL_SUCCESS; } else { OVERFLOW_ERROR_2(szr, szi); } } int gsl_sf_complex_cos_e(const double zr, const double zi, gsl_sf_result * czr, gsl_sf_result * czi) { /* CHECK_POINTER(czr) */ /* CHECK_POINTER(czi) */ if(fabs(zi) < 1.0) { double ch_m1, sh; sinh_series(zi, &sh); cosh_m1_series(zi, &ch_m1); czr->val = cos(zr)*(ch_m1 + 1.0); czi->val = -sin(zr)*sh; czr->err = 2.0 * GSL_DBL_EPSILON * fabs(czr->val); czi->err = 2.0 * GSL_DBL_EPSILON * fabs(czi->val); return GSL_SUCCESS; } else if(fabs(zi) < GSL_LOG_DBL_MAX) { double ex = exp(zi); double ch = 0.5*(ex+1.0/ex); double sh = 0.5*(ex-1.0/ex); czr->val = cos(zr)*ch; czi->val = -sin(zr)*sh; czr->err = 2.0 * GSL_DBL_EPSILON * fabs(czr->val); czi->err = 2.0 * GSL_DBL_EPSILON * fabs(czi->val); return GSL_SUCCESS; } else { OVERFLOW_ERROR_2(czr,czi); } } int gsl_sf_complex_logsin_e(const double zr, const double zi, gsl_sf_result * lszr, gsl_sf_result * lszi) { /* CHECK_POINTER(lszr) */ /* CHECK_POINTER(lszi) */ if(zi > 60.0) { lszr->val = -M_LN2 + zi; lszi->val = 0.5*M_PI - zr; lszr->err = 2.0 * GSL_DBL_EPSILON * fabs(lszr->val); lszi->err = 2.0 * GSL_DBL_EPSILON * fabs(lszi->val); } else if(zi < -60.0) { lszr->val = -M_LN2 - zi; lszi->val = -0.5*M_PI + zr; lszr->err = 2.0 * GSL_DBL_EPSILON * fabs(lszr->val); lszi->err = 2.0 * GSL_DBL_EPSILON * fabs(lszi->val); } else { gsl_sf_result sin_r, sin_i; int status; gsl_sf_complex_sin_e(zr, zi, &sin_r, &sin_i); /* ok by construction */ status = gsl_sf_complex_log_e(sin_r.val, sin_i.val, lszr, lszi); if(status == GSL_EDOM) { DOMAIN_ERROR_2(lszr, lszi); } } return gsl_sf_angle_restrict_symm_e(&(lszi->val)); } int gsl_sf_lnsinh_e(const double x, gsl_sf_result * result) { /* CHECK_POINTER(result) */ if(x <= 0.0) { DOMAIN_ERROR(result); } else if(fabs(x) < 1.0) { double eps; sinh_series(x, &eps); result->val = log(eps); result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else if(x < -0.5*GSL_LOG_DBL_EPSILON) { result->val = x + log(0.5*(1.0 - exp(-2.0*x))); result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else { result->val = -M_LN2 + x; result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } } int gsl_sf_lncosh_e(const double x, gsl_sf_result * result) { /* CHECK_POINTER(result) */ if(fabs(x) < 1.0) { double eps; cosh_m1_series(x, &eps); return gsl_sf_log_1plusx_e(eps, result); } else if(x < -0.5*GSL_LOG_DBL_EPSILON) { result->val = x + log(0.5*(1.0 + exp(-2.0*x))); result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else { result->val = -M_LN2 + x; result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } } /* inline int gsl_sf_sincos_e(const double theta, double * s, double * c) { double tan_half = tan(0.5 * theta); double den = 1. + tan_half*tan_half; double cos_theta = (1.0 - tan_half*tan_half) / den; double sin_theta = 2.0 * tan_half / den; } */ int gsl_sf_polar_to_rect(const double r, const double theta, gsl_sf_result * x, gsl_sf_result * y) { double t = theta; int status = gsl_sf_angle_restrict_symm_e(&t); double c = cos(t); double s = sin(t); x->val = r * cos(t); y->val = r * sin(t); x->err = r * fabs(s * GSL_DBL_EPSILON * t); x->err += 2.0 * GSL_DBL_EPSILON * fabs(x->val); y->err = r * fabs(c * GSL_DBL_EPSILON * t); y->err += 2.0 * GSL_DBL_EPSILON * fabs(y->val); return status; } int gsl_sf_rect_to_polar(const double x, const double y, gsl_sf_result * r, gsl_sf_result * theta) { int stat_h = gsl_sf_hypot_e(x, y, r); if(r->val > 0.0) { theta->val = atan2(y, x); theta->err = 2.0 * GSL_DBL_EPSILON * fabs(theta->val); return stat_h; } else { DOMAIN_ERROR(theta); } } int gsl_sf_angle_restrict_symm_err_e(const double theta, gsl_sf_result * result) { /* synthetic extended precision constants */ const double P1 = 4 * 7.8539812564849853515625e-01; const double P2 = 4 * 3.7748947079307981766760e-08; const double P3 = 4 * 2.6951514290790594840552e-15; const double TwoPi = 2*(P1 + P2 + P3); const double y = GSL_SIGN(theta) * 2 * floor(fabs(theta)/TwoPi); double r = ((theta - y*P1) - y*P2) - y*P3; if(r > M_PI) { r = (((r-2*P1)-2*P2)-2*P3); } /* r-TwoPi */ else if (r < -M_PI) r = (((r+2*P1)+2*P2)+2*P3); /* r+TwoPi */ result->val = r; if(fabs(theta) > 0.0625/GSL_DBL_EPSILON) { result->val = GSL_NAN; result->err = GSL_NAN; GSL_ERROR ("error", GSL_ELOSS); } else if(fabs(theta) > 0.0625/GSL_SQRT_DBL_EPSILON) { result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val - theta); return GSL_SUCCESS; } else { double delta = fabs(result->val - theta); result->err = 2.0 * GSL_DBL_EPSILON * ((delta < M_PI) ? delta : M_PI); return GSL_SUCCESS; } } int gsl_sf_angle_restrict_pos_err_e(const double theta, gsl_sf_result * result) { /* synthetic extended precision constants */ const double P1 = 4 * 7.85398125648498535156e-01; const double P2 = 4 * 3.77489470793079817668e-08; const double P3 = 4 * 2.69515142907905952645e-15; const double TwoPi = 2*(P1 + P2 + P3); const double y = 2*floor(theta/TwoPi); double r = ((theta - y*P1) - y*P2) - y*P3; if(r > TwoPi) {r = (((r-2*P1)-2*P2)-2*P3); } /* r-TwoPi */ else if (r < 0) { /* may happen due to FP rounding */ r = (((r+2*P1)+2*P2)+2*P3); /* r+TwoPi */ } result->val = r; if(fabs(theta) > 0.0625/GSL_DBL_EPSILON) { result->val = GSL_NAN; result->err = fabs(result->val); GSL_ERROR ("error", GSL_ELOSS); } else if(fabs(theta) > 0.0625/GSL_SQRT_DBL_EPSILON) { result->err = GSL_DBL_EPSILON * fabs(result->val - theta); return GSL_SUCCESS; } else { double delta = fabs(result->val - theta); result->err = 2.0 * GSL_DBL_EPSILON * ((delta < M_PI) ? delta : M_PI); return GSL_SUCCESS; } } int gsl_sf_angle_restrict_symm_e(double * theta) { gsl_sf_result r; int stat = gsl_sf_angle_restrict_symm_err_e(*theta, &r); *theta = r.val; return stat; } int gsl_sf_angle_restrict_pos_e(double * theta) { gsl_sf_result r; int stat = gsl_sf_angle_restrict_pos_err_e(*theta, &r); *theta = r.val; return stat; } int gsl_sf_sin_err_e(const double x, const double dx, gsl_sf_result * result) { int stat_s = gsl_sf_sin_e(x, result); result->err += fabs(cos(x) * dx); result->err += GSL_DBL_EPSILON * fabs(result->val); return stat_s; } int gsl_sf_cos_err_e(const double x, const double dx, gsl_sf_result * result) { int stat_c = gsl_sf_cos_e(x, result); result->err += fabs(sin(x) * dx); result->err += GSL_DBL_EPSILON * fabs(result->val); return stat_c; } #if 0 int gsl_sf_sin_pi_x_e(const double x, gsl_sf_result * result) { /* CHECK_POINTER(result) */ if(-100.0 < x && x < 100.0) { result->val = sin(M_PI * x) / (M_PI * x); result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else { const double N = floor(x + 0.5); const double f = x - N; if(N < INT_MAX && N > INT_MIN) { /* Make it an integer if we can. Saves another * call to floor(). */ const int intN = (int)N; const double sign = ( GSL_IS_ODD(intN) ? -1.0 : 1.0 ); result->val = sign * sin(M_PI * f); result->err = GSL_DBL_EPSILON * fabs(result->val); } else if(N > 2.0/GSL_DBL_EPSILON || N < -2.0/GSL_DBL_EPSILON) { /* All integer-valued floating point numbers * bigger than 2/eps=2^53 are actually even. */ result->val = 0.0; result->err = 0.0; } else { const double resN = N - 2.0*floor(0.5*N); /* 0 for even N, 1 for odd N */ const double sign = ( fabs(resN) > 0.5 ? -1.0 : 1.0 ); result->val = sign * sin(M_PI*f); result->err = GSL_DBL_EPSILON * fabs(result->val); } return GSL_SUCCESS; } } #endif int gsl_sf_sinc_e(double x, gsl_sf_result * result) { /* CHECK_POINTER(result) */ { const double ax = fabs(x); if(ax < 0.8) { /* Do not go to the limit of the fit since * there is a zero there and the Chebyshev * accuracy will go to zero. */ return cheb_eval_e(&sinc_cs, 2.0*ax-1.0, result); } else if(ax < 100.0) { /* Small arguments are no problem. * We trust the library sin() to * roughly machine precision. */ result->val = sin(M_PI * ax)/(M_PI * ax); result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else { /* Large arguments must be handled separately. */ const double r = M_PI*ax; gsl_sf_result s; int stat_s = gsl_sf_sin_e(r, &s); result->val = s.val/r; result->err = s.err/r + 2.0 * GSL_DBL_EPSILON * fabs(result->val); return stat_s; } } } /*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/ #include "eval.h" double gsl_sf_sin(const double x) { EVAL_RESULT(gsl_sf_sin_e(x, &result)); } double gsl_sf_cos(const double x) { EVAL_RESULT(gsl_sf_cos_e(x, &result)); } double gsl_sf_hypot(const double x, const double y) { EVAL_RESULT(gsl_sf_hypot_e(x, y, &result)); } double gsl_sf_lnsinh(const double x) { EVAL_RESULT(gsl_sf_lnsinh_e(x, &result)); } double gsl_sf_lncosh(const double x) { EVAL_RESULT(gsl_sf_lncosh_e(x, &result)); } double gsl_sf_angle_restrict_symm(const double theta) { double result = theta; EVAL_DOUBLE(gsl_sf_angle_restrict_symm_e(&result)); } double gsl_sf_angle_restrict_pos(const double theta) { double result = theta; EVAL_DOUBLE(gsl_sf_angle_restrict_pos_e(&result)); } #if 0 double gsl_sf_sin_pi_x(const double x) { EVAL_RESULT(gsl_sf_sin_pi_x_e(x, &result)); } #endif double gsl_sf_sinc(const double x) { EVAL_RESULT(gsl_sf_sinc_e(x, &result)); }
{ "alphanum_fraction": 0.6141632425, "avg_line_length": 25.5349740933, "ext": "c", "hexsha": "a604cd86a5a1544802ff1e0e876a1b36b81990fd", "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/specfunc/trig.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/specfunc/trig.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/specfunc/trig.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": 6917, "size": 19713 }
#ifndef I3SPRNGRANDOMSERVICE_H #define I3SPRNGRANDOMSERVICE_H #include "phys-services/I3RandomService.h" #include <gsl/gsl_randist.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_test.h> #include <string> /** * copyright (C) 2004 * the icecube collaboration * $Id: I3SPRNGRandomService.h 127790 2015-01-14 04:03:06Z olivas $ * * @brief SPRNG Implementation of the I3RandomService interface. * This implementation uses a combination of SPRNG and GSL to generate * statistically independent streams of pseudo-random number distributions. * See gsl-sprng.h for more details. * * NB : It's important that you use the same seed for different jobs. Set * nstreams to the number of jobs and use a different streamnum for each job. * Otherwise you'll get correlations between the RNG streams. I know this is * counterintuitive, but this is how SPRNG works. * * The code for this class is based on John Pretz's implementation of * I3GSLRandomService. * * @version $Revision: 127790 $ * @date $Date: 2015-01-13 21:03:06 -0700 (Tue, 13 Jan 2015) $ * @author juancarlos * * @todo Add ability to save state of rng after run is complete * SPRNG has the functions: * * int pack_sprng(char *bytes); // returns size of bytes * void unpack_sprng(char bytes[MAX_PACKED_LENGTH]); * * which can be used to save and retrieve the state of an rng */ class I3SPRNGRandomService : public I3RandomService{ public: /** * default constructor */ I3SPRNGRandomService(); /** * constructors */ I3SPRNGRandomService(int seed, int nstreams, int streamnum, std::string instatefile=std::string(), std::string outstatefile=std::string()); /** * destructor */ virtual ~I3SPRNGRandomService(); /** * Binomial distribution */ virtual int Binomial(int ntot, double prob); // As with John Pretz's GSL implementation, I have left this out for now. /* virtual double BreitWigner(double mean = 0, double gamma = 1)=0; */ /** * Exponential distribution */ virtual double Exp(double tau); /** * Uniform int distribution with range [0,imax) */ virtual unsigned int Integer(unsigned int imax); /** * int Poisson distribution */ virtual int Poisson(double mean); /** * double Poisson distribution */ virtual double PoissonD(double mean); /** * double uniform distribution with range (0,x1) */ virtual double Uniform(double x1 = 1); /** * double uniform distribution with range (x1,x2) */ virtual double Uniform(double x1, double x2); /** * double Gaussian distribution given mean and StdD */ virtual double Gaus(double mean, double stddev); virtual I3FrameObjectPtr GetState() const; virtual void RestoreState(I3FrameObjectConstPtr state); private: // private copy constructors and assignment I3SPRNGRandomService(const I3SPRNGRandomService& ); I3SPRNGRandomService operator=(const I3SPRNGRandomService& ); gsl_rng* rng_; std::string instatefile_; std::string outstatefile_; int seed_; int streamnum_; int nstreams_; SET_LOGGER("I3SPRNGRandomService"); }; I3_POINTER_TYPEDEFS(I3SPRNGRandomService); #endif // I3SPRNGRANDOMSERVICE_H
{ "alphanum_fraction": 0.70562636, "avg_line_length": 24.7461538462, "ext": "h", "hexsha": "9a0cb07bd168dceebc58864e933de1a5c829429e", "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/I3SPRNGRandomService.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/I3SPRNGRandomService.h", "max_line_length": 77, "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/I3SPRNGRandomService.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": 865, "size": 3217 }
/* * Player - One Hell of a Robot Server * Copyright (C) 2000 Brian Gerkey & Kasper Stoy * gerkey@usc.edu kaspers@robotics.usc.edu * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ /************************************************************************** * Desc: Useful pdf functions * Author: Andrew Howard * Date: 10 Dec 2002 * CVS: $Id: pf_pdf.h 6345 2008-04-17 01:36:39Z gerkey $ *************************************************************************/ #ifndef PF_PDF_H #define PF_PDF_H #include "nav2d_localizer/pf_vector.h" //#include <gsl/gsl_rng.h> //#include <gsl/gsl_randist.h> #ifdef __cplusplus extern "C" { #endif /************************************************************************** * Gaussian *************************************************************************/ // Gaussian PDF info typedef struct { // Mean, covariance and inverse covariance pf_vector_t x; pf_matrix_t cx; //pf_matrix_t cxi; double cxdet; // Decomposed covariance matrix (rotation * diagonal) pf_matrix_t cr; pf_vector_t cd; // A random number generator //gsl_rng *rng; } pf_pdf_gaussian_t; // Create a gaussian pdf pf_pdf_gaussian_t *pf_pdf_gaussian_alloc(pf_vector_t x, pf_matrix_t cx); // Destroy the pdf void pf_pdf_gaussian_free(pf_pdf_gaussian_t *pdf); // Compute the value of the pdf at some point [z]. //double pf_pdf_gaussian_value(pf_pdf_gaussian_t *pdf, pf_vector_t z); // Draw randomly from a zero-mean Gaussian distribution, with standard // deviation sigma. // We use the polar form of the Box-Muller transformation, explained here: // http://www.taygeta.com/random/gaussian.html double pf_ran_gaussian(double sigma); // Generate a sample from the the pdf. pf_vector_t pf_pdf_gaussian_sample(pf_pdf_gaussian_t *pdf); #if 0 /************************************************************************** * Discrete *************************************************************************/ // Discrete PDF info typedef struct { // The list of discrete probs int prob_count; double *probs; // A random number generator gsl_rng *rng; // The discrete prob generator gsl_ran_discrete_t *ran; } pf_pdf_discrete_t; // Create a discrete pdf pf_pdf_discrete_t *pf_pdf_discrete_alloc(int count, double *probs); // Destroy the pdf void pf_pdf_discrete_free(pf_pdf_discrete_t *pdf); // Compute the value of the probability of some element [i] double pf_pdf_discrete_value(pf_pdf_discrete_t *pdf, int i); // Generate a sample from the the pdf. int pf_pdf_discrete_sample(pf_pdf_discrete_t *pdf); #endif #ifdef __cplusplus } #endif #endif
{ "alphanum_fraction": 0.6353046595, "avg_line_length": 27.4426229508, "ext": "h", "hexsha": "b7cbf8975c87b0cdc76a2116d8526a733d2a5624", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2018-11-27T22:55:07.000Z", "max_forks_repo_forks_event_min_datetime": "2018-11-16T16:14:18.000Z", "max_forks_repo_head_hexsha": "0a16489a2cbd0c2d1511b506c540446cc670bde8", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "pplankton/MRSLAM", "max_forks_repo_path": "src/nav2d_localizer/include/nav2d_localizer/pf_pdf.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "0a16489a2cbd0c2d1511b506c540446cc670bde8", "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": "pplankton/MRSLAM", "max_issues_repo_path": "src/nav2d_localizer/include/nav2d_localizer/pf_pdf.h", "max_line_length": 77, "max_stars_count": 1, "max_stars_repo_head_hexsha": "cd2bb81bede9f740c3316783474d68ae7e0b480a", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "swsachith/tb3_rescue_bot", "max_stars_repo_path": "navigation_2d/nav2d_localizer/include/nav2d_localizer/pf_pdf.h", "max_stars_repo_stars_event_max_datetime": "2021-05-17T11:13:01.000Z", "max_stars_repo_stars_event_min_datetime": "2021-05-17T11:13:01.000Z", "num_tokens": 788, "size": 3348 }
#ifndef PMVS3_OPTIM_H #define PMVS3_OPTIM_H #include <vector> #include "patch.h" #include <gsl/gsl_multimin.h> namespace PMVS3 { class CfindMatch; class Coptim { public: Coptim(CfindMatch& findMatch); void init(void); //----------------------------------------------------------------- // Image manipulation //----------------------------------------------------------------- void collectImages(const int index, std::vector<int>& indexes) const; void addImages(Patch::Cpatch& patch) const; void removeImagesEdge(Patch::Cpatch& patch) const; float getUnit(const int index, const Vec4f& coord) const; void computeUnits(const Patch::Cpatch& patch, std::vector<int>& indexes, std::vector<float>& fineness, std::vector<Vec4f>& rays) const; void computeUnits(const Patch::Cpatch& patch, std::vector<float>& fineness) const; //----------------------------------------------------------------- // Optimization //----------------------------------------------------------------- int preProcess(Patch::Cpatch& patch, const int id, const int seed); void refinePatch(Patch::Cpatch& patch, const int id, const int time); void refinePatchBFGS(Patch::Cpatch& patch, const int id, const int time); void refinePatchBFGS(Patch::Cpatch& patch, const int id, const int time, const int ncc); bool refinePatchBFGS2(Patch::Cpatch& patch, const int id, const int time, const int ncc); // LM version void refineDepthBFGS(Patch::Cpatch& patch, const int id, const int time, const int ncc); int postProcess(Patch::Cpatch& patch, const int id, const int seed); void setRefImage(Patch::Cpatch& patch, const int id); int check(Patch::Cpatch& patch); std::vector<int> m_status; protected: void filterImagesByAngle(Patch::Cpatch& patch); void sortImages(Patch::Cpatch& patch) const; void constraintImages(Patch::Cpatch& patch, const float nccThreshold, const int id); void setRefConstraintImages(Patch::Cpatch& patch, const float nccThreshold, const int id); void setINCCs(const Patch::Cpatch& patch, std::vector<float> & nccs, const std::vector<int>& indexes, const int id, const int robust); void setINCCs(const Patch::Cpatch& patch, std::vector<std::vector<float> >& nccs, const std::vector<int>& indexes, const int id, const int robust); int grabTex(const Vec4f& coord, const Vec4f& pxaxis, const Vec4f& pyaxis, const Vec4f& pzaxis, const int index, const int size, std::vector<float>& tex) const; int grabSafe(const int index, const int size, const Vec3f& center, const Vec3f& dx, const Vec3f& dy, const int level) const; double computeSSD(const Vec4f& coord, const Vec4f& normal, const std::vector<int>& indexes, const int id); double computeSSD(const Vec4f& coord, const Vec4f& normal, const std::vector<int>& indexes, const Vec4f& pxaxis, const Vec4f& pyaxis, const int id); /* double computeINCC(const Vec4f& coord, const Vec4f& normal, const std::vector<int>& indexes, const int id, const int robust); */ double computeINCC(const Vec4f& coord, const Vec4f& normal, const std::vector<int>& indexes, const Vec4f& pxaxis, const Vec4f& pyaxis, const int id, const int robust); public: static void normalize(std::vector<float>& tex); static void normalize(std::vector<std::vector<float> >& texs, const int size); float dot(const std::vector<float>& tex0, const std::vector<float>& tex1) const; float ssd(const std::vector<float>& tex0, const std::vector<float>& tex1) const; protected: static void lfunc(double* p, double* hx, int m, int n, void* adata); void func(int m, int n, double* x, double* fvec, int* iflag, void* arg); //BFGS static double my_f(const gsl_vector *v, void *params); static void my_f_lm(const double *par, int m_dat, const void *data, double *fvec, int *info); // LM version static void my_df(const gsl_vector *v, void *params, gsl_vector *df); static void my_fdf(const gsl_vector *x, void *params, double *f, gsl_vector *df); // for derivative computation static double my_f0(double x, void* params); static double my_f1(double x, void* params); static double my_f2(double x, void* params); //---------------------------------------------------------------------- // For ssd static double my_f_ssd(const gsl_vector *v, void *params); static void my_df_ssd(const gsl_vector *v, void *params, gsl_vector *df); static void my_fdf_ssd(const gsl_vector *x, void *params, double *f, gsl_vector *df); // for derivative computation static double my_f_ssd0(double x, void* params); static double my_f_ssd1(double x, void* params); static double my_f_ssd2(double x, void* params); //---------------------------------------------------------------------- // For debugging depth static double my_f_depth(const gsl_vector *v, void *params); static void my_df_depth(const gsl_vector *v, void *params, gsl_vector *df); static void my_fdf_depth(const gsl_vector *x, void *params, double *f, gsl_vector *df); // for derivative computation static double my_f0_depth(double x, void* params); void encode(const Vec4f& coord, double* const vect, const int id) const; void encode(const Vec4f& coord, const Vec4f& normal, double* const vect, const int id) const; void decode(Vec4f& coord, Vec4f& normal, const double* const vect, const int id) const; void decode(Vec4f& coord, const double* const vect, const int id) const; public: void setWeightsT(const Patch::Cpatch& patch, const int id); double computeINCC(const Vec4f& coord, const Vec4f& normal, const std::vector<int>& indexes, const int id, const int robust); void getPAxes(const int index, const Vec4f& coord, const Vec4f& normal, Vec4f& pxaxis, Vec4f& pyaxis) const; static inline float robustincc(const float rhs) { return rhs / (1 + 3 * rhs); } static inline float unrobustincc(const float rhs) { return rhs / (1 - 3 * rhs); } protected: void setAxesScales(void); static Coptim* m_one; CfindMatch& m_fm; //----------------------------------------------------------------- // Axes std::vector<Vec3f> m_xaxes; std::vector<Vec3f> m_yaxes; std::vector<Vec3f> m_zaxes; // Scales std::vector<float> m_ipscales; //----------------------------------------------------------------- // For threads std::vector<float> m_vect0T; std::vector<Vec4f> m_centersT; std::vector<Vec4f> m_raysT; std::vector<std::vector<int> > m_indexesT; std::vector<float> m_dscalesT; std::vector<float> m_ascalesT; // stores current parameters for derivative computation std::vector<Vec3f> m_paramsT; // Grabbed texture std::vector<std::vector<std::vector<float> > > m_texsT; // last is 7x7x3 patch // weights for refineDepthOrientationWeighed std::vector<std::vector<float> > m_weightsT; // Working array for levmar std::vector<std::vector<double> > m_worksT; }; }; #endif // PMVS3_OPTIM_H
{ "alphanum_fraction": 0.5950575314, "avg_line_length": 37.3073170732, "ext": "h", "hexsha": "30729b6228eb63973e2348323d5b87303ddfcf57", "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": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "skair39/structured", "max_forks_repo_path": "CMVS-PMVS/program/base/pmvs/optim.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "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": "skair39/structured", "max_issues_repo_path": "CMVS-PMVS/program/base/pmvs/optim.h", "max_line_length": 109, "max_stars_count": 14, "max_stars_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "mattjr/structured", "max_stars_repo_path": "CMVS-PMVS/program/base/pmvs/optim.h", "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": 1923, "size": 7648 }
/** * * @file qwrapper_clantr.c * * PLASMA core_blas quark wrapper * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author Mathieu Faverge * @date 2010-11-15 * @generated c Tue Jan 7 11:44:57 2014 * **/ #include <lapacke.h> #include "common.h" void CORE_clantr_quark(Quark *quark); void CORE_clantr_f1_quark(Quark *quark); /***************************************************************************//** * **/ void QUARK_CORE_clantr(Quark *quark, Quark_Task_Flags *task_flags, PLASMA_enum norm, PLASMA_enum uplo, PLASMA_enum diag, int M, int N, const PLASMA_Complex32_t *A, int LDA, int szeA, int szeW, float *result) { szeW = max(1, szeW); DAG_CORE_LANGE; QUARK_Insert_Task(quark, CORE_clantr_quark, task_flags, sizeof(PLASMA_enum), &norm, VALUE, sizeof(PLASMA_enum), &uplo, VALUE, sizeof(PLASMA_enum), &diag, VALUE, sizeof(int), &M, VALUE, sizeof(int), &N, VALUE, sizeof(PLASMA_Complex32_t)*szeA, A, INPUT, sizeof(int), &LDA, VALUE, sizeof(float)*szeW, NULL, SCRATCH, sizeof(float), result, OUTPUT, 0); } /***************************************************************************//** * **/ void QUARK_CORE_clantr_f1(Quark *quark, Quark_Task_Flags *task_flags, PLASMA_enum norm, PLASMA_enum uplo, PLASMA_enum diag, int M, int N, const PLASMA_Complex32_t *A, int LDA, int szeA, int szeW, float *result, float *fake, int szeF) { szeW = max(1, szeW); DAG_CORE_LANGE; if ( result == fake ) { QUARK_Insert_Task(quark, CORE_clantr_quark, task_flags, sizeof(PLASMA_enum), &norm, VALUE, sizeof(PLASMA_enum), &uplo, VALUE, sizeof(PLASMA_enum), &diag, VALUE, sizeof(int), &M, VALUE, sizeof(int), &N, VALUE, sizeof(PLASMA_Complex32_t)*szeA, A, INPUT, sizeof(int), &LDA, VALUE, sizeof(float)*szeW, NULL, SCRATCH, sizeof(float), result, OUTPUT | GATHERV, 0); } else { QUARK_Insert_Task(quark, CORE_clantr_f1_quark, task_flags, sizeof(PLASMA_enum), &norm, VALUE, sizeof(PLASMA_enum), &uplo, VALUE, sizeof(PLASMA_enum), &diag, VALUE, sizeof(int), &M, VALUE, sizeof(int), &N, VALUE, sizeof(PLASMA_Complex32_t)*szeA, A, INPUT, sizeof(int), &LDA, VALUE, sizeof(float)*szeW, NULL, SCRATCH, sizeof(float), result, OUTPUT, sizeof(float)*szeF, fake, OUTPUT | GATHERV, 0); } } /***************************************************************************//** * **/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_clantr_quark = PCORE_clantr_quark #define CORE_clantr_quark PCORE_clantr_quark #endif void CORE_clantr_quark(Quark *quark) { float *normA; PLASMA_enum norm, uplo, diag; int M; int N; PLASMA_Complex32_t *A; int LDA; float *work; quark_unpack_args_9(quark, norm, uplo, diag, M, N, A, LDA, work, normA); *normA = LAPACKE_clantr_work( LAPACK_COL_MAJOR, lapack_const(norm), lapack_const(uplo), lapack_const(diag), M, N, A, LDA, work); } /***************************************************************************//** * **/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_clantr_f1_quark = PCORE_clantr_f1_quark #define CORE_clantr_f1_quark PCORE_clantr_f1_quark #endif void CORE_clantr_f1_quark(Quark *quark) { float *normA; PLASMA_enum norm, uplo, diag; int M; int N; PLASMA_Complex32_t *A; int LDA; float *work; float *fake; quark_unpack_args_10(quark, norm, uplo, diag, M, N, A, LDA, work, normA, fake); *normA = LAPACKE_clantr_work( LAPACK_COL_MAJOR, lapack_const(norm), lapack_const(uplo), lapack_const(diag), M, N, A, LDA, work); }
{ "alphanum_fraction": 0.4834658853, "avg_line_length": 34.3741007194, "ext": "c", "hexsha": "9947541e76e14c14d34e89ab67055a02a7198653", "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-qwrapper/qwrapper_clantr.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-qwrapper/qwrapper_clantr.c", "max_line_length": 93, "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-qwrapper/qwrapper_clantr.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1262, "size": 4778 }
/** * * Copyright (c) 2017-2020 King Abdullah University of Science and Technology * All rights reserved. * * ExaGeoStat is a software package provided by KAUST **/ /** * * @file MLE_misc.h * * Header file of auxiliary functions that are needed by ExaGeoStat. * * @version 1.1.0 * * @author Sameh Abdulah * @date 2020-06-06 * **/ #ifndef _MLE_MISC_H_ #define _MLE_MISC_H_ #include <stdbool.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <unistd.h> #include <sys/time.h> #include <stdlib.h> #include <assert.h> #include <string.h> #include "common.h" #include "descriptor.h" #include "chameleon/morse_runtime.h" #include <nlopt.h> #include <math.h> #include <morse.h> #include <lapacke.h> #include <starpu.h> #include <cblas.h> #include "../../include/flops.h" #include <starpu_profiling.h> #if defined(CHAMELEON_USE_MPI) #include <starpu_mpi.h> #else #endif #if defined(CHAMELEON_USE_CUDA) && !defined(CHAMELEON_SIMULATION) #include <starpu_scheduler.h> #include <starpu_cuda.h> #endif #include <gsl/gsl_sf_bessel.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_fft_complex.h> #include "../../include/morse_starpu.h" /** **************************************************************************** * PI value **/ #define PI (3.141592653589793) /** **************************************************************************** * The radius of the eartch (used by Great Circle Distance (GCD) **/ #define earthRadiusKm 6371.0 /** **************************************************************************** * Start timing macro **/ #define START_TIMING(_t) _t =- cWtime(); /** **************************************************************************** * Stop timing macro **/ #define STOP_TIMING(_t) _t += cWtime(); /*******************************************************************************/ /** * Internal function to return address of block (m,n) with m,n = block indices */ inline static void *chameleon_getaddr_null(const MORSE_desc_t *A, int m, int n) { (void)A; (void)m; (void)n; return NULL; } /** * Internal function to return the leading dimension of element A(m,*) with m,n = block indices */ inline static int chameleon_getblkldd_ccrb(const MORSE_desc_t *A, int m) { int mm = m + A->i / A->mb; return ( ((mm+1) == A->lmt) && ((A->lm % A->mb) != 0)) ? A->lm % A->mb : A->mb; } /** * Internal function to return MPI rank of element A(m,n) with m,n = block indices */ inline static int chameleon_getrankof_2d(const MORSE_desc_t *desc, int m, int n) { if(m>=n) return (m % desc->p) * desc->q + (n % desc->q); else return (n % desc->p) * desc->q + (m % desc->q); } /** **************************************************************************** * Allocate matrix in different modes **/ #define EXAGEOSTAT_ALLOCATE_MATRIX_TILE(_desc_, _memspace_, _type2_, _mb_, _nb_, _mbXnb_ , _lda_, _n_, _smb_, _snb_, _m_, _n2_, _p_, _q_) \ if (data->ooc && _memspace_ == NULL && _mb_ != 1 && _nb_ !=1) \ MORSE_Desc_Create_OOC(_desc_, _type2_, _mb_, _nb_, _mbXnb_, _lda_, _n_, _smb_, _snb_, _m_, _n2_, \ _p_, _q_); \ else \ MORSE_Desc_Create(_desc_, _memspace_, _type2_, _mb_, _nb_, _mbXnb_, _lda_, _n_,_smb_, _snb_ , _m_, _n2_, \ _p_, _q_); \ #define EXAGEOSTAT_ALLOCATE_FULL_MATRIX_TILE(_desc_, _memspace_, _type2_, _mb_, _nb_, _mbXnb_ , _lda_, _n_, _smb_, _snb_, _m_, _n2_, _p_, _q_) \ if (data->ooc && _memspace_ == NULL && _mb_ != 1 && _nb_ !=1) \ MORSE_Desc_Create_OOC(_desc_, _type2_, _mb_, _nb_, _mbXnb_, _lda_, _n_, _smb_, _snb_, _m_, _n2_, \ _p_, _q_); \ else \ MORSE_Desc_Create_User(_desc_, _memspace_, _type2_, _mb_, _nb_, _mbXnb_, _lda_, _n_,_smb_, _snb_ , _m_, _n2_, \ _p_, _q_, morse_getaddr_null, morse_getblkldd_ccrb, chameleon_getrankof_2d ); \ #define EXAGEOSTAT_ALLOCATE_DIAG_MATRIX_TILE(_desc_, _memspace_, _type2_, _mb_, _nb_, _mbXnb_ , _lda_, _n_, _smb_, _snb_, _m_, _n2_, _p_, _q_) \ if (data->ooc && _memspace_ == NULL && _mb_ != 1 && _nb_ !=1) \ MORSE_Desc_Create_OOC(_desc_, _type2_, _mb_, _nb_, _mbXnb_, _lda_, _n_, _smb_, _snb_, _m_, _n2_, \ _p_, _q_); \ else \ MORSE_Desc_Create_User(_desc_, _memspace_, _type2_, _mb_, _nb_, _mbXnb_, _lda_, _n_,_smb_, _snb_ , _m_, _n2_, \ _p_, _q_, morse_getaddr_null, morse_getblkldd_ccrb, morse_getrankof_2d_diag ); \ /** **************************************************************************** * Structure for identifies two dimensions struct with two vectors (x and y). **/ typedef struct { double *x; ///< Values in X dimension. double *y; ///< Values in Y dimension. double *z; ///< Values in Z dimension. } location; /** **************************************************************************** * Structure for reading real datasets through STARS-H **/ typedef struct { double xy; ///< Locations (x, y) double z; ///< Measurements. } sdata; /** **************************************************************************** * Structure for output results **/ typedef struct { int problem_size; char* computation; char* kernel; char* ds_type; char* precision; int z_sample; int dense_ts; int lr_ts; int lr_acc; int lr_maxrank; int ncores; int ngpus; int p; int q; int num_params; double *initial_theta; double *starting_theta; double *estimated_theta; double final_loglik; double time_per_iteration; double flops_per_iteration; double total_mle_time; double mse_pred1; double mse_pred2; double mse_pred; double total_pred_time; double total_pred_flops; double mloe; double mmom; char* mloe_exec; double total_mloe_mmom_time; double matrix_gen_mloe_mmom_time; double cho_fact_mloe_mmom_time; double loop_mloe_mmom_time; double total_mloe_mmom_flops; } output; /** **************************************************************************** * Structure for uniquely identifies three different parameters for accuracy * measurments accuracyDenseAppDiff, normDenseAppDiff, and normA. **/ /*typedef struct{ double accuracyDenseAppDiff; ///< Accuracy different between dense format and approx format. double normDenseAppDiff; ///< Norm difference between dense format and approx format. double normA; ///< normA. } acc_struct; */ /** **************************************************************************** * Structure for uniquely identifies different variables that are needed * by EXAGEOSTAT to ease arguments pass. **/ typedef struct { double variance; ///< Variance parameter. double variance1; ///< Variance1 parameter. double variance2; ///< Variance2 parameter. char *computation; ///< Exact or approx computation. char *c_fun; ///< Matern or pow-exp kernels. int test; ///< Synthetic or real dataset execution. int async; ///< Running mode: synchronous or asynchronous. int iter_count; ///< Number of iterations to converge. location l1; ///< 2D locations for the first dataset. location lmiss; ///< 2D locations for the missing data (prediction stage). location lobs; ///< 2D locations for the observed data (prediction stage). location lm; ///< 2D locations for the median data point. void *descC; ///< Covariance matrix C descriptor. void *descsubC11; ///< Covariance sub matrix C11 descriptor. void *descsubC12; ///< Covariance sub matrix C12 descriptor. void *descsubC21; ///< Covariance sub matrix C21 descriptor. void *descsubC22; ///< Covariance sub matrix C22 descriptor. void *descZ; ///< Measurements Z descriptor. void *descZ1; ///< Measurements Z1 submatrix descriptor. void *descZ2; ///< Measurements Z2 submatrix descriptor. double *Adense; ///< Dense matrix descriptor in the case of approximation mode - accuracy check. double *Adense2; ///< Dense matrix descriptor2 in the case of approximation mode - accuracy check. void *descZcpy; ///< A copy of Measurements Z descriptor. void *descdet; ///< Determinant descriptor. void *descproduct; ///< Dot product descriptor. void *descproduct1; ///< Dot product descriptor. void *descproduct2; ///< Dot product descriptor. void *descZmiss; ///< Missing measurements descriptor. void *descC12; ///< Covariance Matrix C12 descriptor. void *descC22; ///< Covariance Matrix C22 descriptor. void *descZactual; ///< Actual Measurements Z descriptor. void *descZobs; ///< observed Measurements Z descriptor. void *descmse1; ///< Mean Square Error (MSE) descriptor. void *descmse2; ///< Mean Square Error (MSE) descriptor. void *descmse; ///< Mean Square Error (MSE) descriptor. void *sequence; ///< MORSE sequence. void *request; ///< MORSE request. int verbose; ///< Verbose indicator. int check; ///< Check indicator -- approximation mode. int log; ///< Log files generation indicator, 0--> no, 1--> yes. double avg_exec_time_per_iter; ///< Avergae execution time per iteration (only used in verbose mode). double total_exec_time; ///< Total execution time (only used in verbose mode). double avg_flops_per_iter; ///< Avergae flops per iteration (only used in verbose mode). double final_loglik; ///< Final log likelihood value. char *locsFPath; ///< Locations file path -- in the case of real dataset (real mode). char *obsFPath; ///< Observations file path -- in the case of real dataset (real mode). char *obsFPath2; ///< Observations file path2 (bivariate case) -- in the case of real dataset (real mode). char *actualZFPath; ///< Actual observations file path -- in the case of prediction. char *actualZFPath2; ///< Actual observations file path -- in the case of prediction. char *actualZLocFPath; ///< Actial locations file path -- in the case of prediction. double det; ///< determinant value. double dotp; ///< double dot product value. double dotp1; ///< double dot2 product value. double dotp2; ///< double dot3 product value. float sdotp; ///< single dot product value. double mserror; ///< Mean Square Error (MSE) value. double mserror1; ///< Mean Square Error (MSE) value, variable 1 in case of bivariate. double mserror2; ///< Mean Square Error (MSE) value, variable 2 in case of bivariate. char *dm; ///< Distance metric to be used ed->Euclidian Distance -- gcd->Great Circle Distance. int diag_thick; ///< The thick of used diagonal in the case of diagonal approximation approach. char *nFileLog; ///< log file name (only used if log -->1). FILE *pFileLog; ///< log file path (only used if log -->1). int hicma_maxrank; ///< Max Rank in the case of LR-HiCMA approx int hicma_data_type; ///< To define the type of the problem to HiCMA (HICMA_STARSH_PROB_GEOSTAT (Synthetic) or HICMA_STARSH_PROB_GEOSTAT_POINT (real)) void *hicma_descC; ///< HiCMA descC descriptor (for accuracy check). void *hicma_descZ; ///< HiCMA descZ descriptor. void *hicma_descCD; ///< HiCMA descCD descriptor. void *hicma_descCUV; ///< HiCMA descCUV descriptor. void *hicma_descCrk; ///< HiCMA descCrk descriptor. void *hicma_descZcpy; ///< A copy of Measurements Z descriptor. void *hicma_descdet; ///< Determinant descriptor. void *hicma_descproduct; ///< Dot product descriptor. void *hicma_descC12D; ///< HiCMA descCD descriptor. void *hicma_descC12UV; ///< HiCMA descCUV descriptor. void *hicma_descC12rk; ///< HiCMA descCrk descriptor. void *hicma_descC22D; ///< HiCMA descCD descriptor. void *hicma_descC22UV; ///< HiCMA descCUV descriptor. void *hicma_descC22rk; ///< HiCMA descCrk descriptor. double hicma_acc; ///< Accuracy in the case of LR-HiCMA approx. void *hsequence; ///< HiCMA sequence. void *hrequest; ///< HiCMA request. int opt_tol; ///< The parameter tol is a tolerance that is used for the purpose of stopping criteria only. int opt_max_iters; ///< Maximum number of mle iterations. int ooc; ///< Support Out-Of-Core execution, 0-->no, 1-->yes. char* kernel_fun; ///< stationary_matern, or non_stationary_matern. int precision; ///< (0)Double, (1)Single, and (2)Mixed. //Mixed Precision void *desctemp; ///< Temporary descriptor for mixed precision Cholesky factorization. void *desctemp22; ///< Temporary descriptor for mixed precision Cholesky factorization. //MLOE and MMOM void *desck_t; void *desck_a; void *desck_ttmp; void *desck_atmp; void *descK_ttmp; void *descK_t; void *descK_a; void *descexpr1; void *descexpr2; void *descexpr3; void *descexpr4; void *descestimatedalpha; void *desctruthalpha; void *desc_mloe_mmom; double expr1; double expr2; double expr3; double expr4; double mloe; double mmom; int mloe_mmom; int mloe_mmom_async; int mspe; char* recovery_file; char* checkpoint_file; int time_slots; int idw; } MLE_data; /** **************************************************************************** * Verbose Macro. **/ #define VERBOSE(str) \ if (data->verbose == 1 && MORSE_My_Mpi_Rank() == 0){ \ fprintf(stdout, "%s", str); \ fflush(stdout);\ } /** **************************************************************************** * Success Macro. **/ #define SUCCESS(success, str) \ if (success != MORSE_SUCCESS){ \ fprintf(stdout, "%s", str);\ fflush(stdout);\ exit(EXIT_FAILURE);\ } output results; void pick_random_points(MLE_data *data, double *Zobs, double *Zactual, int nZmiss, int nZobs, int N); void generate_interior_points(MLE_data *data, double *Zobs, double *Zactual, int nZmiss, int nZobs, int N); void split_data(MLE_data * data, location *locations, double *Z, double *Zactual, int *N, int nZmiss); void init_data_values(MLE_data *data); int locations_obs_zsort_inplace(int n, location *locations, double *z); void zsort_locations_obs(int n, location *locations, double *z); double uniform_distribution(double rangeLow, double rangeHigh); void print_dmatrix(char* desc, int m, int n, double* a, int lda); void print_diagonal(char* desc, int m, double* a, int lda); void print_smatrix(char* desc, int m, int n, float* a, int lda); location* GenerateXYLoc(int n, int seed); int countlines(char *filename); void checkpointing(char *path, int iter_count, double* theta, double loglik, int num_params); bool recover(char *path, int iter_count, double* theta, double* loglik, int num_params); void write_to_file(char * path, int matrix_size,int ncores, int tile_size, int test, char *computation, int async, char *obsFPath,double total_exec_time, double avg_exec_time_per_iter, double avg_flops_per_iter, int p_grid, int q_grid, double final_loglik, int n); void theta_parser2(double *theta_vec, char * kern, int num_params); void write_vectors(double * zvec, MLE_data * data, int n); void write_to_thetafile(char * path, double *theta, int num_params, int n, double time_per_iter, int total_no_iters, double prediction_error, double mloe, double mmom); //void readObsFile(char *obsfile, int n, double * streamdata); void shuffle(double *array, location* locations, size_t n); void theta_parser(double *initial_theta, double *target_theta, double *starting_theta, char *ikernel, char *kernel, double *lb, double *up, int test, int num_params); void init_optimizer(nlopt_opt* opt, double *lb, double *up, double tol); void print_summary(int test, int N, int ncores, int gpus, int ts, int lts, char *computation, int zvecs, int p_grid, int q_grid, int precision); int print_result(MLE_data *data, double *starting_theta, int N, int zvecs, int ncores, int ts, int test, double *initial_theta, char *computation, int p_grid, int q_grid, double final_loglik, double prediction_error); double cWtime(void); void readlocfile(char* loc_file, int n, location* l1); void write_prediction_result(char *path, int matrix_size, int no_missing, double MSE1, double MSE2, double MSE, double solve_time, double flops); int doesFileExist(const char *filename); void init_log (MLE_data * data); void finalize_log (MLE_data * data); //acc_struct check_acc(MLE_data * HICMA_data, int n, int ts); double core_matern_vector (double x0, double y0, double x1, double y1, double *localtheta, int distance_metric); void pick_random_points2(MLE_data *data, double *Zobs, double *Zactual, int nZmiss, int nZobs, int N); location* GenerateXYLoc_ST(int n, int t_slots, int seed); void pick_random_points_noshuffle(MLE_data *data, double *Zobs, double *Zactual, int nZmiss, int nZobs, int N); double* pred_idw(MLE_data *data, double *z_miss, double *z_actual, double*z_obs, int nZmiss, int nZobs); void write_to_estimatedtheta(char * path, double *theta, int num_params, int n, double prediction_time, double mloe_mmom_time, double prediction_error1, double prediction_error2, double prediction_error, double mloe, double mmom, int zvecs); #endif
{ "alphanum_fraction": 0.6010273973, "avg_line_length": 39.6772823779, "ext": "h", "hexsha": "dc78477919b5a601e75ad74dc8265510bf714056", "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": "84880ccca4bd32072e128ef7f5824953973675a4", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "a10Raijin/exageostat", "max_forks_repo_path": "misc/include/MLE_misc.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "84880ccca4bd32072e128ef7f5824953973675a4", "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": "a10Raijin/exageostat", "max_issues_repo_path": "misc/include/MLE_misc.h", "max_line_length": 161, "max_stars_count": null, "max_stars_repo_head_hexsha": "84880ccca4bd32072e128ef7f5824953973675a4", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "a10Raijin/exageostat", "max_stars_repo_path": "misc/include/MLE_misc.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4769, "size": 18688 }
/* $Id$ */ /* * Copyright (c) 2014, 2015 Kristaps Dzonsons <kristaps@kcons.eu> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <assert.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #ifdef MAC_INTEGRATION #include <gtkosxapplication.h> #endif #include <gtk/gtk.h> #include <gdk/gdk.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_multifit.h> #include <gsl/gsl_histogram.h> #include <kplot.h> #include "extern.h" static void swin_init(struct swin *c, enum view view, GtkBuilder *b) { c->window = win_init_window(b, "window1"); c->menu = win_init_menubar(b, "menubar1"); c->draw = win_init_draw(b, "drawingarea1"); c->boxconfig = win_init_box(b, "box3"); c->menufile = win_init_menuitem(b, "menuitem1"); c->menuview = win_init_menuitem(b, "menuitem2"); c->menutools = win_init_menuitem(b, "menuitem3"); c->viewclone = win_init_menuitem(b, "menuitem15"); c->viewpause = win_init_menuitem(b, "menuitem20"); c->viewunpause = win_init_menuitem(b, "menuitem21"); c->views[VIEW_ISLANDMEAN] = win_init_menucheck(b, "menuitem45"); c->views[VIEW_ISLANDERMEAN] = win_init_menucheck(b, "menuitem46"); c->views[VIEW_MEAN] = win_init_menucheck(b, "menuitem8"); c->views[VIEW_SMEAN] = win_init_menucheck(b, "menuitem37"); c->views[VIEW_SEXTM] = win_init_menucheck(b, "menuitem43"); c->views[VIEW_SEXTI] = win_init_menucheck(b, "menuitem44"); c->views[VIEW_EXTM] = win_init_menucheck(b, "menuitem25"); c->views[VIEW_TIMESPDF] = win_init_menucheck(b, "menuitem38"); c->views[VIEW_TIMESCDF] = win_init_menucheck(b, "menuitem39"); c->views[VIEW_EXTMMAXPDF] = win_init_menucheck(b, "menuitem28"); c->views[VIEW_EXTMMAXCDF] = win_init_menucheck(b, "menuitem29"); c->views[VIEW_EXTI] = win_init_menucheck(b, "menuitem26"); c->views[VIEW_EXTIMINPDF] = win_init_menucheck(b, "menuitem27"); c->views[VIEW_EXTIMINCDF] = win_init_menucheck(b, "menuitem30"); c->views[VIEW_EXTIMINS] = win_init_menucheck(b, "menuitem35"); c->views[VIEW_DEV] = win_init_menucheck(b, "menuitem6"); c->views[VIEW_POLY] = win_init_menucheck(b, "menuitem7"); c->views[VIEW_POLYMINPDF] = win_init_menucheck(b, "menuitem9"); c->views[VIEW_POLYMINCDF] = win_init_menucheck(b, "menuitem11"); c->views[VIEW_MEANMINPDF] = win_init_menucheck(b, "menuitem10"); c->views[VIEW_MEANMINCDF] = win_init_menucheck(b, "menuitem12"); c->views[VIEW_MEANMINQ] = win_init_menucheck(b, "menuitem13"); c->views[VIEW_MEANMINS] = win_init_menucheck(b, "menuitem22"); c->views[VIEW_POLYMINS] = win_init_menucheck(b, "menuitem31"); c->views[VIEW_EXTMMAXS] = win_init_menucheck(b, "menuitem33"); c->views[VIEW_POLYMINQ] = win_init_menucheck(b, "menuitem14"); c->menuquit = win_init_menuitem(b, "menuitem5"); c->menuautoexport = win_init_menuitem(b, "menuitem49"); c->menuunautoexport = win_init_menuitem(b, "menuitem50"); c->menuclose = win_init_menuitem(b, "menuitem24"); c->menusave = win_init_menuitem(b, "menuitem34"); c->menusaveall = win_init_menuitem(b, "menuitem47"); gtk_widget_show_all(GTK_WIDGET(c->window)); gtk_window_set_title(GTK_WINDOW(c->window), gtk_menu_item_get_label (GTK_MENU_ITEM(c->views[view]))); gtk_widget_hide(GTK_WIDGET(c->menuunautoexport)); #ifdef MAC_INTEGRATION gtk_widget_hide(GTK_WIDGET(c->menu)); gtk_widget_hide(GTK_WIDGET(c->menuquit)); gtkosx_application_set_menu_bar (gtkosx_application_get(), GTK_MENU_SHELL(c->menu)); gtkosx_application_sync_menubar (gtkosx_application_get()); #endif } /* * Dereference a simulation. * This means that we've closed an output window that's looking at a * particular simulation. * When the simulation has no more references (i.e., no more windows are * painting that simulation), then the simulation destroys itself. */ static void on_sim_deref(gpointer dat) { struct sim *sim = dat; g_debug("%p: Simulation deref (now %zu)", sim, sim->refs - 1); if (0 != --sim->refs) return; g_debug("%p: Simulation terminating", sim); sim_stop(sim, NULL); } /* * Dereference all simulations owned by a given window. * This happens when a window is closing. */ static void on_sims_deref(gpointer dat) { g_list_free_full(dat, on_sim_deref); } static void curwin_free(gpointer dat) { struct curwin *cur = dat; size_t i; g_debug("%p: Simwin freeing", cur); kdata_destroy(cur->winmean); kdata_destroy(cur->winstddev); kdata_destroy(cur->winfitmean); kdata_destroy(cur->winfitstddev); kdata_destroy(cur->winmextinctmean); kdata_destroy(cur->winmextinctstddev); kdata_destroy(cur->winiextinctmean); kdata_destroy(cur->winiextinctstddev); for (i = 0; i < VIEW__MAX; i++) kplot_free(cur->views[i]); cur->b->windows = g_list_remove(cur->b->windows, cur); on_sims_deref(cur->sims); g_free(cur->autosave); g_free(cur); } static void window_add_configmarkup(GtkWidget *box, const gchar *fmt, ...) { gchar buf[1024]; GtkWidget *w; va_list ap; va_start(ap, fmt); g_vsnprintf(buf, sizeof(buf), fmt, ap); va_end(ap); w = gtk_label_new(NULL); gtk_label_set_markup(GTK_LABEL(w), buf); gtk_misc_set_alignment(GTK_MISC(w), 0.0, 0.5); gtk_container_add(GTK_CONTAINER(box), w); } static void window_add_config(GtkWidget *box, const gchar *fmt, ...) { gchar buf[1024]; GtkWidget *w; va_list ap; va_start(ap, fmt); g_vsnprintf(buf, sizeof(buf), fmt, ap); va_end(ap); w = gtk_label_new(buf); gtk_misc_set_alignment(GTK_MISC(w), 0.0, 0.5); gtk_container_add(GTK_CONTAINER(box), w); } static void window_add_sim(struct curwin *cur, struct sim *sim) { GtkWidget *box, *outbox, *leftbox; struct kdata *stats[2]; enum kplottype ts[2]; struct kdatacfg solidcfg, transcfg; struct kdatacfg *cfgs[2]; double solid[4], trans[4]; gchar label[64]; struct ksmthcfg smth; /* Get our colours. */ memcpy(solid, cur->b->clrs[sim->colour % cur->b->clrsz].rgba, sizeof(solid)); memcpy(trans, solid, sizeof(trans)); trans[3] = 0.4; /* Append to the per-window simulation views. */ kdata_vector_append(cur->winmean, g_list_length(cur->sims), 0.0); kdata_vector_append(cur->winstddev, g_list_length(cur->sims), 0.0); kdata_vector_append(cur->winfitmean, g_list_length(cur->sims), 0.0); kdata_vector_append(cur->winfitstddev, g_list_length(cur->sims), 0.0); kdata_vector_append(cur->winmextinctmean, g_list_length(cur->sims), 0.0); kdata_vector_append(cur->winmextinctstddev, g_list_length(cur->sims), 0.0); kdata_vector_append(cur->winiextinctmean, g_list_length(cur->sims), 0.0); kdata_vector_append(cur->winiextinctstddev, g_list_length(cur->sims), 0.0); /* Append our configuration. */ outbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 2); g_snprintf(label, sizeof(label), "<span bgcolor=\"#%.2x%.2x%.2x\">" "&#x00a0;&#x00a0;&#x00a0;&#x00a0;" "</span>", (unsigned int)(solid[0] * 255), (unsigned int)(solid[1] * 255), (unsigned int)(solid[2] * 255)); leftbox = gtk_label_new(NULL); gtk_misc_set_alignment(GTK_MISC(leftbox), 0.0, 0.0); gtk_label_set_markup(GTK_LABEL(leftbox), label); gtk_container_add(GTK_CONTAINER(outbox), leftbox); box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 2); gtk_container_add(GTK_CONTAINER(outbox), box); window_add_config(box, "Name: %s", sim->name); window_add_configmarkup(box, "Payoffs: &#x03c0; = %s; " "T = %zu", sim->func, sim->stop); window_add_configmarkup(box, "Poisson offspring: " "&#x03bb; = %g(1 + %g * &#x03c0;)", sim->alpha, sim->delta); window_add_config(box, "Incumbents: " "x = [%g, %g), %zu slices", sim->xmin, sim->xmax, sim->dims); if (MUTANTS_DISCRETE == sim->mutants) window_add_config(box, "Mutants: y = [%g, %g), " "%zu slices", sim->ymin, sim->ymax, sim->dims); else window_add_configmarkup(box, "Mutants: " "Gaussian &#x03c3; = %g, Y = [%g, %g)", sim->mutantsigma, sim->ymin, sim->ymax); switch (sim->input) { case (INPUT_UNIFORM): window_add_config(box, "Population: uniform %zu " "islands, %zu islanders (%zu total), m = %g", sim->pop, sim->islands, sim->totalpop, sim->m); break; case (INPUT_VARIABLE): window_add_config(box, "Population: variable %zu " "islands (%zu total, %suniform), m = %g", sim->islands, sim->totalpop, NULL != sim->ms ? "non-" : "", sim->m); if (sim->ideathmean) window_add_config(box, "Island death Poisson mean: %zu, " "coefficient %g", sim->ideathmean, sim->ideathcoef); break; case (INPUT_MAPPED): window_add_config(box, "Population: mapped %zu " "islands (%zu total, %suniform), m = %g", sim->islands, sim->totalpop, NULL != sim->ms ? "non-" : "", sim->m); switch (sim->maptop) { case (MAPTOP_RECORD): window_add_config(box, "Map topology: " "KML records"); break; case (MAPTOP_RAND): window_add_config(box, "Map topology: " "random records"); break; case (MAPTOP_TORUS): window_add_config(box, "Map topology: " "toroidal records"); break; default: abort(); } switch (sim->migrant) { case (MAPMIGRANT_UNIFORM): window_add_config(box, "Map migration: " "uniform random"); break; case (MAPMIGRANT_DISTANCE): window_add_config(box, "Map migration: " "inverse square distance"); break; case (MAPMIGRANT_NEAREST): window_add_config(box, "Map migration: " "first nearest neighbour"); break; case (MAPMIGRANT_TWONEAREST): window_add_config(box, "Map migration: " "two-nearest neighbours"); break; default: abort(); } break; default: abort(); } if (0 == sim->fitpoly) window_add_config(box, "Polynomial fitting: disabled"); else window_add_config(box, "Polynomial fitting: order " "%zu (%sweighted)", sim->fitpoly, sim->weighted ? "" : "un"); gtk_container_add(GTK_CONTAINER(cur->wins.boxconfig), outbox); gtk_widget_show_all(GTK_WIDGET(cur->wins.boxconfig)); /* Configure our line and point style. */ ksmthcfg_defaults(&smth); smth.movsamples = sim->smoothing; kdatacfg_defaults(&solidcfg); solidcfg.point.clr.type = KPLOTCTYPE_RGBA; memcpy(solidcfg.point.clr.rgba, solid, sizeof(solid)); solidcfg.line.clr.type = KPLOTCTYPE_RGBA; memcpy(solidcfg.line.clr.rgba, solid, sizeof(solid)); kdatacfg_defaults(&transcfg); transcfg.point.clr.type = KPLOTCTYPE_RGBA; memcpy(transcfg.point.clr.rgba, trans, sizeof(trans)); transcfg.line.clr.type = KPLOTCTYPE_RGBA; memcpy(transcfg.line.clr.rgba, trans, sizeof(trans)); /* Mean view. */ kplot_attach_data(cur->views[VIEW_MEAN], sim->bufs.means->cold, KPLOT_LINES, &solidcfg); /* Mutant mean view. */ kplot_attach_data(cur->views[VIEW_EXTM], sim->bufs.mextinct->cold, KPLOT_LINES, &solidcfg); /* Incumbent mean view. */ kplot_attach_data(cur->views[VIEW_EXTI], sim->bufs.iextinct->cold, KPLOT_LINES, &solidcfg); /* Mean and poly-fitted line. */ kplot_attach_data(cur->views[VIEW_POLY], sim->bufs.fitpolybuf, KPLOT_LINES, &solidcfg); kplot_attach_data(cur->views[VIEW_POLY], sim->bufs.means->cold, KPLOT_LINES, &transcfg); /* Mutant mean and smoothed line. */ kplot_attach_smooth(cur->views[VIEW_SEXTM], sim->bufs.mextinct->cold, KPLOT_LINES, &solidcfg, KSMOOTH_MOVAVG, &smth); kplot_attach_data(cur->views[VIEW_SEXTM], sim->bufs.mextinct->cold, KPLOT_LINES, &transcfg); /* Mutant mean and smoothed line. */ kplot_attach_smooth(cur->views[VIEW_SEXTI], sim->bufs.iextinct->cold, KPLOT_LINES, &solidcfg, KSMOOTH_MOVAVG, &smth); kplot_attach_data(cur->views[VIEW_SEXTI], sim->bufs.iextinct->cold, KPLOT_LINES, &transcfg); /* Mean and smoothed lines. */ kplot_attach_smooth(cur->views[VIEW_SMEAN], sim->bufs.means->cold, KPLOT_LINES, &solidcfg, KSMOOTH_MOVAVG, &smth); kplot_attach_data(cur->views[VIEW_SMEAN], sim->bufs.means->cold, KPLOT_LINES, &transcfg); /* Mean and stddev. */ ts[0] = ts[1] = KPLOT_LINES; stats[0] = sim->bufs.means->cold; stats[1] = sim->bufs.stddevs->cold; cfgs[0] = &solidcfg; cfgs[1] = &transcfg; kplot_attach_datas(cur->views[VIEW_DEV], 2, stats, ts, (const struct kdatacfg *const *)cfgs, KPLOTS_YERRORLINE); /* Island mean and stddev. */ ts[0] = ts[1] = KPLOT_POINTS; stats[0] = sim->bufs.islandmeans->cold; stats[1] = sim->bufs.islandstddevs->cold; cfgs[0] = &solidcfg; cfgs[1] = &transcfg; kplot_attach_datas(cur->views[VIEW_ISLANDERMEAN], 2, stats, ts, (const struct kdatacfg *const *)cfgs, KPLOTS_YERRORBAR); /* Island mean and stddev. */ ts[0] = ts[1] = KPLOT_POINTS; stats[0] = sim->bufs.imeans->cold; stats[1] = sim->bufs.istddevs->cold; cfgs[0] = &solidcfg; cfgs[1] = &transcfg; kplot_attach_datas(cur->views[VIEW_ISLANDMEAN], 2, stats, ts, (const struct kdatacfg *const *)cfgs, KPLOTS_YERRORBAR); /* Time PMF views. */ kplot_attach_smooth(cur->views[VIEW_TIMESPDF], sim->bufs.times->cold, KPLOT_LINES, &solidcfg, KSMOOTH_PMF, NULL); kplot_attach_smooth(cur->views[VIEW_TIMESCDF], sim->bufs.times->cold, KPLOT_LINES, &solidcfg, KSMOOTH_CDF, NULL); /* Mean PMF views. */ kplot_attach_smooth(cur->views[VIEW_MEANMINPDF], sim->bufs.meanmins, KPLOT_LINES, &solidcfg, KSMOOTH_PMF, NULL); kplot_attach_smooth(cur->views[VIEW_MEANMINCDF], sim->bufs.meanmins, KPLOT_LINES, &solidcfg, KSMOOTH_CDF, NULL); /* Mutant PMF views. */ kplot_attach_smooth(cur->views[VIEW_EXTMMAXPDF], sim->bufs.mextinctmaxs, KPLOT_LINES, &solidcfg, KSMOOTH_PMF, NULL); kplot_attach_smooth(cur->views[VIEW_EXTMMAXCDF], sim->bufs.mextinctmaxs, KPLOT_LINES, &solidcfg, KSMOOTH_CDF, NULL); /* Incumbent PMF views. */ kplot_attach_smooth(cur->views[VIEW_EXTIMINPDF], sim->bufs.iextinctmins, KPLOT_LINES, &solidcfg, KSMOOTH_PMF, NULL); kplot_attach_smooth(cur->views[VIEW_EXTIMINCDF], sim->bufs.iextinctmins, KPLOT_LINES, &solidcfg, KSMOOTH_CDF, NULL); /* Fit poly PMF views. */ kplot_attach_smooth(cur->views[VIEW_POLYMINPDF], sim->bufs.fitpolymins, KPLOT_LINES, &solidcfg, KSMOOTH_PMF, NULL); kplot_attach_smooth(cur->views[VIEW_POLYMINCDF], sim->bufs.fitpolymins, KPLOT_LINES, &solidcfg, KSMOOTH_CDF, NULL); kplot_attach_data(cur->views[VIEW_MEANMINQ], sim->bufs.meanminqbuf, KPLOT_LINES, &solidcfg); kplot_attach_data(cur->views[VIEW_POLYMINQ], sim->bufs.fitminqbuf, KPLOT_LINES, &solidcfg); } /* * Indicate that a given simulation is now being referenced by a new * window. */ static void sim_ref(gpointer dat, gpointer unused) { struct sim *sim = dat; ++sim->refs; g_debug("%p: Simulation ref (now %zu)", sim, sim->refs); } /* * Transfer the other widget's data into our own. */ void on_drag_recv(GtkWidget *widget, GdkDragContext *ctx, gint x, gint y, GtkSelectionData *sel, guint target, guint time, gpointer dat) { GObject *srcptr, *dstptr; struct curwin *cur; GList *srcsims, *l, *ll; /* Get pointers to our and the other's window. */ assert(NULL != sel); dstptr = G_OBJECT(gtk_widget_get_toplevel(widget)); srcptr = G_OBJECT(*(void **) gtk_selection_data_get_data(sel)); assert(NULL != srcptr); gtk_drag_finish(ctx, TRUE, FALSE, time); /* Don't copy into ourselves. */ if (dstptr == srcptr) return; /* Get the simulation lists. */ cur = g_object_get_data(srcptr, "cfg"); srcsims = cur->sims; assert(NULL != srcsims); cur = g_object_get_data(dstptr, "cfg"); /* Concatenate the simulation lists. */ /* XXX: use g_list_concat? */ for (l = srcsims; NULL != l; l = l->next) { g_debug("%p: Copying simulation", l->data); for (ll = cur->sims; NULL != ll; ll = ll->next) if (ll->data == l->data) break; if (NULL != ll) { g_debug("Simulation %p duplicate", l->data); continue; } sim_ref(l->data, NULL); cur->sims = g_list_append(cur->sims, l->data); window_add_sim(cur, l->data); } } /* * Signifity sight-unseen that we can transfer data. * We're only using DnD for one particular thing, so there's no need for * elaborate security measures. */ gboolean on_drag_drop(GtkWidget *widget, GdkDragContext *ctx, gint x, gint y, guint time, gpointer dat) { gtk_drag_get_data(widget, ctx, 0, time); return(TRUE); } /* * Send our identifier to the destination of the DnD. * They'll query our data separately. */ void on_drag_get(GtkWidget *widget, GdkDragContext *ctx, GtkSelectionData *sel, guint targ, guint time, gpointer dat) { void *ptr; ptr = gtk_widget_get_toplevel(widget); gtk_selection_data_set(sel, gtk_selection_data_get_target(sel), sizeof(intptr_t) * 8, (const guchar *)&ptr, sizeof(intptr_t)); } /* * Initialise a simulation (or simulations) window. * This is either called when we've just made a new simulation */ static void window_init(struct bmigrate *b, struct curwin *cur, GList *sims) { GtkBuilder *builder; GtkTargetEntry target; GList *l; struct kdata *stats[2]; enum kplottype ts[2]; size_t i; struct kplotcfg cfg; builder = builder_get("simwin.glade"); g_assert(NULL != builder); swin_init(&cur->wins, cur->view, builder); gtk_builder_connect_signals(builder, cur); g_object_unref(G_OBJECT(builder)); cur->winmean = kdata_vector_alloc(1); cur->winstddev = kdata_vector_alloc(1); cur->winfitmean = kdata_vector_alloc(1); cur->winfitstddev = kdata_vector_alloc(1); cur->winmextinctmean = kdata_vector_alloc(1); cur->winmextinctstddev = kdata_vector_alloc(1); cur->winiextinctmean = kdata_vector_alloc(1); cur->winiextinctstddev = kdata_vector_alloc(1); for (i = 0; i < VIEW__MAX; i++) { kplotcfg_defaults(&cfg); switch (i) { case (VIEW_DEV): case (VIEW_POLY): case (VIEW_EXTIMINS): case (VIEW_EXTMMAXS): case (VIEW_MEANMINS): case (VIEW_POLYMINS): case (VIEW_ISLANDMEAN): case (VIEW_ISLANDERMEAN): cfg.extrema_ymin = 0.0; cfg.extrema = EXTREMA_YMIN; break; default: break; } switch (i) { case (VIEW_DEV): case (VIEW_EXTI): case (VIEW_EXTIMINCDF): case (VIEW_EXTIMINPDF): case (VIEW_EXTM): case (VIEW_EXTMMAXCDF): case (VIEW_EXTMMAXPDF): case (VIEW_MEAN): case (VIEW_MEANMINCDF): case (VIEW_MEANMINPDF): case (VIEW_POLY): case (VIEW_POLYMINCDF): case (VIEW_POLYMINPDF): case (VIEW_SEXTM): case (VIEW_SEXTI): case (VIEW_SMEAN): cfg.xaxislabel = "incumbent"; break; case (VIEW_ISLANDMEAN): case (VIEW_ISLANDERMEAN): cfg.xaxislabel = "island"; break; case (VIEW_TIMESCDF): case (VIEW_TIMESPDF): cfg.xaxislabel = "exit time"; break; case (VIEW_EXTIMINS): case (VIEW_EXTMMAXS): case (VIEW_MEANMINS): case (VIEW_POLYMINS): cfg.xaxislabel = "simulation"; break; case (VIEW_MEANMINQ): case (VIEW_POLYMINQ): cfg.xaxislabel = "relative time"; break; default: abort(); } cfg.yaxislabelrot = M_PI / 2; switch (i) { case (VIEW_POLY): case (VIEW_DEV): case (VIEW_MEAN): case (VIEW_SMEAN): cfg.y2axislabel = "mutant fraction"; break; case (VIEW_SEXTI): case (VIEW_EXTI): cfg.y2axislabel = "incumbent extinction"; break; case (VIEW_SEXTM): case (VIEW_EXTM): cfg.y2axislabel = "mutant extinction"; break; case (VIEW_EXTIMINCDF): case (VIEW_EXTIMINPDF): case (VIEW_EXTMMAXCDF): case (VIEW_EXTMMAXPDF): case (VIEW_MEANMINCDF): case (VIEW_MEANMINPDF): case (VIEW_POLYMINCDF): case (VIEW_POLYMINPDF): case (VIEW_TIMESCDF): case (VIEW_TIMESPDF): break; case (VIEW_ISLANDMEAN): case (VIEW_ISLANDERMEAN): cfg.y2axislabel = "mutant fraction mean"; break; case (VIEW_EXTMMAXS): case (VIEW_EXTIMINS): case (VIEW_MEANMINS): case (VIEW_POLYMINS): case (VIEW_MEANMINQ): case (VIEW_POLYMINQ): cfg.y2axislabel = "incumbent"; break; default: abort(); } cur->views[i] = kplot_alloc(&cfg); g_assert(NULL != cur->views[i]); } ts[0] = ts[1] = KPLOT_POINTS; stats[0] = cur->winmean; stats[1] = cur->winstddev; kplot_attach_datas(cur->views[VIEW_MEANMINS], 2, stats, ts, NULL, KPLOTS_YERRORBAR); ts[0] = ts[1] = KPLOT_POINTS; stats[0] = cur->winfitmean; stats[1] = cur->winfitstddev; kplot_attach_datas(cur->views[VIEW_POLYMINS], 2, stats, ts, NULL, KPLOTS_YERRORBAR); ts[0] = ts[1] = KPLOT_POINTS; stats[0] = cur->winmextinctmean; stats[1] = cur->winmextinctstddev; kplot_attach_datas(cur->views[VIEW_EXTMMAXS], 2, stats, ts, NULL, KPLOTS_YERRORBAR); ts[0] = ts[1] = KPLOT_POINTS; stats[0] = cur->winiextinctmean; stats[1] = cur->winiextinctstddev; kplot_attach_datas(cur->views[VIEW_EXTIMINS], 2, stats, ts, NULL, KPLOTS_YERRORBAR); cur->redraw = 1; cur->sims = sims; cur->b = b; g_object_set_data_full(G_OBJECT (cur->wins.window), "cfg", cur, curwin_free); b->windows = g_list_append(b->windows, cur); /* * Coordinate drag-and-drop. * We only allow drag-and-drop between us and other windows of * this same simulation. */ target.target = g_strdup("integer"); target.flags = GTK_TARGET_SAME_APP|GTK_TARGET_OTHER_WIDGET; target.info = 0; gtk_drag_dest_set(GTK_WIDGET(cur->wins.draw), GTK_DEST_DEFAULT_ALL, &target, 1, GDK_ACTION_COPY); gtk_drag_source_set(GTK_WIDGET(cur->wins.draw), GDK_BUTTON1_MASK, &target, 1, GDK_ACTION_COPY); g_free(target.target); for (l = cur->sims; NULL != l; l = g_list_next(l)) window_add_sim(cur, l->data); } /* * Clone the current window. * We create a new window, intialised in the same way as for a new * single simulation, but give it an existing list of simulations. */ void onclone(GtkMenuItem *menuitem, gpointer dat) { struct curwin *oldcur = dat, *newcur; GList *oldsims, *newsims; oldsims = oldcur->sims; g_list_foreach(oldsims, sim_ref, NULL); newsims = g_list_copy(oldsims); newcur = g_malloc0(sizeof(struct curwin)); newcur->view = oldcur->view; window_init(oldcur->b, newcur, newsims); } /* * Brute-force scan all possible pi values (and Poisson means) by * scanning through the strategy space. */ static gboolean on_rangefind_idle(gpointer dat) { return(rangefind(dat)); } static int entry2func(GtkEntry *entry, struct hnode ***exp, GtkLabel *error) { const gchar *txt; GdkRGBA bad = { 1.0, 0.0, 0.0, 0.5 }; txt = gtk_entry_get_text(entry); *exp = hnode_parse((const gchar **)&txt); if (NULL != *exp) { gtk_widget_override_background_color (GTK_WIDGET(entry), GTK_STATE_FLAG_NORMAL, NULL); return(1); } gtk_label_set_text(error, "Error: not a function."); gtk_widget_show_all(GTK_WIDGET(error)); gtk_widget_override_background_color (GTK_WIDGET(entry), GTK_STATE_FLAG_NORMAL, &bad); return(0); } static int entryworder(GtkEntry *mine, GtkEntry *maxe, double min, double max, GtkLabel *error) { GdkRGBA bad = { 1.0, 0.0, 0.0, 0.5 }; if (min < max) { gtk_widget_override_background_color (GTK_WIDGET(mine), GTK_STATE_FLAG_NORMAL, NULL); gtk_widget_override_background_color (GTK_WIDGET(maxe), GTK_STATE_FLAG_NORMAL, NULL); return(1); } gtk_label_set_text(error, "Error: bad weak ordering."); gtk_widget_show_all(GTK_WIDGET(error)); gtk_widget_override_background_color (GTK_WIDGET(mine), GTK_STATE_FLAG_NORMAL, &bad); gtk_widget_override_background_color (GTK_WIDGET(maxe), GTK_STATE_FLAG_NORMAL, &bad); return(0); } static int entryorder(GtkEntry *mine, GtkEntry *maxe, double min, double max, GtkLabel *error) { GdkRGBA bad = { 1.0, 0.0, 0.0, 0.5 }; if (min <= max) { gtk_widget_override_background_color (GTK_WIDGET(mine), GTK_STATE_FLAG_NORMAL, NULL); gtk_widget_override_background_color (GTK_WIDGET(maxe), GTK_STATE_FLAG_NORMAL, NULL); return(1); } gtk_label_set_text(error, "Error: bad ordering."); gtk_widget_show_all(GTK_WIDGET(error)); gtk_widget_override_background_color (GTK_WIDGET(mine), GTK_STATE_FLAG_NORMAL, &bad); gtk_widget_override_background_color (GTK_WIDGET(maxe), GTK_STATE_FLAG_NORMAL, &bad); return(0); } static int entry2double(GtkEntry *entry, gdouble *sz, GtkLabel *error) { gchar *ep; GdkRGBA bad = { 1.0, 0.0, 0.0, 0.5 }; *sz = g_ascii_strtod(gtk_entry_get_text(entry), &ep); if (ERANGE != errno && '\0' == *ep) { gtk_widget_override_background_color (GTK_WIDGET(entry), GTK_STATE_FLAG_NORMAL, NULL); return(1); } gtk_label_set_text(error, "Error: not a decimal number."); gtk_widget_show_all(GTK_WIDGET(error)); gtk_widget_override_background_color (GTK_WIDGET(entry), GTK_STATE_FLAG_NORMAL, &bad); return(0); } static int entry2size(GtkEntry *entry, size_t *sz, GtkLabel *error, size_t min) { guint64 v; gchar *ep; GdkRGBA bad = { 1.0, 0.0, 0.0, 0.5 }; v = g_ascii_strtoull(gtk_entry_get_text(entry), &ep, 10); if (ERANGE == errno || '\0' != *ep || v >= SIZE_MAX) { gtk_label_set_text (error, "Error: not a natural number."); gtk_widget_show_all(GTK_WIDGET(error)); gtk_widget_override_background_color (GTK_WIDGET(entry), GTK_STATE_FLAG_NORMAL, &bad); return(0); } else if (v < min) { gtk_label_set_text (error, "Error: number too small."); gtk_widget_show_all(GTK_WIDGET(error)); gtk_widget_override_background_color (GTK_WIDGET(entry), GTK_STATE_FLAG_NORMAL, &bad); return(0); } *sz = (size_t)v; gtk_widget_override_background_color (GTK_WIDGET(entry), GTK_STATE_FLAG_NORMAL, NULL); return(1); } /* * We have various ways of auto-setting the name of the simulation. * By default, it's set to the current date-time. */ static void donamefill(struct hwin *c) { enum namefill v; GTimeVal gt; enum input input; gchar buf[1024]; gchar *bufp; enum mutants mutants; input = gtk_notebook_get_current_page(c->inputs); g_assert(input < INPUT__MAX); for (mutants = 0; mutants < MUTANTS__MAX; mutants++) if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON(c->mutants[mutants]))) break; for (v = 0; v < NAMEFILL__MAX; v++) if (gtk_toggle_button_get_active(c->namefill[v])) break; bufp = buf; switch (v) { case (NAMEFILL_M): g_snprintf(buf, sizeof(buf), "m=%s", gtk_entry_get_text(c->migrate[input])); break; case (NAMEFILL_T): g_snprintf(buf, sizeof(buf), "T=%s", gtk_entry_get_text(c->stop)); break; case (NAMEFILL_MUTANTS): if (MUTANTS_DISCRETE == mutants) { g_snprintf(buf, sizeof(buf), "discrete [%s,%s)", gtk_entry_get_text(c->xmin), gtk_entry_get_text(c->xmax)); break; } g_snprintf(buf, sizeof(buf), "Gaussian s=%s, [%s,%s)", gtk_entry_get_text(c->mutantsigma), gtk_entry_get_text(c->ymin), gtk_entry_get_text(c->ymax)); break; case (NAMEFILL_DATE): g_get_current_time(&gt); bufp = g_time_val_to_iso8601(&gt); break; case (NAMEFILL_NONE): return; default: abort(); } gtk_entry_set_text(c->name, bufp); if (bufp != buf) g_free(bufp); } void onnametoggle(GtkToggleButton *editable, gpointer dat) { struct bmigrate *b = dat; donamefill(&b->wins); } void onnameupdate(GtkEditable *editable, gpointer dat) { struct bmigrate *b = dat; donamefill(&b->wins); } /* * We want to run the given simulation. * First, verify all data; then, start the simulation; lastly, open a * window assigned specifically to that simulation. */ void onactivate(GtkButton *button, gpointer dat) { gint input; struct bmigrate *b = dat; struct hnode **exp; enum mapmigrant migrants; GtkWidget *w; struct kml *kml; GList *l, *cl; GtkLabel *err = b->wins.error; const gchar *name, *func; gchar *file; gdouble **ms; gdouble xmin, xmax, delta, alpha, m, sigma, ymin, ymax, idcoef, strat; enum mutants mutants; size_t i, totalpop, islands, stop, ideathmean, slices, islandpop, mapindexfix; size_t *islandpops; struct sim *sim; struct curwin *cur; struct kmlplace *kmlp; GError *er; enum maptop maptop; enum mapindex mapindex; sigma = idcoef = 0.0; islandpops = NULL; islandpop = 0; ms = NULL; kml = NULL; exp = NULL; if ( ! entry2size(b->wins.stop, &stop, err, 1)) goto cleanup; for (migrants = 0; migrants < MAPMIGRANT__MAX; migrants++) if (gtk_toggle_button_get_active (b->wins.mapmigrants[migrants])) break; g_assert(migrants < MAPMIGRANT__MAX); for (mapindex = 0; mapindex < MAPINDEX__MAX; mapindex++) if (gtk_toggle_button_get_active (b->wins.mapindices[mapindex])) break; g_assert(mapindex < MAPINDEX__MAX); mapindexfix = MAPINDEX_FIXED != mapindex ? 0 : gtk_adjustment_get_value(b->wins.mapindexfix); for (maptop = 0; maptop < MAPTOP__MAX; maptop++) if (gtk_toggle_button_get_active (b->wins.maptop[maptop])) break; g_assert(maptop < MAPTOP__MAX); input = gtk_notebook_get_current_page(b->wins.inputs); switch (input) { case (INPUT_UNIFORM): /* * In the simplest possible case, we use uniform values * for both migration (no inter-island migration) and * populations. */ islands = gtk_adjustment_get_value(b->wins.islands); islandpop = gtk_adjustment_get_value(b->wins.pop); break; case (INPUT_VARIABLE): /* * Variable number of islands. * We also add a check to see if we're really running * with different island sizes or not. */ if ( ! entry2double(b->wins.ideathcoef, &idcoef, err)) goto cleanup; if (idcoef < 0.0 || idcoef > 1.0) { gtk_label_set_text(err, "Death coefficient " "must be in the unit interval."); gtk_widget_show_all(GTK_WIDGET(err)); goto cleanup; } l = gtk_container_get_children (GTK_CONTAINER(b->wins.mapbox)); islands = g_list_length(l); islandpops = g_malloc0_n(islands, sizeof(size_t)); for (i = 0; i < islands; i++) { w = GTK_WIDGET(g_list_nth_data(l, i)); cl = gtk_container_get_children(GTK_CONTAINER(w)); islandpops[i] = gtk_spin_button_get_value_as_int (GTK_SPIN_BUTTON(g_list_next(cl)->data)); g_list_free(cl); } g_list_free(l); break; case (INPUT_MAPPED): /* * Possibly variable island sizes, possibly variable * inter-island migration. */ switch (maptop) { case (MAPTOP_RECORD): /* Try to read KML from file. */ file = gtk_file_chooser_get_filename (b->wins.mapfile); if (NULL == file) { gtk_label_set_text(err, "Error: " "map file not specified."); gtk_widget_show_all(GTK_WIDGET(err)); goto cleanup; } er = NULL; kml = kml_parse(file, &er); g_free(file); if (NULL == kml) { file = g_strdup_printf("Error: " "bad map file: %s", NULL != er ? er->message : "cannot load file"); gtk_label_set_text(err, file); gtk_widget_show_all(GTK_WIDGET(err)); g_free(file); if (NULL != er) g_error_free(er); goto cleanup; } break; case (MAPTOP_RAND): islands = gtk_adjustment_get_value (b->wins.maprandislands); islandpop = gtk_adjustment_get_value (b->wins.maprandislanders); kml = kml_rand(islands, islandpop); islandpop = islands = 0; break; case (MAPTOP_TORUS): islands = gtk_adjustment_get_value (b->wins.maptorusislands); islandpop = gtk_adjustment_get_value (b->wins.maptorusislanders); kml = kml_torus(islands, islandpop); islandpop = islands = 0; break; default: abort(); } /* * Grok our island populations from the input file. * This will have a reasonable default, but make sure * anyway with some assertions. */ islands = (size_t)g_list_length(kml->kmls); islandpops = g_malloc0_n(islands, sizeof(size_t)); for (i = 0; i < islands; i++) { kmlp = g_list_nth_data(kml->kmls, i); islandpops[i] = kmlp->pop; } /* * If we're uniformly migrating, then stop processing * right now. * If we're distance-migrating, then have the kml file * set the inter-island migration probabilities. */ switch (migrants) { case (MAPMIGRANT_UNIFORM): ms = kml_migration_distance(kml->kmls, maptop); break; case (MAPMIGRANT_NEAREST): ms = kml_migration_nearest(kml->kmls, maptop); break; case (MAPMIGRANT_TWONEAREST): ms = kml_migration_twonearest(kml->kmls, maptop); break; default: break; } break; default: abort(); } /* * Base check: we need at least two islands. */ if (islands < 2) { gtk_label_set_text(err, "Error: need at least two islands."); gtk_widget_show_all(GTK_WIDGET(err)); goto cleanup; } ideathmean = gtk_adjustment_get_value(b->wins.ideathmean); /* * If we have an array of island populations, make sure that * each has more than two islanders. * While here, revert to a single island population size if our * sizes are, in fact, uniform. * Calculate our total population size as well. */ if (NULL != islandpops) { g_assert(0 == islandpop); for (i = 0; i < islands; i++) { if (islandpops[i] > 1) continue; gtk_label_set_text(err, "Error: need at " "least two islanders per island."); gtk_widget_show_all(GTK_WIDGET(err)); goto cleanup; } for (totalpop = i = 0; i < islands; i++) totalpop += islandpops[i]; /* Check for uniformity. */ for (i = 1; i < islands; i++) if (islandpops[i] != islandpops[0]) break; if (i == islands && 0 == ideathmean) { g_debug("Reverting to uniform island " "populations: all islands have " "the same (with no death process): " "%zu", islandpops[0]); islandpop = islandpops[0]; g_free(islandpops); islandpops = NULL; } } /* * Handle uniform island sizes. * (This isn't part of the conditional above because we might * set ourselves to be uniform whilst processing.) */ if (NULL == islandpops && islandpop < 2) { gtk_label_set_text(err, "Error: need at " "least two islanders per island."); gtk_widget_show_all(GTK_WIDGET(err)); goto cleanup; } else if (NULL == islandpops) totalpop = islands * islandpop; for (mutants = 0; mutants < MUTANTS__MAX; mutants++) if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON(b->wins.mutants[mutants]))) break; if ( ! entry2double(b->wins.xmin, &xmin, err)) goto cleanup; if ( ! entry2double(b->wins.xmax, &xmax, err)) goto cleanup; if ( ! entryworder(b->wins.xmin, b->wins.xmax, xmin, xmax, err)) goto cleanup; ymin = xmin; ymax = xmax; if (MUTANTS_GAUSSIAN == mutants) { if ( ! entry2double(b->wins.ymin, &ymin, err)) goto cleanup; if ( ! entry2double(b->wins.ymax, &ymax, err)) goto cleanup; if ( ! entryorder(b->wins.ymin, b->wins.xmin, ymin, xmin, err)) goto cleanup; if ( ! entryorder(b->wins.xmax, b->wins.ymax, xmax, ymax, err)) goto cleanup; if ( ! entryworder(b->wins.ymin, b->wins.ymax, ymin, ymax, err)) goto cleanup; if ( ! entry2double(b->wins.mutantsigma, &sigma, err)) goto cleanup; } if ( ! entry2double(b->wins.alpha, &alpha, err)) goto cleanup; if ( ! entry2double(b->wins.delta, &delta, err)) goto cleanup; if ( ! entry2double(b->wins.migrate[input], &m, err)) goto cleanup; if ( ! entry2size(b->wins.incumbents, &slices, err, 1)) goto cleanup; if ( ! entry2func(b->wins.func, &exp, err)) goto cleanup; func = gtk_entry_get_text(b->wins.func); name = gtk_entry_get_text(b->wins.name); if ('\0' == *name) name = "unnamed"; gtk_widget_hide(GTK_WIDGET(err)); /* * All parameters check out! * Allocate the simulation now. */ if (button == b->wins.buttonrange) { if (0 == b->rangeid) { g_debug("Starting rangefinder"); b->rangeid = g_idle_add ((GSourceFunc)on_rangefind_idle, b); } else g_debug("Re-using rangefinder"); hnode_free(b->range.exp); if (NULL != islandpops) { b->range.n = 0; for (i = 0; i < islands; i++) b->range.n = islandpops[i] > b->range.n ? islandpops[i] : b->range.n; } else b->range.n = islandpop; b->range.exp = exp; b->range.alpha = alpha; b->range.delta = delta; b->range.slices = slices; b->range.slicex = b->range.slicey = 0; b->range.piaggr = 0.0; b->range.picount = 0; b->range.pimin = DBL_MAX; b->range.pimax = -DBL_MAX; b->range.xmin = b->range.ymin = xmin; b->range.xmax = b->range.ymax = xmax; if (MUTANTS_GAUSSIAN == mutants) { b->range.ymin = ymin; b->range.ymax = ymax; } exp = NULL; file = g_strdup_printf ("%s, X=[%g, %g), Y=[%g, %g), n=%zu", func, b->range.xmin, b->range.xmax, b->range.ymin, b->range.ymax, b->range.n); gtk_label_set_text(b->wins.rangefunc, file); g_free(file); file = g_strdup_printf ("%g(1 + %g&#x03c0;)", b->range.alpha, b->range.delta); gtk_label_set_markup(b->wins.rangeparms, file); g_free(file); gtk_widget_hide(GTK_WIDGET(b->wins.rangeerrorbox)); gtk_widget_set_visible (GTK_WIDGET(b->wins.rangefind), TRUE); goto cleanup; } sim = g_malloc0(sizeof(struct sim)); sim->dims = slices; sim->islands = islands; sim->mutants = mutants; sim->mutantsigma = sigma; sim->func = g_strdup(func); sim->name = g_strdup(name); sim->fitpoly = gtk_adjustment_get_value(b->wins.fitpoly); sim->weighted = gtk_toggle_button_get_active(b->wins.weighted); sim->smoothing = gtk_adjustment_get_value(b->wins.smoothing); sim->ideathmean = ideathmean; sim->ideathcoef = idcoef; sim->kml = kml; sim->migrant = migrants; sim->maptop = maptop; sim->mapindex = mapindex; if ((sim->mapindexfix = mapindexfix) > sim->islands) { g_debug("Clamping map index to %zu", sim->islands - 1); sim->mapindexfix = sim->islands - 1; } g_mutex_init(&sim->hot.mux); g_cond_init(&sim->hot.cond); /* Source for the fraction of mutants. */ sim->bufs.fractions = kdata_array_alloc(NULL, slices); g_assert(NULL != sim->bufs.fractions); sim->bufs.ifractions = kdata_array_alloc(NULL, islands); g_assert(NULL != sim->bufs.ifractions); sim->bufs.mutants = kdata_array_alloc(NULL, slices); g_assert(NULL != sim->bufs.mutants); sim->bufs.incumbents = kdata_array_alloc(NULL, slices); g_assert(NULL != sim->bufs.incumbents); sim->bufs.islands = kdata_array_alloc(NULL, islands); g_assert(NULL != sim->bufs.islands); sim->bufs.meanmins = kdata_array_alloc(NULL, slices); g_assert(NULL != sim->bufs.meanmins); sim->bufs.mextinctmaxs = kdata_array_alloc(NULL, slices); g_assert(NULL != sim->bufs.mextinctmaxs); sim->bufs.iextinctmins = kdata_array_alloc(NULL, slices); g_assert(NULL != sim->bufs.iextinctmins); sim->bufs.fitpoly = kdata_array_alloc(NULL, slices); g_assert(NULL != sim->bufs.fitpoly); sim->bufs.fitpolybuf = kdata_buffer_alloc(slices); g_assert(NULL != sim->bufs.fitpolybuf); sim->bufs.fitpolymins = kdata_array_alloc(NULL, slices); g_assert(NULL != sim->bufs.fitpolymins); sim->bufs.meanminqbuf = kdata_array_alloc(NULL, CQUEUESZ); g_assert(NULL != sim->bufs.meanminqbuf); sim->bufs.fitminqbuf = kdata_array_alloc(NULL, CQUEUESZ); g_assert(NULL != sim->bufs.fitminqbuf); for (i = 0; i < slices; i++) { strat = xmin + (xmax - xmin) * (i / (double)slices); kdata_array_set(sim->bufs.fractions, i, strat, 0); kdata_array_set(sim->bufs.mutants, i, strat, 0); kdata_array_set(sim->bufs.incumbents, i, strat, 0); kdata_array_set(sim->bufs.meanmins, i, strat, 0); kdata_array_set(sim->bufs.mextinctmaxs, i, strat, 0); kdata_array_set(sim->bufs.iextinctmins, i, strat, 0); kdata_array_set(sim->bufs.fitpoly, i, strat, 0); kdata_array_set(sim->bufs.fitpolymins, i, strat, 0); } sim->bufs.times = simbuf_alloc (kdata_array_alloc(NULL, stop + 1), stop + 1); sim->bufs.islandmeans = simbuf_alloc (kdata_mean_alloc(sim->bufs.islands), islands); sim->bufs.islandstddevs = simbuf_alloc (kdata_stddev_alloc(sim->bufs.islands), islands); sim->bufs.imeans = simbuf_alloc (kdata_mean_alloc(sim->bufs.ifractions), islands); sim->bufs.istddevs = simbuf_alloc (kdata_stddev_alloc(sim->bufs.ifractions), islands); sim->bufs.means = simbuf_alloc (kdata_mean_alloc(sim->bufs.fractions), slices); sim->bufs.stddevs = simbuf_alloc (kdata_stddev_alloc(sim->bufs.fractions), slices); sim->bufs.mextinct = simbuf_alloc (kdata_mean_alloc(sim->bufs.mutants), slices); sim->bufs.iextinct = simbuf_alloc (kdata_mean_alloc(sim->bufs.incumbents), slices); /* * Conditionally allocate our fitness polynomial structures. * These are per-simulation as they're only run by one thread at * any one time during the simulation. */ if (sim->fitpoly) { sim->work.X = gsl_matrix_alloc (sim->dims, sim->fitpoly + 1); sim->work.y = gsl_vector_alloc(sim->dims); sim->work.w = gsl_vector_alloc(sim->dims); sim->work.c = gsl_vector_alloc(sim->fitpoly + 1); sim->work.cov = gsl_matrix_alloc (sim->fitpoly + 1, sim->fitpoly + 1); sim->work.work = gsl_multifit_linear_alloc (sim->dims, sim->fitpoly + 1); sim->work.coeffs = g_malloc0_n (sim->fitpoly + 1, sizeof(double)); } sim->nprocs = gtk_adjustment_get_value(b->wins.nthreads); sim->totalpop = totalpop; sim->stop = stop; sim->alpha = alpha; sim->colour = b->nextcolour++; sim->delta = delta; sim->m = m; sim->ms = ms; sim->pop = islandpop; sim->pops = islandpops; sim->input = input; sim->exp = exp; sim->xmin = xmin; sim->xmax = xmax; sim->ymin = ymin; sim->ymax = ymax; b->sims = g_list_append(b->sims, sim); sim_ref(sim, NULL); sim->threads = g_malloc0_n(sim->nprocs, sizeof(struct simthr)); g_debug("%p: Simulation created", sim); /* Create the simulation threads. */ for (i = 0; i < sim->nprocs; i++) { sim->threads[i].rank = i; sim->threads[i].sim = sim; sim->threads[i].thread = g_thread_new (NULL, simulation, &sim->threads[i]); } /* Create the simulation window. */ cur = g_malloc0(sizeof(struct curwin)); cur->view = VIEW_MEAN; window_init(b, cur, g_list_append(NULL, sim)); /* Initialise the name of our simulation. */ donamefill(&b->wins); return; cleanup: if (NULL != ms) for (i = 0; i < islands; i++) g_free(ms[i]); g_free(islandpops); g_free(ms); hnode_free(exp); kml_free(kml); }
{ "alphanum_fraction": 0.6923040255, "avg_line_length": 28.3110661269, "ext": "c", "hexsha": "ba4729942773e0b6d57c6a2560957855c4d3febd", "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": "0280a899564031a5a14af87d9264cd239a89851f", "max_forks_repo_licenses": [ "0BSD" ], "max_forks_repo_name": "kristapsdz/bmigrate", "max_forks_repo_path": "simwin.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "0BSD" ], "max_issues_repo_name": "kristapsdz/bmigrate", "max_issues_repo_path": "simwin.c", "max_line_length": 75, "max_stars_count": 1, "max_stars_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f", "max_stars_repo_licenses": [ "0BSD" ], "max_stars_repo_name": "kristapsdz/bmigrate", "max_stars_repo_path": "simwin.c", "max_stars_repo_stars_event_max_datetime": "2018-03-03T17:13:19.000Z", "max_stars_repo_stars_event_min_datetime": "2018-03-03T17:13:19.000Z", "num_tokens": 13251, "size": 41957 }
#ifndef PRIMAL_DUAL_LOOPLESS_H #define PRIMAL_DUAL_LOOPLESS_H #include "problem_data.h" #include <string> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <stdio.h> /* printf */ #include <time.h> #include <fstream> #include <algorithm> #include <iomanip> #include <ctime> #include <sstream> #include <omp.h> //This class implements the loopless variance reduced type methods with arbitrary sampling /* The optimization problem to solve is: \sum_{i=1}^n \lambda_i\phi_i(A_i^{\top} w)+ g(w) Assumption 1: For each i, \phi_i is 1-smooth By default, lambda_i=1/n for all i. * * The dual problem is * g*(-sum_{i=1}^n \lambda_i \alpha_i A_i)+\sum_{i=1}^n \lambda_i \phi*_i(\alpha_i) */ template<typename L, typename D> class Primal_Dual_LOOPLESS: public problem_data<L, D> { private: // involved variables std::vector<D> proba_vector; std::vector<D> tilde_proba_vector; std::vector<D> group_C; std::vector<D> index_group_C; std::vector<D> maxp_group_C; std::vector<D> isolated_I; std::vector<D> sump_group_C; vector<D> theta_S; //theta_S in the paper std::vector<D> Li; std::vector<D> gk; // the vector g^k in the paper // auxiliary variables std::vector<D> deltagk; std::vector<D> index_to_do_prox; std::vector<D> whether_or_not_to_do_prox; L nb_of_iters_per_loop; D primal_value; D dual_value; D epsilon; L max_nb_loops; D max_p; D maxv; D lambda_1; D lambda_2; D running_time; L nb_loops; L print_every_N; D delta; vector<L> batch_i; vector<L> my_batch; vector<D> batch_deltaalphai; L batch_size; L nb_groups; //number of groups in group sampling protected: std::vector<D> primal_x; // the x variable string uniform; D Lf; D L2; D L1; D sumLi; D p; // the probability of changing w to x as in the paper L tau; //number of threads on each node/computer D scaler; std::vector<D> dual_alpha; // dual_alpha[i]=\phi_i'(A_i't) std::vector<D> lambda_f; // lambda_f[i]=lambda_i std::vector<D> baralpha; // baralpha=sum_{i=1}^{nsamples} lambda_f[i]* dual_alpha[i]*A_i L current_nb_iters; L nb_iters; std::vector<D> last_update_i; ofstream samp; public: gsl_rng * rng; virtual inline D gradient_of_phi_i(D, L){return D(NULL);} virtual inline D gradient_of_gstar_j(D, L){return D(NULL);} virtual inline D value_of_phi_i(D, L) {return D(NULL);} virtual inline D value_of_g_j(D, L){return D(NULL);} virtual inline D value_of_phistar_i(D,L) {return D(NULL);} virtual inline D value_of_gstar(vector<D> &){return D(NULL);} virtual inline D value_of_gstar_minus(vector<D> &, D){return D(NULL);} virtual inline D feasible_dual(vector<D> &){return D(NULL);} virtual inline D compute_delta_alpha(D,D,L){return D(NULL);} virtual inline void set_auxiliary_v(){} virtual inline D get_lambda1(){return D(NULL);} virtual inline D get_lambda2(){return D(NULL);} virtual inline D compute_current_xj_value(D , L, L , L){return D(NULL);} virtual inline D compute_current_xj_value_without_update(D , L, L , L){return D(NULL);} virtual inline void set_stepsize(){} virtual inline void update_x(D,L){} virtual inline void update_baralpha(){} Primal_Dual_LOOPLESS() : problem_data<L,D>() { } Primal_Dual_LOOPLESS(const char* matrix_file, const char* vector_file) : problem_data<L,D>(matrix_file, vector_file) { } Primal_Dual_LOOPLESS(const char* matrix_file) : problem_data<L,D>(matrix_file) { } void set_rng() { gsl_rng_env_setup(); const gsl_rng_type * T; T = gsl_rng_default; rng = gsl_rng_alloc(T); gsl_rng_set(rng,time(NULL)); //gsl_rng_set(rng, 27432042); } void set_print_every_N(L i){print_every_N=i;} void set_L1(L p){ if(p==0){ //batch sampling mode (stochastic process in the paper) L1=(1-1./tau)*Lf+L2; }else{ //group sampling mode L1=Lf+L2; } // alpha_l=1/(4.*L1+2*L2); } void set_Li_Lf() { sumLi=0; maxv=0; D minv=std::numeric_limits<double>::max(); Li.resize(this->nsamples,0); for(L i=0;i<this->nsamples;i++) { D vi=0; for (L k = this->ptr[i]; k < this->ptr[i + 1];k++) { vi+=lambda_f[i]*this->nsamples*this->A[k]*this->A[k]; } Li[i]=vi; if(maxv<vi) maxv=vi; if(minv>vi) minv=vi; } for(L i=0;i<this->nsamples;i++){ if(Li[i]<maxv*1e-15) { for (L k = this->ptr[i]; k < this->ptr[i + 1];k++) { this->A[k]=0; L j=this->row_idx[k]; for (L kj = this->ptr_t[j]; kj < this->ptr_t[j + 1]; kj++) { L i2=this->col_idx[kj]; if(i2==i) this->A_t[kj]=0; } } Li[i]=maxv*1e-15; } sumLi+=Li[i]; } Lf=compute_lambda_max(10); cout<<" max of v: "<<maxv<<" min of v: "<<minv<<" sumof Li="<<sumLi<<" Lf= "<<Lf<<endl; } //compute the maximal eigenvalue of sum_{i=1}^m \lambda_f[i]*A_i*A_i' by power iteration D compute_lambda_max(L K){ std::vector<D> bk(this->nfeatures); for (L j=0;j<this->nfeatures;j++) { bk[j]=1; } std::vector<D> yk(this->nsamples); D normk; D tmp; for(L kk=0;kk<K;kk++){ for (L i=0;i<this->nsamples;i++){ tmp=0; for (L k = this->ptr[i]; k < this->ptr[i + 1]; k++) { L j=this->row_idx[k]; tmp+=this->A[k]*bk[j]; } yk[i]=tmp; } normk=0; for (L j=0;j<this->nfeatures;j++){ bk[j]=0; for (L k = this->ptr_t[j]; k < this->ptr_t[j + 1]; k++) { L i=this->col_idx[k]; bk[j]+=this->A_t[k]*yk[i]*lambda_f[i]; } normk+=bk[j]*bk[j]; } normk=sqrt(normk); for (L j=0;j<this->nfeatures;j++) {bk[j]=bk[j]/normk; } } cout<<endl; D res=0; normk=0; for (L i=0;i<this->nsamples;i++){ tmp=0; for (L k = this->ptr[i]; k < this->ptr[i + 1]; k++) { L j=this->row_idx[k]; tmp+=this->A[k]*bk[j]; } yk[i]=tmp; normk+=yk[i]*yk[i]; } std::vector<D> bk2(this->nfeatures); for (L j=0;j<this->nfeatures;j++){ bk2[j]=0; for (L k = this->ptr_t[j]; k < this->ptr_t[j + 1]; k++) { L i=this->col_idx[k]; bk2[j]+=this->A_t[k]*yk[i]*lambda_f[i]; } } for (L j=0;j<this->nfeatures;j++) res+=bk2[j]*bk[j]; return res; } void set_optimal_probability() { tilde_proba_vector.clear(); tilde_proba_vector.resize(this->nsamples,0); proba_vector.clear(); proba_vector.resize(this->nsamples,0); D sum=0; for(L i=0; i<this->nsamples;i++) { tilde_proba_vector[i]=Li[i]; sum+=Li[i]; } max_p=0; for(L i=0; i<this->nsamples;i++) { tilde_proba_vector[i]=tilde_proba_vector[i]/sum; proba_vector[i]=1-pow(1-tilde_proba_vector[i],tau); if(max_p<tilde_proba_vector[i]) { max_p=tilde_proba_vector[i]; } } cout<<"sum="<<sum<<"; proba"<<tilde_proba_vector[0]<<endl; } void set_group_sampling_probability(){ proba_vector.clear(); proba_vector.resize(this->nsamples,0); std::vector<D> q(this->nsamples); D sumq=0; cout<<"start setting group sampling probablity"<<endl; for(L i=0; i<this->nsamples;i++) { q[i]=Li[i]; sumq+=q[i]; } D maxq=0; L nb=0; D tmp=0; for(L i=0; i<this->nsamples;i++) { q[i]=q[i]/sumq*tau; if(q[i]>maxq) maxq=q[i]; if(q[i]>1) { nb++; //count the number of elements larger than 1 tmp+=q[i]-1; } } cout<<"maxq="<<maxq<<endl; if(maxq<=1){ for(L i=0; i<this->nsamples;i++) { proba_vector[i]=q[i]; } }else{ for(L i=0; i<this->nsamples;i++) { if(q[i]>1) q[i]=1; else { D deltaq=min(1-q[i],tmp); tmp=tmp-deltaq; q[i]+=deltaq; } proba_vector[i]=q[i]; } } } void set_L2(L p_mod, L u){ if(p_mod==0){ //batch sampling mode D tmp=0; D st; for(L i=0;i<this->nsamples;i++){ st=Li[i]/tilde_proba_vector[i]; if (st>tmp) tmp=st; } L2=tmp/this->nsamples/tau; cout<<"L2="<<L2<<"; "<<tilde_proba_vector[0]<<endl; } else{ //group sampling mode D tmp=0; D st; for(L i=0;i<this->nsamples;i++){ st=Li[i]/proba_vector[i]; if(isolated_I[i]==1) st=st-Li[i]; if(st>tmp) tmp=st; } L2=tmp/this->nsamples; } cout<<"set_L2="<<L2<<endl; } void set_uniform_probability(L p_mod) { if(p_mod==0) { //batch sampling (stochastic process as defined in the paper) proba_vector.clear(); tilde_proba_vector.clear(); tilde_proba_vector.resize(this->nsamples,1./this->nsamples); proba_vector.resize(this->nsamples,1-pow(1-1.0/this->nsamples,tau)); max_p=1.0/this->nsamples; cout<<"uniform="<<tilde_proba_vector[0]<<endl; } else{ //group sampling D pi=(tau*this->c+0.0)/this->nsamples; proba_vector.clear(); proba_vector.resize(this->nsamples,pi); } } void sort_p(){ vector<pair<D,L> >a; for (L i = 0 ;i < this->nsamples ; i++) { a.push_back(make_pair(proba_vector[i],i)); // k = value, i = original index } sort(a.begin(),a.end()); group_C.clear(); group_C.resize(this->nsamples); isolated_I.clear(); isolated_I.resize(this->nsamples,0); D tmp=0; D maxpi=0; D previous_i=0; index_group_C.clear(); index_group_C.push_back(0); maxp_group_C.clear(); sump_group_C.clear(); for (L i = 0 ;i < this->nsamples ; i++){ group_C[i]=a[this->nsamples-1-i].second; D pi=a[this->nsamples-1-i].first; if(tmp+pi<=1){ if(pi>maxpi) maxpi=pi; tmp+=pi; } else{ index_group_C.push_back(i); maxp_group_C.push_back(maxpi); sump_group_C.push_back(tmp); tmp=pi; maxpi=pi; if(i-previous_i==1) isolated_I[group_C[previous_i]]=1; previous_i=i; } } index_group_C.push_back(this->nsamples); maxp_group_C.push_back(maxpi); sump_group_C.push_back(tmp); nb_groups=sump_group_C.size(); if(previous_i==this->nsamples-1) isolated_I[group_C[previous_i]]=1; cout<<"size of group="<<nb_groups<<endl; } inline L sampling(L n) { L i=(floor)(gsl_rng_uniform(rng)*n); D y=gsl_rng_uniform(rng); while(y*max_p>tilde_proba_vector[i]) { i=(floor)(gsl_rng_uniform(rng)*n); y=gsl_rng_uniform(rng); } return i; } void set_initial_dual(){ for(L i=0;i<this->nsamples;i++) { D res=0; for (L k = this->ptr[i]; k < this->ptr[i + 1];k++) { L j=this->row_idx[k]; res+=this->A[k]*primal_x[j]; } dual_alpha[i]=gradient_of_phi_i(res,i); } } void update_primal() { L nb_indices=0; //#pragma omp parallel for for(L i_t=0;i_t<batch_size;i_t++) { L i=batch_i[i_t]; D deltaalphai=batch_deltaalphai[i_t]; for (L k = this->ptr[i]; k < this->ptr[i + 1];k++) { L j=this->row_idx[k]; if (whether_or_not_to_do_prox[j]==0) { //#pragma omp critical { whether_or_not_to_do_prox[j]=1; index_to_do_prox[nb_indices]=j; nb_indices++; deltagk[j]=0; } } deltagk[j]+=lambda_f[i]*deltaalphai*this->A[k]*theta_S[i]; } } #pragma omp parallel for for(L i_d=0;i_d<nb_indices;i_d++){ L j=index_to_do_prox[i_d]; D xj=compute_current_xj_value(baralpha[j]+deltagk[j], j,last_update_i[j],current_nb_iters); //update_x(xj,j); last_update_i[j]=current_nb_iters; whether_or_not_to_do_prox[j]=0; index_to_do_prox[i_d]=-1; } } void update_baralpha(L i, D deltaalphai) { for (L k = this->ptr[i]; k < this->ptr[i + 1]; k++) { L j=this->row_idx[k]; baralpha[j]+=lambda_f[i]*deltaalphai*this->A[k]; } } D compute_AiTxk(L i) //This function compute A_i^\top x^k { D res=0; D xj; for (L k = this->ptr[i]; k < this->ptr[i + 1];k++) { L j=this->row_idx[k]; if(current_nb_iters!=last_update_i[j]) { xj=compute_current_xj_value(baralpha[j], j,last_update_i[j],current_nb_iters); //update_x(xj,j); } res+=this->A[k]*primal_x[j]; last_update_i[j]=current_nb_iters; } return res; } D compute_AiTxk_without_update(L i) //This function compute A_i^\top x^k without updating x^k { D res=0; D xj; //#pragma omp parallel for reduction(+:res) for (L k = this->ptr[i]; k < this->ptr[i + 1];k++) { L j=this->row_idx[k]; if(current_nb_iters!=last_update_i[j]) { xj=compute_current_xj_value_without_update(baralpha[j], j,last_update_i[j],current_nb_iters); } else { xj=primal_x[j]; } res+=this->A[k]*xj; } return res; } void compute_dual_value() { D res=0; //D alphaAx= 0; std::vector<D> alpha_tmp(this->nsamples,0); std::vector<D> baralpha_tmp(this->nfeatures,0); //#pragma omp parallel for schedule(dynamic) for(L i=0;i<this->nsamples;i++) { D aitx=compute_AiTxk_without_update(i); alpha_tmp[i]=gradient_of_phi_i(aitx,i); //alphaAx+= lambda_f[i]*alpha_tmp[i]*aitx; for (L k = this->ptr[i]; k < this->ptr[i + 1]; k++) { L j=this->row_idx[k]; baralpha_tmp[j]+=lambda_f[i]*alpha_tmp[i]*this->A[k]; } } D scal=feasible_dual(baralpha_tmp); //#pragma omp parallel for reduction(-:res) for(L i=0;i<this->nsamples;i++) { res-=value_of_phistar_i(scal*alpha_tmp[i],i)*lambda_f[i]; } res-=value_of_gstar_minus(baralpha_tmp,scal); // should have used value_of_gstar(-baralpha) dual_value=res; } void compute_primal_value() { D res=0; //#pragma omp parallel for reduction(+:res) for(L i=0;i<this->nsamples;i++) { D aitx=compute_AiTxk_without_update(i); res+=lambda_f[i]*value_of_phi_i(aitx,i); } D res2=0; //#pragma omp parallel for reduction(+:res2) for(L j=0; j<this->nfeatures; j++) { D xj=compute_current_xj_value_without_update(baralpha[j], j,last_update_i[j],current_nb_iters); D gj=value_of_g_j(xj,j); res2+=gj; } primal_value= res+res2; } void compute_initial_dual_value() { D res=0; D scal=feasible_dual(baralpha); #pragma omp parallel for reduction(-:res) for(L i=0;i<this->nsamples;i++) { res-=value_of_phistar_i(scal*dual_alpha[i],i)*lambda_f[i]; } //cout<< "d_1(x)= "<< res<< " d_2(x)= "<< value_of_gstar_minus(baralpha,scal)<< endl; res-=value_of_gstar_minus(baralpha,scal); // should have used value_of_gstar(-baralpha) dual_value=res; } void compute_initial_primal_value() { D res=0; #pragma omp parallel for reduction(+:res) for(L j=0; j<this->nfeatures; j++) { res+=value_of_g_j(primal_x[j],j); } D res2=0; #pragma omp parallel for reduction(+:res2) for(L i=0;i<this->nsamples;i++) { D aitx=0; for (L k = this->ptr[i]; k < this->ptr[i + 1]; k++) { L j=this->row_idx[k]; aitx+=this->A[k]*primal_x[j]; } res2+=lambda_f[i]*value_of_phi_i(aitx,i); } //cout<< "p_1(x)= "<< res<< " p_2(x)= "<< res2<< endl; primal_value= res+res2; } void set_p(D scal_p){ if(scal_p==4.6){ p=sqrt(this->mu/L1*tau/this->nsamples); } else if (scal_p==5.6){ p=this->mu/L1; } else{ p=scal_p*tau/(0.0+this->nsamples); } cout<<"changing probablity: "<<p<<endl; } void initialize(vector<D> & x0, vector<D> & w0, vector<D> & L_phi, D val_mu, D val_epsilon, L max_nb, L nb_tau, L nb_c, L u, L p_mod, D scal_p) { cout<<"start initializing"<<" u="<<u<<endl; this->distributed_set_up(nb_c); if(nb_tau>this->noverc) perror("tau should be less than n over c"); tau=nb_tau; nb_of_iters_per_loop=floor(this->nsamples/(this->c*(tau+0.0))); batch_i.clear(); batch_deltaalphai.clear(); batch_i.resize(this->nsamples,0); batch_deltaalphai.resize(this->nsamples,0); deltagk.clear(); deltagk.resize(this->nfeatures,0); index_to_do_prox.clear(); index_to_do_prox.resize(this->nfeatures,-1); whether_or_not_to_do_prox.clear(); whether_or_not_to_do_prox.resize(this->nfeatures,0); gk.clear(); gk.resize(this->nfeatures,0); /**setup parameters**/ epsilon=val_epsilon; max_nb_loops=max_nb; this->mu=val_mu; cout<<"mu="<<this->mu<<endl; lambda_f.clear(); lambda_f.resize(this->nsamples,0); //L_phi is the Lipschitz constant of the function \phi_i. for(int i=0;i< this->nsamples; i++){ lambda_f[i]= L_phi[i]/this->nsamples; } set_rng(); set_auxiliary_v(); lambda_1=get_lambda1(); lambda_2=get_lambda2(); set_Li_Lf(); running_time=0; /**setup probability**/ if(p_mod==0) // batch sampling (stochastic process as defined in the paper) { if(u==0) // uniform sampling { set_uniform_probability(p_mod); this->uniform="uniform"; } else{ set_optimal_probability(); this->uniform="nonuniform"; } } else{ //group sampling if(u==0){ set_uniform_probability(p_mod); this->uniform="uniform"; }else{ this->set_group_sampling_probability(); this->uniform="nonuniform"; } sort_p(); cout<<"sort p"<<endl; } set_L2(p_mod,u); scaler=scal_p; set_L1(p_mod); cout<<"set L1="<<L1<<endl; set_p(scal_p); set_thetaS(p_mod); cout<<"setthetaS"<<endl; primal_x=w0; dual_alpha=x0; set_stepsize(); cout<<"set stepsize"<<endl; set_initial_dual(); baralpha.clear(); baralpha.resize(this->nfeatures,0); last_update_i.clear(); last_update_i.resize(this->nfeatures,0); for(L i=0;i<this->nsamples;i++) { update_baralpha(i, dual_alpha[i]); } current_nb_iters=0; D start_time_initial=std::clock(); compute_initial_primal_value(); compute_initial_dual_value(); D end_time_initial=std::clock(); cout<<"computation of initial primal dual value time="<<(end_time_initial-start_time_initial) / (double) CLOCKS_PER_SEC<<endl; cout<<"primal value="<<primal_value<<endl; cout<<"dual_value="<<dual_value<<endl; cout<<"Initialization is finished!"<<endl; } void result_record() { cout<<primal_value<<endl; cout<<dual_value<<endl; ofstream result; result.open("results/x0.dat"); for (L j=0;j<this->nfeatures;j++){ result <<setprecision(20)<< primal_x[j] << " "; //cout<< primal_x[j] << " "; } result << endl; ofstream resulta; resulta.open("results/alpha0.dat"); for (L i=0;i<this->nsamples;i++) resulta << setprecision(20)<<dual_alpha[i] << " "; resulta << endl; result.close(); } void read_w0(){ ifstream recordw0("results/x0.dat"); for(L j=0;j<this->nfeatures;j++) { recordw0>>primal_x[j]; } recordw0.close(); ifstream recordalpha0("results/alpha0.dat"); for(L i=0;i<this->nsamples;i++) { recordalpha0>>dual_alpha[i]; } recordalpha0.close(); } void compute_and_record_result() { if(nb_loops%print_every_N==0){ D start = std::clock(); compute_primal_value(); D endt=std::clock(); cout<<"computation of primal value time="<<(endt-start) / (double) CLOCKS_PER_SEC<<endl; compute_dual_value(); delta=primal_value-dual_value; cout<<setprecision(16)<<floor(((0.0+nb_iters)*this->c*tau/(this->nsamples)))<<";;; "<<running_time<<"; primal dual gap="<<delta<<" primal value="<<primal_value<<"; dual value="<<dual_value<<endl; samp<<floor(((0.0+nb_iters)*this->c*tau/(this->nsamples)))<<" "<<delta<<" "<<running_time<<" "<<primal_value<<endl; } } void batch_sampling() { batch_size=0; L i; for(L it_t=0;it_t<tau;it_t++) { i=sampling(this->nsamples); batch_i[batch_size]=i; batch_size++; } } void set_thetaS(L p_mod){ theta_S.clear(); theta_S.resize(this->nsamples,0); if(p_mod==0){ for(L i=0;i<this->nsamples;i++) theta_S[i]=1.0/(tau*tilde_proba_vector[i]); } else{ for(L i=0;i<this->nsamples;i++) theta_S[i]=1.0/proba_vector[i]; } } void group_sampling(){ batch_size=0; std::vector<L> sampled_groups; for(L i=0;i<nb_groups;i++){ D y=gsl_rng_uniform(rng); if(y<sump_group_C[i]) { sampled_groups.push_back(i); batch_size++; } } for(L t=0;t<batch_size;t++){ L group_i=sampled_groups[t]; L s1=index_group_C[group_i]; L s2=index_group_C[group_i+1]; L i=s1+(floor)(gsl_rng_uniform(rng)*(s2-s1)); D y=gsl_rng_uniform(rng); D maxpi=maxp_group_C[group_i]; while(y*maxpi>proba_vector[group_C[i]]) { i=s1+(floor)(gsl_rng_uniform(rng)*(s2-s1)); y=gsl_rng_uniform(rng); } batch_i[t]=group_C[i]; } } void loopless(vector<D> & x0, vector<D> & w0, string filename, vector<D> & L_phi, D val_mu, D val_epsilon, L max_nb, L nb_tau, L nb_c, L u, L p_mod, D scal_p) { initialize(x0, w0, L_phi, val_mu, val_epsilon, max_nb, nb_tau, nb_c, u, p_mod, scal_p); string sampname="results/L_"+filename+uniform; if(p_mod==0) sampname=sampname+"_batch"; else sampname=sampname+"_group"; string scal_str; stringstream scal_convert; scal_convert<<scal_p; scal_str=scal_convert.str(); sampname+=scal_str; cout<<"running Loopless"<<" ; "<<sampname<<endl; samp.open(sampname.c_str()); delta=primal_value-dual_value; nb_loops=0; nb_iters=0; cout<<setprecision(9)<<"initial: "<<" delta: "<<delta<<" primal: "<<primal_value<<"; dual: "<<dual_value<<"epsilon="<<epsilon<<endl; samp<<((0.0+nb_iters)*this->c*tau/(this->nsamples))<<" "<<delta<<running_time<<" "<<primal_value<<endl; srand48(27432042); //srand(time(NULL)); printf("There are %d threads\n",omp_get_num_threads()); D start; while(delta>=epsilon && nb_loops<max_nb_loops) { compute_and_record_result(); if(delta<epsilon) break; start = std::clock(); nb_loops++; //cout<<"before the loop time elapsed="<<duration<<endl; start = std::clock(); //cout<<"nb_of_iters_per_loop="<<nb_of_iters_per_loop<<endl; for(L it=0;it<nb_of_iters_per_loop;it++) { if(p_mod==0) batch_sampling(); else group_sampling(); //start = std::clock(); start=omp_get_wtime(); #pragma omp parallel { #pragma omp for for(L i_t=0;i_t<batch_size;i_t++) { L i=batch_i[i_t]; D aitg=compute_AiTxk(i); D deltaalphai=(gradient_of_phi_i(aitg,i)-dual_alpha[i]); batch_deltaalphai[i_t]=deltaalphai; } } //cout<<omp_get_wtime()-start<<endl; current_nb_iters++; update_primal(); update_baralpha(); nb_iters++; D end_time = omp_get_wtime(); //running_time+= ( std::clock() - start ) / (double) CLOCKS_PER_SEC; running_time+=end_time-start; } //cout<<"after the loop time elapsed="<<duration<<endl; } if(delta>=epsilon) {compute_primal_value(); compute_dual_value(); delta=primal_value-dual_value; cout<<setprecision(9)<<floor(((0.0+nb_iters)*this->c*tau/(this->nsamples)))<<"; "<<running_time<<"; primal dual gap="<<delta<<" primal value="<<primal_value<<"; dual value="<<dual_value<<endl; samp<<floor(((0.0+nb_iters)*this->c*tau/(this->nsamples)))<<" "<<delta<<" "<<running_time<<" "<<primal_value<<endl; } cout<<setprecision(9)<<"nb_loops: "<<nb_loops<<"nb_iters"<<floor(((0.0+nb_iters)*this->c*tau/(this->nsamples)))<<"; delta: "<<delta<<" primal: "<<primal_value<<"; dual: "<<dual_value<<endl; samp.close(); } void loopless2(vector<D> & x0, vector<D> & w0, string filename, vector<D> & L_phi, D val_mu, D val_epsilon, L max_nb, L nb_tau, L nb_c, L u, L p_mod, D scal_p) { initialize(x0, w0, L_phi, val_mu, val_epsilon, max_nb, nb_tau, nb_c, u, p_mod, scal_p); string sampname="results/L_"+filename+uniform; if(p_mod==0) sampname=sampname+"_batch"; else sampname=sampname+"_group"; string scal_str; stringstream scal_convert; scal_convert<<scal_p; scal_str=scal_convert.str(); sampname+=scal_str; cout<<"running Loopless"<<" ; "<<sampname<<endl; samp.open(sampname.c_str()); delta=primal_value-dual_value; nb_loops=0; nb_iters=0; cout<<setprecision(9)<<"initial: "<<" delta: "<<delta<<" primal: "<<primal_value<<"; dual: "<<dual_value<<endl; samp<<((0.0+nb_iters)*this->c*tau/(this->nsamples))<<" "<<delta<<running_time<<" "<<primal_value<<endl; //srand48(27432042); srand(time(NULL)); D start; while(nb_loops<max_nb_loops) { compute_and_record_result(); start = std::clock(); nb_loops++; //cout<<"before the loop time elapsed="<<duration<<endl; start = std::clock(); //cout<<"nb_of_iters_per_loop="<<nb_of_iters_per_loop<<endl; for(L it=0;it<nb_of_iters_per_loop;it++) { if(p_mod==0) batch_sampling(); else group_sampling(); start = std::clock(); for(L i_t=0;i_t<batch_size;i_t++) { L i=batch_i[i_t]; D aitg=compute_AiTxk(i); D deltaalphai=(gradient_of_phi_i(aitg,i)-dual_alpha[i]); batch_deltaalphai[i_t]=deltaalphai; } current_nb_iters++; update_primal(); update_baralpha(); nb_iters++; running_time+= ( std::clock() - start ) / (double) CLOCKS_PER_SEC; } //cout<<"after the loop time elapsed="<<duration<<endl; } cout<<setprecision(9)<<"nb_loops: "<<floor(((0.0+nb_iters)*this->c*tau/(this->nsamples)))<<"; delta: "<<delta<<" primal: "<<primal_value<<"; dual: "<<dual_value<<endl; samp.close(); } }; #endif /* MIN_SMOOTH_CONVEX_H */
{ "alphanum_fraction": 0.5619774891, "avg_line_length": 25.0280797101, "ext": "h", "hexsha": "740385b1c37e0a49f063a626ca996fa0c273a5c8", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-01-15T04:23:24.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-15T04:23:24.000Z", "max_forks_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff", "max_forks_repo_licenses": [ "BSD-Source-Code" ], "max_forks_repo_name": "lifei16/supplementary_code", "max_forks_repo_path": "IPALM_OPENMP/Primal_Dual_LOOPLESS.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-Source-Code" ], "max_issues_repo_name": "lifei16/supplementary_code", "max_issues_repo_path": "IPALM_OPENMP/Primal_Dual_LOOPLESS.h", "max_line_length": 203, "max_stars_count": null, "max_stars_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff", "max_stars_repo_licenses": [ "BSD-Source-Code" ], "max_stars_repo_name": "lifei16/supplementary_code", "max_stars_repo_path": "IPALM_OPENMP/Primal_Dual_LOOPLESS.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 8106, "size": 27631 }
#pragma once #include <assert.h> #include <math.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include "defines.h" #include "matrix_vector_ops.h" #define DEFAULT_DIFF_ERROR_TOLERANCE 5e-5 #define DEFAULT_DIFF_STEPSIZE 1e-2 #define MAX_DIFF_CORRECTION_ATTEMPTS 100 #define RUNGE_KUTTA_ORDER 5 typedef int (*DynamicsFunction) (gsl_vector *dy, double t, const gsl_vector *y, const gsl_vector *u); // Runge-Kutte-Dormand-Prince embedded method modified for controlled systems //TODO implement adaptive step size int rungeKutteStep(DynamicsFunction dyn, double t, gsl_vector *y_next, gsl_vector *rk_e_next, const VehicleState *vehicle, const Controller *controller, double h); int rungeKutteAdaptiveStep(DynamicsFunction dyn, double t, gsl_vector *y_next, gsl_vector *rk_e_next, const VehicleState *vehicle, const Controller *controller, double *stepSize, double tolerance); //TODO implement implicit RK method as well for stiff equations
{ "alphanum_fraction": 0.5648011782, "avg_line_length": 31.5813953488, "ext": "h", "hexsha": "645b419905d8edb0ce7488184a48fdab0cb6062a", "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": "d04a8fa496ec414e2cffdc70ee0beda85e0d7cb4", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "umd-agrc/SimpleControlSim", "max_forks_repo_path": "diff.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "d04a8fa496ec414e2cffdc70ee0beda85e0d7cb4", "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": "umd-agrc/SimpleControlSim", "max_issues_repo_path": "diff.h", "max_line_length": 77, "max_stars_count": null, "max_stars_repo_head_hexsha": "d04a8fa496ec414e2cffdc70ee0beda85e0d7cb4", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "umd-agrc/SimpleControlSim", "max_stars_repo_path": "diff.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 263, "size": 1358 }
/* Implementation for next reaction method */ #include <math.h> #include <stdint.h> #include <time.h> #include <stdio.h> #include <stdint.h> #include <float.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include "ssa.h" #include "nrm.h" #include "priorityq.h" #include "depgraph.h" const gsl_rng_type *SSARNGT; gsl_rng *SSARNG; void update_reaction(REACTION *r, SYSTEM *s, double t) { double newp = ssa_h(s->R[r->number], s->x, s->n) * s->k[r->number]; double oldp = s->propensities[r->number]; if (newp > 0.0) { if (oldp > 0.0) { pq_update(s->pq, r, (oldp / newp) * (r->tau - t) + t); } else { r->tau = gsl_ran_gamma(SSARNG, s->steps[r->number], 1 / newp) + t; pq_insert(s->pq, r); } } else if (oldp > 0.0) { pq_delete(s->pq, r); } s->propensities[r->number] = newp; } double ssa_nrmstep(SYSTEM *s) { REACTION *r = pq_min(s->pq); ssa_doreaction(s->R[r->number], s->P[r->number], s->x, s->n); double t = r->tau; s->propensities[r->number] = ssa_h(s->R[r->number], s->x, s->n) * s->k[r->number]; if (s->propensities[r->number] > 0.0) pq_update(s->pq, r, gsl_ran_gamma(SSARNG, s->steps[r->number], 1 / s->propensities[r->number]) + t); else pq_delete(s->pq, r); LLIST *head = r->affects; while (head != NULL) { REACTION *update = (REACTION *) head->data; update_reaction(update, s, t); head = head->next; } return t; } REACTION **setup_reactions(SYSTEM *s) { REACTION **reactions = malloc(sizeof(REACTION*) * s->m); char **adjmat = adjacencymatrix(s->R, s->P, s->n, s->m); INDEX i, j; for (i = 0; i < s->m; i++) { REACTION *reaction = reaction_make(i); reactions[i] = reaction; } for (i = 0; i < s->m; i++) { REACTION *r = reactions[i]; for (j = 0; j < s->m; j++) if (i != j && adjmat[i][j] != 0) r->affects = llist_push(r->affects, reactions[j]); } for (i = 0; i < s->m; i++) { REACTION *r = reactions[i]; for (j = 0; j < s->m; j++) { if (s->creates[i][j] != 0) r->creates = llist_push(r->creates, reactions[j]); if (s->destroys[i][j] != 0) r->destroys = llist_push(r->destroys, reactions[j]); } } for (i = 0; i < s->m; i++) free(adjmat[i]); free(adjmat); return reactions; } void ssa_nrm(INDEX **R, INDEX **P, INDEX n, INDEX m, double *k, COUNT *x, COUNT *steps, INDEX **creates, INDEX **destroys, double T) { gsl_rng_env_setup(); SSARNGT = gsl_rng_default; SSARNG = gsl_rng_alloc(SSARNGT); gsl_rng_set(SSARNG, time(NULL)); SYSTEM *s = malloc(sizeof(SYSTEM)); s->m = m; s->n = n; s->R = R; s->P = P; s->creates = creates; s->destroys = destroys; REACTION **reactions = setup_reactions(s); double *propensities = malloc(sizeof(double) * m); PQ *pq = pq_make(); s->pq = pq; s->x = x; s->steps = steps; s->k = k; s->propensities = propensities; INDEX i; for (i = 0; i < m; i++) { REACTION *r = reactions[i]; propensities[i] = ssa_h(R[i], x, n) * k[i]; if (propensities[i] > 0.0) { r->tau = gsl_ran_gamma(SSARNG, steps[i], 1 / propensities[i]); pq_insert(pq, r); } } ssa_printstate(0.0, x, n); while(!pq_isempty(pq) && pq_min(pq)->tau < T) ssa_printstate(ssa_nrmstep(s), x, n); pq_free(pq); gsl_rng_free(SSARNG); }
{ "alphanum_fraction": 0.5660490137, "avg_line_length": 23.2361111111, "ext": "c", "hexsha": "24590755176c68344b33d7b986a4ded1f1e90108", "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/nrm.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/nrm.c", "max_line_length": 132, "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/nrm.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1200, "size": 3346 }
#define _XOPEN_SOURCE 600 #include <stdlib.h> #include <stdio.h> #include <mpi.h> #include <stdint.h> #include <time.h> #include <math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <errno.h> #include "fileio.h" #include "likelihood.h" #include "master_tasks.h" #include "mutation.h" #include "radix.h" #include "randomisation.h" #include "resampling.h" #include "typedefs.h" static const int ALG = 6; static const int MASTER = 0; int main ( int argc, char *argv[]) { struct Process process; struct Estimates estimates; int pair_rank, src; int do_resampling; long *inds; double *w, *x, *x_resamp; double total_w = 1; double my_normal_weight; double w_pair[2]; double rsamp_time=0; double rsamp_start=0; double comm_time=0; double comm_start; double comm_time2=0; double *output; double weight_time = 0; double mutation_time = 0.0; double init_time = 0.0; unsigned int cnts[2]; short counts[2]; short n_resamp; const gsl_rng_type * T; double timer_start; // Parse commandline arguments int run_idx = 0; if ( argc > 1 ) run_idx = atoi( argv[ 1 ] ); long N = 1000; if ( argc > 2 ) N = atol( argv[ 2 ] ); int state_dim; if ( argc > 3 ) state_dim = atoi( argv[ 3 ] ); else { perror("State dimesion must be provided"); return -1; } double epc_threshold; if (argc > 4 ) { epc_threshold = atof( argv[ 4 ] ); } else { perror("Reampling threshold must be provided"); return -1; } // Initialize the MPI environment MPI_Init(NULL, NULL); gsl_rng_env_setup(); T = gsl_rng_default; gsl_rng *rgen; rgen = gsl_rng_alloc( T ); // Get the number of processes int world_size; MPI_Comm_size(MPI_COMM_WORLD, &world_size); // Get the rank of the process int world_rank; MPI_Comm_rank(MPI_COMM_WORLD, &world_rank); // Start the timer struct timespec start_time; clock_gettime(CLOCK_REALTIME, &start_time); MPI_Barrier( MPI_COMM_WORLD ); timer_start = MPI_Wtime(); long data_length; process = readProcessFile( state_dim ); data_length = (int)process.n; // Construct the communication hypercube MPI_Comm nthCube; int hc_rank; int nDim; constructHypercube( world_size, &nthCube, &hc_rank, &nDim ); int S = nDim; //--------------- // Initialisation //--------------- x = malloc( sizeof( double ) * N * state_dim ); w = malloc( sizeof( double ) * N ); inds = malloc( sizeof( long ) * N ); x_resamp = malloc( sizeof( double ) * N * state_dim ); // Initial distribution setup setupInitialSeed( world_rank, rgen ); // Create initial sample createInitialSample( x, N, rgen, state_dim ); // Setup the randomisation set_resamplingseed( world_rank ); int output_dim = 2 + state_dim + 2 * world_size + world_size * state_dim; if ( world_rank == MASTER ) output = malloc( sizeof( double ) * output_dim * data_length ); my_normal_weight = 1.0 / world_size; MPI_Barrier( MPI_COMM_WORLD ); init_time += MPI_Wtime() - timer_start; // main loop for( long n = 0; n < data_length; n++ ) { // ------------------------------------------------------------------------------ MPI_Barrier( MPI_COMM_WORLD ); timer_start = MPI_Wtime(); evaluateLikelihoods( x, process, state_dim, data_length, N, n, w, my_normal_weight ); MPI_Barrier( MPI_COMM_WORLD ); weight_time += MPI_Wtime() - timer_start ; // Compute the relevant estimates for THIS filter only estimates = estimateOutput( w, x, world_rank, N, run_idx, state_dim ); // Combine the results of all filters combineEstimates( world_rank, state_dim, estimates, output, n, output_dim, world_size, &total_w, &my_normal_weight, &do_resampling, epc_threshold); // ----------------------------- // RESAMPLING // ----------------------------- // Resampling within processors MPI_Barrier( MPI_COMM_WORLD ); rsamp_start = MPI_Wtime(); serial_multinomial_resample_sng_noutk( N, w, inds, N ); for ( long i = 0; i < N; i++) for ( int d = 0; d < state_dim; d++ ) x_resamp[ state_dim * i + d ] = x[ state_dim * inds[ i ] + d ]; for ( long i = 0; i < N; i++) for ( int d = 0; d < state_dim ; d++ ) x[ state_dim * i + d ] = x_resamp[ state_dim * i + d ]; // ----------------------------------------------------------------------------- MPI_Barrier( MPI_COMM_WORLD ); rsamp_time += MPI_Wtime() - rsamp_start; comm_start = MPI_Wtime(); if ( do_resampling ) { // --------------------------- // START THE RADIX INTERACTION // --------------------------- for ( int s = 0; s < S ; s++ ) { // Determine the process you need to communicate with MPI_Cart_shift( nthCube, s, 1, &src, &pair_rank ); // The lower ranking process in the pair gets the filter weights and // does the island level resampling if ( hc_rank < pair_rank ) { MPI_Recv( w_pair + 1, 1, MPI_DOUBLE, pair_rank, 0, nthCube, MPI_STATUS_IGNORE ); // The lower ranking filter must send its weight to the paired filter // so that the paired filter can update its weight MPI_Send( &my_normal_weight, 1, MPI_DOUBLE, pair_rank, 1, nthCube ); w_pair[ 0 ] = my_normal_weight; // Generate a binomial random variate indicating how many samples // are drawn from each of the paired processes. gsl_ran_multinomial( rgen , ( size_t ) 2, ( unsigned int ) ( 2 ), w_pair, cnts ); counts[ 0 ] = ( short ) cnts[ 0 ]; counts[ 1 ] = ( short ) cnts[ 1 ]; // Send the resampling counts to the paired process MPI_Send( counts + 1 , 1, MPI_SHORT, pair_rank, 3, nthCube ); n_resamp = counts[ 0 ]; } else { // Send my weight to the lower ranking filter in the pair MPI_Send(&my_normal_weight, 1, MPI_DOUBLE, pair_rank, 0, nthCube ); // Receive the weight of the paired filter MPI_Recv( w_pair, 1, MPI_DOUBLE, pair_rank, 1, nthCube, MPI_STATUS_IGNORE ); // Receive the duplicate count ( 0 or 1 ) MPI_Recv( &n_resamp, 1, MPI_SHORT, pair_rank, 3, nthCube, MPI_STATUS_IGNORE ); w_pair[ 1 ] = my_normal_weight; } // ----------------------------------------------------------------------------- MPI_Barrier( MPI_COMM_WORLD ); comm_time2 += MPI_Wtime() - comm_start; comm_start = MPI_Wtime(); // Balance the resampled particle counts if ( n_resamp > 1 ) { // Send the surplus particles, i.e. the last n_resamp - N of the // resampled particles MPI_Send( x, N * state_dim , MPI_DOUBLE, pair_rank, 2, nthCube ); } else if ( n_resamp < 1 ) { // Receive compensation for shortage MPI_Recv( x, N * state_dim, MPI_DOUBLE, pair_rank, 2, nthCube, MPI_STATUS_IGNORE ); } my_normal_weight = ( w_pair[ 0 ] + w_pair[ 1 ] ) / (double ) 2; } } // ----------------------------------------------------------------------------- MPI_Barrier( MPI_COMM_WORLD ); comm_time += MPI_Wtime() - comm_start; timer_start = MPI_Wtime(); mutation(N, x, state_dim, rgen); // ----------------------------------------------------------------------------- MPI_Barrier( MPI_COMM_WORLD ); mutation_time += MPI_Wtime() - timer_start ; } struct timespec end_time; clock_gettime(CLOCK_REALTIME, &end_time); createOutput( ALG, world_rank, output, data_length, world_size, run_idx, N, state_dim, start_time, end_time, comm_time, rsamp_time, comm_time2, weight_time, mutation_time, init_time, (int)( atof( argv[ 4 ] ) * 100 ) ); // Finalize the MPI environment. MPI_Finalize(); return 0; }
{ "alphanum_fraction": 0.5946364105, "avg_line_length": 26.7448275862, "ext": "c", "hexsha": "aa857326d592b833b71d88626808d7feb31024a0", "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": "2b7d74519289d2dac684b483a85ec2696e694c27", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "heinekmp/AIRPF", "max_forks_repo_path": "src/airpf1.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "2b7d74519289d2dac684b483a85ec2696e694c27", "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": "heinekmp/AIRPF", "max_issues_repo_path": "src/airpf1.c", "max_line_length": 85, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2b7d74519289d2dac684b483a85ec2696e694c27", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "heinekmp/AIRPF", "max_stars_repo_path": "src/airpf1.c", "max_stars_repo_stars_event_max_datetime": "2020-05-21T06:38:23.000Z", "max_stars_repo_stars_event_min_datetime": "2020-05-21T06:38:23.000Z", "num_tokens": 2150, "size": 7756 }
#ifndef DDM__ALGORITHM__SUMMA_H_ #define DDM__ALGORITHM__SUMMA_H_ #include "../../ddm/Exception.h" #include "../../ddm/Types.h" #include "../../ddm/Pattern.h" #include "../../ddm/Future.h" #include "../../ddm/algorithm/Copy.h" #include "../../ddm/util/Trace.h" #include <utility> // Prefer MKL if available: #ifdef DDM_ENABLE_MKL #include <mkl.h> #include <mkl_types.h> #include <mkl_cblas.h> #include <mkl_blas.h> #include <mkl_lapack.h> // BLAS support: #elif defined(DDM_ENABLE_BLAS) extern "C" { #include <cblas.h> } #endif #define DDM_ALGORITHM_SUMMA_ASYNC_INIT_PREFETCH namespace ddm { namespace internal { #if defined(DDM_ENABLE_MKL) || defined(DDM_ENABLE_BLAS) /** * Matrix multiplication for local multiplication of matrix blocks via MKL. */ template<typename ValueType> void mmult_local( /// Matrix to multiply, m rows by k columns. const ValueType * A, /// Matrix to multiply, k rows by n columns. const ValueType * B, /// Matrix to contain the multiplication result, m rows by n columns. ValueType * C, long long m, long long n, long long k, MemArrange storage); #else /** * Naive matrix multiplication for local multiplication of matrix blocks, * used only for tests and where MKL is not available. */ template<typename ValueType> void mmult_local( /// Matrix to multiply, extents n x m const ValueType * A, /// Matrix to multiply, extents m x p const ValueType * B, /// Matrix to contain the multiplication result, extents n x p ValueType * C, long long m, long long n, long long p, MemArrange storage) { #ifndef DEBUG DDM_THROW( ddm::exception::RuntimeError, "Called fallback implementation of DGEMM (only enabled in Debug)"); #endif ValueType c_sum = 0; for (auto i = 0; i < n; ++i) { // row i = 0...n for (auto j = 0; j < p; ++j) { // column j = 0...p c_sum = C[i * p + j]; // = C[j][i] for (auto k = 0; k < m; ++k) { // k = 0...m auto ik = i * m + k; auto kj = k * m + j; auto value = A[ik] * B[kj]; c_sum += value; } C[i * p + j] = c_sum; // C[j][i] = c_sum } } } #endif // defined(DDM_ENABLE_MKL) || defined(DDM_ENABLE_BLAS) } // namespace internal /// Constraints on pattern partitioning properties of matrix operands passed /// to \c ddm::summa. typedef ddm::pattern_partitioning_properties< // Block extents are constant for every dimension. ddm::pattern_partitioning_tag::rectangular, // Identical number of elements in every block. ddm::pattern_partitioning_tag::balanced, // Matrices must be partitioned in more than one dimension. ddm::pattern_partitioning_tag::ndimensional > summa_pattern_partitioning_constraints; /// Constraints on pattern mapping properties of matrix operands passed to /// \c ddm::summa. typedef ddm::pattern_mapping_properties< // Every unit mapped to more than one block, required for // block prefetching to take effect. ddm::pattern_mapping_tag::multiple, // Number of blocks assigned to a unit may differ. ddm::pattern_mapping_tag::unbalanced > summa_pattern_mapping_constraints; /// Constraints on pattern layout properties of matrix operands passed to /// \c ddm::summa. typedef ddm::pattern_layout_properties< // Elements are contiguous in local memory within single block. ddm::pattern_layout_tag::blocked, // Local element order corresponds to a logical linearization // within single blocks. // Required for cache-optimized block matrix multiplication. ddm::pattern_layout_tag::linear > summa_pattern_layout_constraints; template<typename MatrixType> using summa_pattern_constraints = typename ddm::pattern_constraints< ddm::summa_pattern_partitioning_constraints, ddm::summa_pattern_mapping_constraints, ddm::summa_pattern_layout_constraints, typename MatrixType::pattern_type>; /** * Multiplies two matrices using the SUMMA algorithm. * Performs \c (2 * (nunits-1) * nunits^2) async copy operations of * submatrices in \c A and \c B. * * Pseudocode: * * C = zeros(n,n) * for k = 1:b:n { // k increments in steps of blocksize b * u = k:(k+b-1) // u is [k, k+1, ..., k+b-1] * C = C + A(:,u) * B(u,:) // Multiply n x b matrix from A with * // b x p matrix from B * } */ template< typename MatrixTypeA, typename MatrixTypeB, typename MatrixTypeC > void summa( /// Matrix to multiply, extents n x m MatrixTypeA & A, /// Matrix to multiply, extents m x p MatrixTypeB & B, /// Matrix to contain the multiplication result, extents n x p, /// initialized with zeros MatrixTypeC & C) { typedef typename MatrixTypeA::value_type value_type; typedef typename MatrixTypeA::index_type index_t; typedef typename MatrixTypeA::size_type extent_t; //typedef typename MatrixTypeA::pattern_type pattern_a_type; //typedef typename MatrixTypeB::pattern_type pattern_b_type; //typedef typename MatrixTypeC::pattern_type pattern_c_type; typedef std::array<index_t, 2> coords_t; const bool shifted_tiling = ddm::pattern_constraints< ddm::pattern_partitioning_properties<>, ddm::pattern_mapping_properties< ddm::pattern_mapping_tag::diagonal >, ddm::pattern_layout_properties<>, typename MatrixTypeC::pattern_type >::satisfied::value; const bool minimal_tiling = ddm::pattern_constraints< ddm::pattern_partitioning_properties< ddm::pattern_partitioning_tag::minimal >, ddm::pattern_mapping_properties<>, ddm::pattern_layout_properties<>, typename MatrixTypeC::pattern_type >::satisfied::value; static_assert( std::is_floating_point<value_type>::value, "ddm::summa expects matrix element type double or float"); DDM_LOG_DEBUG("ddm::summa()"); // Verify that matrix patterns satisfy pattern constraints: if (!ddm::check_pattern_constraints< summa_pattern_partitioning_constraints, summa_pattern_mapping_constraints, summa_pattern_layout_constraints >(A.pattern())) { DDM_THROW( ddm::exception::InvalidArgument, "ddm::summa(): " "pattern of first matrix argument does not match constraints"); } if (!ddm::check_pattern_constraints< summa_pattern_partitioning_constraints, summa_pattern_mapping_constraints, summa_pattern_layout_constraints >(B.pattern())) { DDM_THROW( ddm::exception::InvalidArgument, "ddm::summa(): " "pattern of second matrix argument does not match constraints"); } if (!ddm::check_pattern_constraints< summa_pattern_partitioning_constraints, summa_pattern_mapping_constraints, summa_pattern_layout_constraints >(C.pattern())) { DDM_THROW( ddm::exception::InvalidArgument, "ddm::summa(): " "pattern of result matrix does not match constraints"); } DDM_LOG_TRACE("ddm::summa", "matrix pattern properties valid"); if (shifted_tiling) { DDM_LOG_TRACE("ddm::summa", "using communication scheme for diagonal-shift mapping"); } if (minimal_tiling) { DDM_LOG_TRACE("ddm::summa", "using communication scheme for minimal partitioning"); } // A B C // _____ _____ _____ // | | | | | | // n | x m | = n | // |_ m _| |_ p _| |_ p _| // ddm::Team & team = C.team(); auto unit_id = team.myid(); // Check run-time invariants on pattern instances: auto pattern_a = A.pattern(); auto pattern_b = B.pattern(); auto pattern_c = C.pattern(); auto m = pattern_a.extent(0); // number of columns in A, rows in B #if DDM_ENABLE_TRACE_LOGGING auto n = pattern_a.extent(1); // number of rows in A and C auto p = pattern_b.extent(0); // number of columns in B and C #endif const ddm::MemArrange memory_order = pattern_a.memory_order(); DDM_ASSERT_EQ( pattern_a.extent(1), pattern_b.extent(0), "ddm::summa(): " "Extents of first operand in dimension 1 do not match extents of " "second operand in dimension 0"); DDM_ASSERT_EQ( pattern_c.extent(0), pattern_a.extent(0), "ddm::summa(): " "Extents of result matrix in dimension 0 do not match extents of " "first operand in dimension 0"); DDM_ASSERT_EQ( pattern_c.extent(1), pattern_b.extent(1), "ddm::summa(): " "Extents of result matrix in dimension 1 do not match extents of " "second operand in dimension 1"); DDM_LOG_TRACE("ddm::summa", "matrix pattern extents valid"); // Patterns are balanced, all blocks have identical size: auto block_size_m = pattern_a.block(0).extent(0); auto block_size_n = pattern_b.block(0).extent(1); auto block_size_p = pattern_b.block(0).extent(0); auto num_blocks_m = m / block_size_m; #if DDM_ENABLE_TRACE_LOGGING auto num_blocks_n = n / block_size_n; auto num_blocks_p = p / block_size_p; #endif // Size of temporary local blocks auto block_a_size = block_size_n * block_size_m; auto block_b_size = block_size_m * block_size_p; // Number of units in rows and columns: auto teamspec = C.pattern().teamspec(); auto unit_ts_coords = teamspec.coords(unit_id); DDM_LOG_TRACE("ddm::summa", "blocks:", "m:", num_blocks_m, "*", block_size_m, "n:", num_blocks_n, "*", block_size_n, "p:", num_blocks_p, "*", block_size_p); DDM_LOG_TRACE("ddm::summa", "number of units:", "cols:", teamspec.extent(0), "rows:", teamspec.extent(1), "unit team coords:", unit_ts_coords); DDM_LOG_TRACE("ddm::summa", "allocating local temporary blocks, sizes:", "A:", block_a_size, "B:", block_b_size); #ifdef DDM_ENABLE_MKL value_type * buf_block_a_get = (value_type *)(mkl_malloc( sizeof(value_type) * block_a_size, 64)); value_type * buf_block_b_get = (value_type *)(mkl_malloc( sizeof(value_type) * block_b_size, 64)); value_type * buf_block_a_comp = (value_type *)(mkl_malloc( sizeof(value_type) * block_a_size, 64)); value_type * buf_block_b_comp = (value_type *)(mkl_malloc( sizeof(value_type) * block_b_size, 64)); #else value_type * buf_block_a_get = new value_type[block_a_size]; value_type * buf_block_b_get = new value_type[block_b_size]; value_type * buf_block_a_comp = new value_type[block_a_size]; value_type * buf_block_b_comp = new value_type[block_b_size]; #endif // Copy of buffer pointers for swapping, delete[] on swapped pointers tends // to crash: value_type * local_block_a_get = buf_block_a_get; value_type * local_block_b_get = buf_block_b_get; value_type * local_block_a_comp = buf_block_a_comp; value_type * local_block_b_comp = buf_block_b_comp; value_type * local_block_a_get_bac = nullptr; value_type * local_block_b_get_bac = nullptr; value_type * local_block_a_comp_bac = nullptr; value_type * local_block_b_comp_bac = nullptr; // ------------------------------------------------------------------------- // Prefetch blocks from A and B for first local multiplication: // ------------------------------------------------------------------------- // Block coordinates of submatrices of A and B to be prefetched: // Local block index of local submatrix of C for multiplication result of // blocks to be prefetched: auto l_block_c_get = C.local.block(0); auto l_block_c_get_view = l_block_c_get.begin().viewspec(); index_t l_block_c_get_row = l_block_c_get_view.offset(1) / block_size_n; index_t l_block_c_get_col = l_block_c_get_view.offset(0) / block_size_p; // Block coordinates of blocks in A and B to prefetch: coords_t block_a_get_coords = coords_t {{ static_cast<index_t>(unit_ts_coords[0]), l_block_c_get_row }}; coords_t block_b_get_coords = coords_t {{ l_block_c_get_col, static_cast<index_t>(unit_ts_coords[0]) }}; // Local block index of local submatrix of C for multiplication result of // currently prefetched blocks: auto l_block_c_comp = l_block_c_get; auto l_block_c_comp_view = l_block_c_comp.begin().viewspec(); index_t l_block_c_comp_row = l_block_c_comp_view.offset(1) / block_size_n; index_t l_block_c_comp_col = l_block_c_comp_view.offset(0) / block_size_p; // Prefetch blocks from A and B for computation in next iteration: ddm::Future<value_type *> get_a; ddm::Future<value_type *> get_b; auto block_a = A.block(block_a_get_coords); auto block_a_lptr = block_a.begin().local(); auto block_b = B.block(block_b_get_coords); auto block_b_lptr = block_b.begin().local(); DDM_LOG_TRACE("ddm::summa", "summa.prefetch.block.a", "block:", block_a_get_coords, "local:", block_a_lptr != nullptr, "unit:", block_a.begin().lpos().unit, "view:", block_a.begin().viewspec()); ddm::util::Trace trace("SUMMA"); trace.enter_state("prefetch"); if (block_a_lptr == nullptr) { #ifdef DDM_ALGORITHM_SUMMA_ASYNC_INIT_PREFETCH get_a = ddm::copy_async(block_a.begin(), block_a.end(), local_block_a_comp); #else ddm::copy(block_a.begin(), block_a.end(), local_block_a_comp); get_a = ddm::Future<value_type *>( [=]() { return local_block_a_comp + block_a.size(); }); #endif } else { local_block_a_comp_bac = local_block_a_comp; local_block_a_comp = block_a_lptr; } DDM_LOG_TRACE("ddm::summa", "summa.prefetch.block.b", "block:", block_b_get_coords, "local:", block_b_lptr != nullptr, "unit:", block_b.begin().lpos().unit, "view:", block_b.begin().viewspec()); if (block_b_lptr == nullptr) { #ifdef DDM_ALGORITHM_SUMMA_ASYNC_INIT_PREFETCH get_b = ddm::copy_async(block_b.begin(), block_b.end(), local_block_b_comp); #else ddm::copy(block_b.begin(), block_b.end(), local_block_b_comp); get_b = ddm::Future<value_type *>( [=]() { return local_block_b_comp + block_b.size(); }); #endif } else { local_block_b_comp_bac = local_block_b_comp; local_block_b_comp = block_b_lptr; } #ifdef DDM_ALGORITHM_SUMMA_ASYNC_INIT_PREFETCH if (block_a_lptr == nullptr) { DDM_LOG_TRACE("ddm::summa", "summa.prefetch.block.a.wait", "waiting for prefetching of block A from unit", block_a.begin().lpos().unit); get_a.wait(); } if (block_b_lptr == nullptr) { DDM_LOG_TRACE("ddm::summa", "summa.prefetch.block.b.wait", "waiting for prefetching of block B from unit", block_b.begin().lpos().unit); get_b.wait(); } #endif trace.exit_state("prefetch"); DDM_LOG_TRACE("ddm::summa", "summa.block", "prefetching of blocks completed"); // ------------------------------------------------------------------------- // Iterate local blocks in matrix C: // ------------------------------------------------------------------------- extent_t num_local_blocks_c = pattern_c.local_blockspec().size(); DDM_LOG_TRACE("ddm::summa", "summa.block.C", "C.num.local.blocks:", num_local_blocks_c, "C.num.column.blocks:", num_blocks_m); for (extent_t lb = 0; lb < num_local_blocks_c; ++lb) { // Block coordinates for current block multiplication result: l_block_c_comp = C.local.block(lb); l_block_c_comp_view = l_block_c_comp.begin().viewspec(); l_block_c_comp_row = l_block_c_comp_view.offset(1) / block_size_n; l_block_c_comp_col = l_block_c_comp_view.offset(0) / block_size_p; // Block coordinates for next block multiplication result: l_block_c_get = l_block_c_comp; l_block_c_get_view = l_block_c_comp_view; l_block_c_get_row = l_block_c_get_row; l_block_c_get_col = l_block_c_get_col; DDM_LOG_TRACE("ddm::summa", "summa.block.comp", "C.local.block", "l_block_idx:", lb, "row:", l_block_c_comp_row, "col:", l_block_c_comp_col, "view:", l_block_c_comp_view); // ----------------------------------------------------------------------- // Iterate blocks in columns of A / rows of B: // ----------------------------------------------------------------------- for (extent_t block_k = 0; block_k < num_blocks_m; ++block_k) { DDM_LOG_TRACE("ddm::summa", "summa.block.k", block_k, "active local block in C:", lb); // --------------------------------------------------------------------- // Prefetch local copy of blocks from A and B for multiplication in // next iteration. // --------------------------------------------------------------------- bool last = (lb == num_local_blocks_c - 1) && (block_k == num_blocks_m - 1); // Do not prefetch blocks in last iteration: if (!last) { index_t block_get_k = static_cast<index_t>(block_k + 1); block_get_k = (block_get_k + unit_ts_coords[0]) % num_blocks_m; // Block coordinate of local block in matrix C to prefetch: if (block_k == num_blocks_m - 1) { // Prefetch for next local block in matrix C: block_get_k = unit_ts_coords[0]; l_block_c_get = C.local.block(lb + 1); l_block_c_get_view = l_block_c_get.begin().viewspec(); l_block_c_get_row = l_block_c_get_view.offset(1) / block_size_n; l_block_c_get_col = l_block_c_get_view.offset(0) / block_size_p; } // Block coordinates of blocks in A and B to prefetch: block_a_get_coords = coords_t {{ block_get_k, l_block_c_get_row }}; block_b_get_coords = coords_t {{ l_block_c_get_col, block_get_k }}; block_a = A.block(block_a_get_coords); block_a_lptr = block_a.begin().local(); block_b = B.block(block_b_get_coords); block_b_lptr = block_b.begin().local(); DDM_LOG_TRACE("ddm::summa", "summa.prefetch.block.a", "block:", block_a_get_coords, "local:", block_a_lptr != nullptr, "unit:", block_a.begin().lpos().unit, "view:", block_a.begin().viewspec()); if (block_a_lptr == nullptr) { get_a = ddm::copy_async(block_a.begin(), block_a.end(), local_block_a_get); local_block_a_get_bac = nullptr; } else { local_block_a_get_bac = local_block_a_get; local_block_a_get = block_a_lptr; } DDM_LOG_TRACE("ddm::summa", "summa.prefetch.block.b", "block:", block_b_get_coords, "local:", block_b_lptr != nullptr, "unit:", block_b.begin().lpos().unit, "view:", block_b.begin().viewspec()); if (block_b_lptr == nullptr) { get_b = ddm::copy_async(block_b.begin(), block_b.end(), local_block_b_get); local_block_b_get_bac = nullptr; } else { local_block_b_get_bac = local_block_b_get; local_block_b_get = block_b_lptr; } } else { DDM_LOG_TRACE("ddm::summa", " ->", "last block multiplication", "lb:", lb, "bk:", block_k); } // --------------------------------------------------------------------- // Computation of matrix product of local block matrices: // --------------------------------------------------------------------- DDM_LOG_TRACE("ddm::summa", "summa.block.comp.multiply", "multiplying local block matrices", "C.local.block.comp:", lb, "view:", l_block_c_comp.begin().viewspec()); trace.enter_state("multiply"); ddm::internal::mmult_local<value_type>( local_block_a_comp, local_block_b_comp, l_block_c_comp.begin().local(), block_size_m, block_size_n, block_size_p, memory_order); trace.exit_state("multiply"); if (local_block_a_comp_bac != nullptr) { local_block_a_comp = local_block_a_comp_bac; local_block_a_comp_bac = nullptr; } if (local_block_b_comp_bac != nullptr) { local_block_b_comp = local_block_b_comp_bac; local_block_b_comp_bac = nullptr; } if (!last) { // ------------------------------------------------------------------- // Wait for local copies: // ------------------------------------------------------------------- trace.enter_state("prefetch"); if (block_a_lptr == nullptr) { DDM_LOG_TRACE("ddm::summa", "summa.prefetch.block.a.wait", "waiting for prefetching of block A from unit", block_a.begin().lpos().unit); get_a.wait(); } if (block_b_lptr == nullptr) { DDM_LOG_TRACE("ddm::summa", "summa.prefetch.block.b.wait", "waiting for prefetching of block B from unit", block_b.begin().lpos().unit); get_b.wait(); } DDM_LOG_TRACE("ddm::summa", "summa.prefetch.completed", "local copies of next blocks received"); trace.exit_state("prefetch"); // ----------------------------------------------------------------- // Swap communication and computation buffers: // ----------------------------------------------------------------- std::swap(local_block_a_get, local_block_a_comp); std::swap(local_block_b_get, local_block_b_comp); if (local_block_a_get_bac != nullptr) { local_block_a_comp_bac = local_block_a_get_bac; local_block_a_get_bac = nullptr; } if (local_block_b_get_bac != nullptr) { local_block_b_comp_bac = local_block_b_get_bac; local_block_b_get_bac = nullptr; } } } } // for lb DDM_LOG_TRACE("ddm::summa", "locally completed"); #ifdef DDM_ENABLE_MKL mkl_free(buf_block_a_get); mkl_free(buf_block_b_get); mkl_free(buf_block_a_comp); mkl_free(buf_block_b_comp); #else delete[] buf_block_a_get; delete[] buf_block_b_get; delete[] buf_block_a_comp; delete[] buf_block_b_comp; #endif DDM_LOG_TRACE("ddm::summa", "waiting for other units"); trace.enter_state("barrier"); C.barrier(); trace.exit_state("barrier"); DDM_LOG_TRACE("ddm::summa >", "finished"); } #ifdef DOXYGEN /** * Function adapter to an implementation of matrix-matrix multiplication * (xDGEMM) depending on the matrix distribution patterns. * * Delegates \c ddm::mmult<MatrixType> * to \c ddm::summa<MatrixType> * if \c MatrixType::pattern_type * satisfies the pattern property constraints of the SUMMA implementation. */ template < typename MatrixTypeA, typename MatrixTypeB, typename MatrixTypeC > void mmult( /// Matrix to multiply, extents n x m MatrixTypeA & A, /// Matrix to multiply, extents m x p MatrixTypeB & B, /// Matrix to contain the multiplication result, extents n x p, /// initialized with zeros MatrixTypeC & C); #else // DOXYGEN template < typename MatrixTypeA, typename MatrixTypeB, typename MatrixTypeC > auto mmult( /// Matrix to multiply, extents n x m MatrixTypeA & A, /// Matrix to multiply, extents m x p MatrixTypeB & B, /// Matrix to contain the multiplication result, extents n x p, /// initialized with zeros MatrixTypeC & C) -> typename std::enable_if< summa_pattern_constraints<MatrixTypeA>::satisfied::value && summa_pattern_constraints<MatrixTypeB>::satisfied::value && summa_pattern_constraints<MatrixTypeC>::satisfied::value, void >::type { ddm::summa(A, B, C); } #endif // DOXYGEN } // namespace ddm #endif // DDM__ALGORITHM__SUMMA_H_
{ "alphanum_fraction": 0.5940067474, "avg_line_length": 39.1226708075, "ext": "h", "hexsha": "69b1abe4154d856a11afd9f7100e036201bea787", "lang": "C", "max_forks_count": 6, "max_forks_repo_forks_event_max_datetime": "2020-01-09T03:32:31.000Z", "max_forks_repo_forks_event_min_datetime": "2019-06-03T16:56:43.000Z", "max_forks_repo_head_hexsha": "31df6d22b8aac9a10c1e5c7809913b63ba83d23b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "caixiuhong/Develop-MCCE", "max_forks_repo_path": "yingying_delphi/Delphicpp_v8.4.2_Linux/src/dplt/ddm/algorithm/SUMMA.h", "max_issues_count": 36, "max_issues_repo_head_hexsha": "31df6d22b8aac9a10c1e5c7809913b63ba83d23b", "max_issues_repo_issues_event_max_datetime": "2020-04-17T19:17:26.000Z", "max_issues_repo_issues_event_min_datetime": "2019-06-03T20:30:45.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "caixiuhong/Develop-MCCE", "max_issues_repo_path": "yingying_delphi/Delphicpp_v8.4.2_Linux/src/dplt/ddm/algorithm/SUMMA.h", "max_line_length": 84, "max_stars_count": null, "max_stars_repo_head_hexsha": "31df6d22b8aac9a10c1e5c7809913b63ba83d23b", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "caixiuhong/Develop-MCCE", "max_stars_repo_path": "yingying_delphi/Delphicpp_v8.4.2_Linux/src/dplt/ddm/algorithm/SUMMA.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 5987, "size": 25195 }
#include <stdio.h> #include <gsl/gsl_rng.h> /* https://www.gnu.org/software/gsl/doc/html/rng.html */ /* run as ./a.out 10000 rnd_u.csv */ gsl_rng * r; /* global generator */ int main(int argc, char **argv) { const gsl_rng_type * T; gsl_rng * r; if( argc > 1) { FILE *fp; /* file container for random numbers */ double i, n = atoi( argv[1] ); char *fname = argv[2]; fp = fopen(fname,"w"); if( fp == NULL) { printf("file can't be opened\n"); exit(1); } fprintf( fp, "u\n"); gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc (T); for (i = 0; i < n; i++) { double u = gsl_rng_uniform (r); /* printf ("%.5f\t%s\n", u, fname); */ fprintf( fp, "%.6f\n", u); } fclose(fp); gsl_rng_free (r); } return EXIT_SUCCESS; }
{ "alphanum_fraction": 0.5677749361, "avg_line_length": 15.9591836735, "ext": "c", "hexsha": "2147e7018c5f69b4c937c375d883125caada3d4c", "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": "ca0d124c1cd4c98719371b693d51849c8e895f5b", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "hafermoraes/C_learning", "max_forks_repo_path": "rng/rng.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "ca0d124c1cd4c98719371b693d51849c8e895f5b", "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": "hafermoraes/C_learning", "max_issues_repo_path": "rng/rng.c", "max_line_length": 56, "max_stars_count": null, "max_stars_repo_head_hexsha": "ca0d124c1cd4c98719371b693d51849c8e895f5b", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "hafermoraes/C_learning", "max_stars_repo_path": "rng/rng.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 257, "size": 782 }
#include <stdio.h> #include <gsl/gsl_sf_gamma.h> int main() { printf("hello, world!\n"); printf("%f\n", gsl_sf_gamma(1.0)); printf("%f\n", gsl_sf_gamma(1.5)); printf("%f\n", gsl_sf_gamma(2.0)); printf("%f\n", gsl_sf_gamma(2.5)); printf("%f\n", gsl_sf_gamma(3.0)); }
{ "alphanum_fraction": 0.5841924399, "avg_line_length": 24.25, "ext": "c", "hexsha": "51a471534bcd034202eac1fcee6475d5420d5649", "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": "4c368b12eaaffcf0af8032f10348cf8bc1c3957a", "max_forks_repo_licenses": [ "Unlicense" ], "max_forks_repo_name": "berquist/eg", "max_forks_repo_path": "c/test_libgsl/main.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "4c368b12eaaffcf0af8032f10348cf8bc1c3957a", "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": "berquist/eg", "max_issues_repo_path": "c/test_libgsl/main.c", "max_line_length": 38, "max_stars_count": null, "max_stars_repo_head_hexsha": "4c368b12eaaffcf0af8032f10348cf8bc1c3957a", "max_stars_repo_licenses": [ "Unlicense" ], "max_stars_repo_name": "berquist/eg", "max_stars_repo_path": "c/test_libgsl/main.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 99, "size": 291 }
/* monte/test.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Michael Booth * * 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. */ #include <config.h> #include <stdlib.h> #include <math.h> #include <stdio.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_test.h> #include <gsl/gsl_ieee_utils.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_monte_plain.h> #include <gsl/gsl_monte_miser.h> #include <gsl/gsl_monte_vegas.h> #define CONSTANT #define PRODUCT #define GAUSSIAN #define DBLGAUSSIAN #define TSUDA #define PLAIN #define MISER #define VEGAS double xl[11] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; double xu[11] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; double xu2[11] = { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 }; double xu3[2] = { GSL_DBL_MAX, GSL_DBL_MAX }; double fconst (double x[], size_t d, void *params); double f0 (double x[], size_t d, void *params); double f1 (double x[], size_t d, void *params); double f2 (double x[], size_t d, void *params); double f3 (double x[], size_t d, void *params); void my_error_handler (const char *reason, const char *file, int line, int err); struct problem { gsl_monte_function * f; double * xl; double * xu; size_t dim; size_t calls; double expected_result; double expected_error; char * description; } ; gsl_monte_function make_function (double (*f)(double *, size_t, void *), size_t d, void * p); gsl_monte_function make_function (double (*f)(double *, size_t, void *), size_t d, void * p) { gsl_monte_function f_new; f_new.f = f; f_new.dim = d; f_new.params = p; return f_new; } void add (struct problem * problems, int * n, gsl_monte_function * f, double xl[], double xu[], size_t dim, size_t calls, double result, double err, char * description); void add (struct problem * problems, int * n, gsl_monte_function * f, double xl[], double xu[], size_t dim, size_t calls, double result, double err, char * description) { int i = *n; problems[i].f = f; problems[i].xl = xl; problems[i].xu = xu; problems[i].dim = dim; problems[i].calls = calls; problems[i].expected_result = result; problems[i].expected_error = err; problems[i].description = description; (*n)++; } #define TRIALS 10 int main (void) { double result[TRIALS], error[TRIALS]; double a = 0.1; double c = (1.0 + sqrt (10.0)) / 9.0; gsl_monte_function Fc = make_function(&fconst, 0, 0); gsl_monte_function F0 = make_function(&f0, 0, &a); gsl_monte_function F1 = make_function(&f1, 0, &a); gsl_monte_function F2 = make_function(&f2, 0, &a); gsl_monte_function F3 = make_function(&f3, 0, &c); /* The relationship between the variance of the function itself, the error on the integral and the number of calls is, sigma = sqrt(variance/N) where the variance is the <(f - <f>)^2> where <.> denotes the volume average (integral over the integration region divided by the volume) */ int n = 0; struct problem * I; struct problem problems[256]; #ifdef CONSTANT /* variance(Fc) = 0 */ add(problems,&n, &Fc, xl, xu, 1, 1000, 1.0, 0.0, "constant, 1d"); add(problems,&n, &Fc, xl, xu, 2, 1000, 1.0, 0.0, "constant, 2d"); add(problems,&n, &Fc, xl, xu, 3, 1000, 1.0, 0.0, "constant, 3d"); add(problems,&n, &Fc, xl, xu, 4, 1000, 1.0, 0.0, "constant, 4d"); add(problems,&n, &Fc, xl, xu, 5, 1000, 1.0, 0.0, "constant, 5d"); add(problems,&n, &Fc, xl, xu, 6, 1000, 1.0, 0.0, "constant, 6d"); add(problems,&n, &Fc, xl, xu, 7, 1000, 1.0, 0.0, "constant, 7d"); add(problems,&n, &Fc, xl, xu, 8, 1000, 1.0, 0.0, "constant, 8d"); add(problems,&n, &Fc, xl, xu, 9, 1000, 1.0, 0.0, "constant, 9d"); add(problems,&n, &Fc, xl, xu, 10, 1000, 1.0, 0.0, "constant, 10d"); #endif #ifdef PRODUCT /* variance(F0) = (4/3)^d - 1 */ add(problems,&n, &F0, xl, xu, 1, 3333, 1.0, 0.01, "product, 1d" ); add(problems,&n, &F0, xl, xu, 2, 7777, 1.0, 0.01, "product, 2d" ); add(problems,&n, &F0, xl, xu, 3, 13703, 1.0, 0.01, "product, 3d" ); add(problems,&n, &F0, xl, xu, 4, 21604, 1.0, 0.01, "product, 4d" ); add(problems,&n, &F0, xl, xu, 5, 32139, 1.0, 0.01, "product, 5d" ); add(problems,&n, &F0, xl, xu, 6, 46186, 1.0, 0.01, "product, 6d" ); add(problems,&n, &F0, xl, xu, 7, 64915, 1.0, 0.01, "product, 7d" ); add(problems,&n, &F0, xl, xu, 8, 89887, 1.0, 0.01, "product, 8d" ); add(problems,&n, &F0, xl, xu, 9, 123182, 1.0, 0.01, "product, 9d" ); add(problems,&n, &F0, xl, xu, 10, 167577, 1.0, 0.01, "product, 10d" ); #endif #ifdef GAUSSIAN /* variance(F1) = (1/(a sqrt(2 pi)))^d - 1 */ add(problems,&n, &F1, xl, xu, 1, 298, 1.0, 0.1, "gaussian, 1d" ); add(problems,&n, &F1, xl, xu, 2, 1492, 1.0, 0.1, "gaussian, 2d" ); add(problems,&n, &F1, xl, xu, 3, 6249, 1.0, 0.1, "gaussian, 3d" ); add(problems,&n, &F1, xl, xu, 4, 25230, 1.0, 0.1, "gaussian, 4d" ); add(problems,&n, &F1, xl, xu, 5, 100953, 1.0, 0.1, "gaussian, 5d" ); add(problems,&n, &F1, xl, xu, 6, 44782, 1.0, 0.3, "gaussian, 6d" ); add(problems,&n, &F1, xl, xu, 7, 178690, 1.0, 0.3, "gaussian, 7d" ); add(problems,&n, &F1, xl, xu, 8, 712904, 1.0, 0.3, "gaussian, 8d" ); add(problems,&n, &F1, xl, xu, 9, 2844109, 1.0, 0.3, "gaussian, 9d" ); add(problems,&n, &F1, xl, xu, 10, 11346390, 1.0, 0.3, "gaussian, 10d" ); #endif #ifdef DBLGAUSSIAN /* variance(F2) = 0.5 * (1/(a sqrt(2 pi)))^d - 1 */ add(problems,&n, &F2, xl, xu, 1, 9947, 1.0, 0.01, "double gaussian, 1d" ); add(problems,&n, &F2, xl, xu, 2, 695, 1.0, 0.1, "double gaussian, 2d" ); add(problems,&n, &F2, xl, xu, 3, 3074, 1.0, 0.1, "double gaussian, 3d" ); add(problems,&n, &F2, xl, xu, 4, 12565, 1.0, 0.1, "double gaussian, 4d" ); add(problems,&n, &F2, xl, xu, 5, 50426, 1.0, 0.1, "double gaussian, 5d" ); add(problems,&n, &F2, xl, xu, 6, 201472, 1.0, 0.1, "double gaussian, 6d" ); add(problems,&n, &F2, xl, xu, 7, 804056, 1.0, 0.1, "double gaussian, 7d" ); add(problems,&n, &F2, xl, xu, 8, 356446, 1.0, 0.3, "double gaussian, 8d" ); add(problems,&n, &F2, xl, xu, 9, 1422049, 1.0, 0.3, "double gaussian, 9d" ); add(problems,&n, &F2, xl, xu, 10, 5673189, 1.0, 0.3, "double gaussian, 10d" ); #endif #ifdef TSUDA /* variance(F3) = ((c^2 + c + 1/3)/(c(c+1)))^d - 1 */ add(problems,&n, &F3, xl, xu, 1, 4928, 1.0, 0.01, "tsuda function, 1d" ); add(problems,&n, &F3, xl, xu, 2, 12285, 1.0, 0.01, "tsuda function, 2d" ); add(problems,&n, &F3, xl, xu, 3, 23268, 1.0, 0.01, "tsuda function, 3d" ); add(problems,&n, &F3, xl, xu, 4, 39664, 1.0, 0.01, "tsuda function, 4d" ); add(problems,&n, &F3, xl, xu, 5, 64141, 1.0, 0.01, "tsuda function, 5d" ); add(problems,&n, &F3, xl, xu, 6, 100680, 1.0, 0.01, "tsuda function, 6d" ); add(problems,&n, &F3, xl, xu, 7, 155227, 1.0, 0.01, "tsuda function, 7d" ); add(problems,&n, &F3, xl, xu, 8, 236657, 1.0, 0.01, "tsuda function, 8d" ); add(problems,&n, &F3, xl, xu, 9, 358219, 1.0, 0.01, "tsuda function, 9d" ); add(problems,&n, &F3, xl, xu, 10, 539690, 1.0, 0.01, "tsuda function, 10d" ); #endif add(problems,&n, 0, 0, 0, 0, 0, 0, 0, 0 ); /* gsl_set_error_handler (&my_error_handler); */ gsl_ieee_env_setup (); gsl_rng_env_setup (); #ifdef A printf ("testing allocation/input checks\n"); status = gsl_monte_plain_validate (s, xl, xu3, 1, 1); gsl_test (status != 0, "error if limits too large"); status = gsl_monte_plain_validate (s, xl, xu, 0, 10); gsl_test (status != 0, "error if num_dim = 0"); status = gsl_monte_plain_validate (s, xl, xu, 1, 0); gsl_test (status != 0, "error if calls = 0"); status = gsl_monte_plain_validate (s, xu, xl, 1, 10); gsl_test (status != 0, "error if xu < xl"); #endif #ifdef PLAIN #define NAME "plain" #define MONTE_STATE gsl_monte_plain_state #define MONTE_ALLOC gsl_monte_plain_alloc #define MONTE_INTEGRATE gsl_monte_plain_integrate #define MONTE_FREE gsl_monte_plain_free #define MONTE_SPEEDUP 1 #define MONTE_ERROR_TEST(err,expected) gsl_test_factor(err,expected, 5.0, NAME ", %s, abserr[%d]", I->description, i) #include "test_main.c" #undef NAME #undef MONTE_STATE #undef MONTE_ALLOC #undef MONTE_INTEGRATE #undef MONTE_FREE #undef MONTE_ERROR_TEST #undef MONTE_SPEEDUP #endif #ifdef MISER #define NAME "miser" #define MONTE_STATE gsl_monte_miser_state #define MONTE_ALLOC gsl_monte_miser_alloc #define MONTE_INTEGRATE gsl_monte_miser_integrate #define MONTE_FREE gsl_monte_miser_free #define MONTE_SPEEDUP 2 #define MONTE_ERROR_TEST(err,expected) gsl_test(err > 5.0 * expected, NAME ", %s, abserr[%d] (obs %g vs plain %g)", I->description, i, err, expected) #include "test_main.c" #undef NAME #undef MONTE_STATE #undef MONTE_ALLOC #undef MONTE_INTEGRATE #undef MONTE_FREE #undef MONTE_ERROR_TEST #undef MONTE_SPEEDUP #endif #ifdef VEGAS #define NAME "vegas" #define MONTE_STATE gsl_monte_vegas_state #define MONTE_ALLOC gsl_monte_vegas_alloc #define MONTE_INTEGRATE(f,xl,xu,dim,calls,r,s,res,err) { gsl_monte_vegas_integrate(f,xl,xu,dim,calls,r,s,res,err) ; if (s->chisq < 0.5 || s->chisq > 2) gsl_monte_vegas_integrate(f,xl,xu,dim,calls,r,s,res,err); } #define MONTE_FREE gsl_monte_vegas_free #define MONTE_SPEEDUP 3 #define MONTE_ERROR_TEST(err,expected) gsl_test(err > 3.0 * (expected == 0 ? 1.0/(I->calls/MONTE_SPEEDUP) : expected), NAME ", %s, abserr[%d] (obs %g vs exp %g)", I->description, i, err, expected) #include "test_main.c" #undef NAME #undef MONTE_STATE #undef MONTE_ALLOC #undef MONTE_INTEGRATE #undef MONTE_FREE #undef MONTE_ERROR_TEST #undef MONTE_SPEEDUP #endif exit (gsl_test_summary ()); } /* Simple constant function */ double fconst (double x[], size_t num_dim, void *params) { return 1; } /* Simple product function */ double f0 (double x[], size_t num_dim, void *params) { double prod = 1.0; unsigned int i; for (i = 0; i < num_dim; ++i) { prod *= 2.0 * x[i]; } return prod; } /* Gaussian centered at 1/2. */ double f1 (double x[], size_t num_dim, void *params) { double a = *(double *)params; double sum = 0.; unsigned int i; for (i = 0; i < num_dim; i++) { double dx = x[i] - 0.5; sum += dx * dx; } return (pow (M_2_SQRTPI / (2. * a), (double) num_dim) * exp (-sum / (a * a))); } /* double gaussian */ double f2 (double x[], size_t num_dim, void *params) { double a = *(double *)params; double sum1 = 0.; double sum2 = 0.; unsigned int i; for (i = 0; i < num_dim; i++) { double dx1 = x[i] - 1. / 3.; double dx2 = x[i] - 2. / 3.; sum1 += dx1 * dx1; sum2 += dx2 * dx2; } return 0.5 * pow (M_2_SQRTPI / (2. * a), num_dim) * (exp (-sum1 / (a * a)) + exp (-sum2 / (a * a))); } /* Tsuda's example */ double f3 (double x[], size_t num_dim, void *params) { double c = *(double *)params; double prod = 1.; unsigned int i; for (i = 0; i < num_dim; i++) { prod *= c / (c + 1) * pow((c + 1) / (c + x[i]), 2.0); } return prod; } void my_error_handler (const char *reason, const char *file, int line, int err) { if (0) printf ("(caught [%s:%d: %s (%d)])\n", file, line, reason, err); }
{ "alphanum_fraction": 0.6195424453, "avg_line_length": 31.9064171123, "ext": "c", "hexsha": "2c2da55dfc3986af84ef189de33db9e480bda6e5", "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/monte/test.c", "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/monte/test.c", "max_line_length": 211, "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/monte/test.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": 4732, "size": 11933 }
#include <math.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_roots.h> #include <gsl/gsl_sf_hyperg.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_math.h> #include <fastpm/libfastpm.h> void fastpm_horizon_init(FastPMHorizon * horizon, FastPMCosmology * cosmology) { gsl_set_error_handler_off(); // Turn off GSL error handler horizon->cosmology = cosmology; horizon->size = 8192; horizon->da = 1.0 / (horizon->size - 1); int i; for (i = 0; i < horizon->size; i ++) { double a = 1.0 * i / (horizon->size - 1); horizon->xi_a[i] = HubbleDistance * ComovingDistance(a, horizon->cosmology); FastPMGrowthInfo gi; fastpm_growth_info_init(&gi, a, horizon->cosmology); horizon->growthfactor_a[i] = gi.D1; } } void fastpm_horizon_destroy(FastPMHorizon * horizon) { } double HorizonDistance(double a, FastPMHorizon * horizon) { double x = a * (horizon->size - 1); int l = floor(x); int r = l + 1; if(r >= horizon->size) { return horizon->xi_a[horizon->size - 1]; } if(l <= 0) { return horizon->xi_a[0]; } return horizon->xi_a[l] * (r - x) + horizon->xi_a[r] * (x - l); } double HorizonGrowthFactor(double a, FastPMHorizon * horizon) { double x = a * (horizon->size - 1); int l = floor(x); int r = l + 1; if(r >= horizon->size) { return horizon->growthfactor_a[horizon->size - 1]; } if(l <= 0) { return horizon->growthfactor_a[0]; } return horizon->growthfactor_a[l] * (r - x) + horizon->growthfactor_a[r] * (x - l); } void * fastpm_horizon_solve_start() { const gsl_root_fsolver_type *T = gsl_root_fsolver_brent; return gsl_root_fsolver_alloc(T); } void fastpm_horizon_solve_end(void * context) { gsl_root_fsolver_free(context); } int fastpm_horizon_solve(FastPMHorizon * horizon, void * context, double * solution, double a_i, double a_f, double (*func)(double a, void * userdata), void * userdata) { int status; int iter = 0, max_iter; double r, x_lo=a_i, x_hi=a_f, eps; /* Reorganize to struct later */ max_iter = 20; eps = 1e-5; gsl_function F; F.function = func; F.params = userdata; status = gsl_root_fsolver_set(context, &F, x_lo, x_hi); if(status == GSL_EINVAL || status == GSL_EDOM) { /** Error in value or out of range **/ return 0; } do { iter++; // // Debug printout #1 //if(iter == 1) { //fastpm_info("ID | [x_lo, x_hi] | r | funct(r) | x_hi - x_lo\n"); //} // status = gsl_root_fsolver_iterate(context); r = gsl_root_fsolver_root(context); x_lo = gsl_root_fsolver_x_lower(context); x_hi = gsl_root_fsolver_x_upper(context); status = gsl_root_test_interval(x_lo, x_hi, eps, 0.0); // //Debug printout #2 //fastpm_info("%5d [%.7f, %.7f] %.7f %.7f %.7f\n", iter, x_lo, x_hi, r, funct(r, &params), x_hi - x_lo); // if(status == GSL_SUCCESS || iter == max_iter ) { *solution = r; // // Debug printout #3.1 //fastpm_info("fastpm_lc_intersect() called with parameters %.7f and %.7f, returned status %d.\n\n", a, b, 1); // return 1; } } while (status == GSL_CONTINUE); // // Debug printout #3.2 //fastpm_info("fastpm_lc_intersect() called with parameters %.7f and %.7f, returned status %d.\n\n", a, b, 0); // return 0; }
{ "alphanum_fraction": 0.580581981, "avg_line_length": 24.3129251701, "ext": "c", "hexsha": "8a0620a8afe4aa03df702cc7b2bb2607dda1b826", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-04-14T23:24:19.000Z", "max_forks_repo_forks_event_min_datetime": "2021-04-14T23:24:19.000Z", "max_forks_repo_head_hexsha": "f38f6e69c603fb699436b645fe7b4eb418ee82c2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "sbird/FastPMRunner", "max_forks_repo_path": "fastpm/libfastpm/horizon.c", "max_issues_count": 4, "max_issues_repo_head_hexsha": "f38f6e69c603fb699436b645fe7b4eb418ee82c2", "max_issues_repo_issues_event_max_datetime": "2022-01-24T05:51:04.000Z", "max_issues_repo_issues_event_min_datetime": "2021-04-19T23:01:33.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "sbird/FastPMRunner", "max_issues_repo_path": "fastpm/libfastpm/horizon.c", "max_line_length": 122, "max_stars_count": null, "max_stars_repo_head_hexsha": "f38f6e69c603fb699436b645fe7b4eb418ee82c2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "sbird/FastPMRunner", "max_stars_repo_path": "fastpm/libfastpm/horizon.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1075, "size": 3574 }
#include <viaio/Vlib.h> #include <viaio/VImage.h> #include <viaio/mu.h> #include <viaio/option.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <gsl/gsl_cblas.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_statistics.h> #include <gsl/gsl_sort.h> #include <gsl/gsl_wavelet.h> #include <gsl/gsl_wavelet2d.h> extern void gsl_sort_vector(gsl_vector *); #define ABS(x) ((x) > 0 ? (x) : -(x)) void WriteTest(gsl_matrix *data) { FILE *fp=0; VAttrList alist; VImage tmp; double u; int i,j; tmp = VCreateImage(1,data->size1,data->size2,VFloatRepn); for (i = 0; i < data->size1; i++) { for (j = 0; j < data->size2; j++) { u = gsl_matrix_get(data,i,j); VPixel(tmp,0,i,j,VFloat) = u; } } alist = VCreateAttrList(); VAppendAttr(alist,"image",NULL,VImageRepn,tmp); fp = fopen("qtest.v","w"); VWriteFile (fp,alist); fclose(fp); exit(0); } double estimateSigma(gsl_matrix *data) { int i,j,i2,j2,n,nn; gsl_vector *vec=NULL; double median=0,med0,u,xmax,tiny=1.0e-6; i2 = data->size1/2; j2 = data->size2/2; nn = 3 * (i2+1) * (j2+1); vec = gsl_vector_calloc(nn); /* ** first pass, median, no absolute values */ xmax = VRepnMaxValue(VDoubleRepn); gsl_vector_set_all(vec,xmax); n = 0; for (i=0; i<i2; i++) { for (j=j2; j<data->size2; j++) { u = gsl_matrix_get(data,i,j); if (ABS(u) > tiny) gsl_vector_set(vec,n++,u); } } for (i=i2; i<data->size1; i++) { for (j=0; j<j2; j++) { u = gsl_matrix_get(data,i,j); if (ABS(u) > tiny) gsl_vector_set(vec,n++,u); } } for (i=i2; i<data->size1; i++) { for (j=j2; j<data->size2; j++) { u = gsl_matrix_get(data,i,j); if (ABS(u) > tiny) gsl_vector_set(vec,n++,u); } } gsl_sort_vector(vec); u = (double)n/2.0; nn = (int)u; med0 = 0.5*(gsl_vector_get(vec,nn) + gsl_vector_get(vec,nn+1)); /* ** median, 2nd pass */ xmax = VRepnMaxValue(VDoubleRepn); gsl_vector_set_all(vec,xmax); n = 0; for (i=0; i<i2; i++) { for (j=j2; j<data->size2; j++) { u = gsl_matrix_get(data,i,j); if (ABS(u) <= tiny) continue; u = ABS(u - med0); gsl_vector_set(vec,n++,u); } } for (i=i2; i<data->size1; i++) { for (j=0; j<j2; j++) { u = gsl_matrix_get(data,i,j); if (ABS(u) <= tiny) continue; u = ABS(u - med0); gsl_vector_set(vec,n++,u); } } for (i=i2; i<data->size1; i++) { for (j=j2; j<data->size2; j++) { u = gsl_matrix_get(data,i,j); if (ABS(u) <= tiny) continue; u = ABS(u - med0); gsl_vector_set(vec,n++,u); } } gsl_sort_vector(vec); u = (double)n/2.0; nn = (int)u; median = 0.5*(gsl_vector_get(vec,nn) + gsl_vector_get(vec,nn+1)); return (median/0.455); } double sgn(double x) { if (x < 0) return -1; else if (x > 0) return 1; else return 0; } void Filtering(gsl_matrix *data, int type, double intensity, double sigma) { int i,j,n; double d,dd,alpha; n = data->size1; double tau = sigma * intensity * sqrt(2 * log10((double) (n*n))); for (i=0; i < data->size1; i++) { for (j=0; j < data->size2; j++) { d = gsl_matrix_get(data,i,j); /* Wiener-Filter */ if (type == 0) { alpha = ((d * d) - intensity * (sigma * sigma)) / (d * d); if (alpha < 0) alpha = 0; d *= alpha; } /* Soft-Threshold */ else if (type == 1) { if (ABS(d) < tau) dd = 0; else dd = sgn(d) * (ABS(d) - tau); d = dd; } /* Hard-Threshold */ else if (type == 2) { if (ABS(d) < tau) d = 0; } gsl_matrix_set(data,i,j,d); } } } void Shift(gsl_matrix *data,gsl_matrix *shiftdata,int ishift,int jshift) { int i,j,ii,jj,n; double u; gsl_matrix_set_zero(shiftdata); n = data->size1; for (i=0; i<n; i++) { ii = i+ishift; if (ii < 0 || ii >= n) continue; for (j=0; j<n; j++) { jj = j+jshift; if (jj < 0 || jj >= n) continue; u = gsl_matrix_get(data,i,j); gsl_matrix_set(shiftdata,ii,jj,u); } } } void AddShift(gsl_matrix *data,gsl_matrix *shiftdata,int ishift,int jshift) { int i,j,ii,jj,n; double u,v; n = data->size1; for (i=0; i<n; i++) { ii = i+ishift; if (ii < 0 || ii >= n) continue; for (j=0; j<n; j++) { jj = j+jshift; if (jj < 0 || jj >= n) continue; u = gsl_matrix_get(data,i,j); v = gsl_matrix_get(shiftdata,ii,jj); u = u+v; gsl_matrix_set(data,i,j,u); } } } VImage VWavelets(VImage src,VImage dest,int filtertype,int wtype,int nshift,double level) { static gsl_wavelet_workspace *work=NULL; static gsl_wavelet *w=NULL; static gsl_matrix *data=NULL,*tmp=NULL,*shiftdata=NULL; int nslices,nrows,ncols,i,j,slice,n,size,dim; double u,sum1,sum2,nx,mean,sig,sigma=0,avesig; extern VFloat VGetPixelValue (VImage,int); /* ** read image info */ nslices = VImageNBands(src); nrows = VImageNRows(src); ncols = VImageNColumns(src); if (dest == NULL) dest = VCreateImage(nslices,nrows,ncols,VPixelRepn(src)); VCopyImageAttrs (src, dest); VFillImage(dest,VAllBands,0); size = nrows; if (nrows < ncols) size = ncols; n = (int) ceil(log10((double) size) / log10(2.0)); dim = (int) pow(2.0, (double) n); /* ** ini wavelets transform */ if (work == NULL) { switch (wtype) { case 0: w = gsl_wavelet_alloc (gsl_wavelet_haar_centered,2); break; case 1: w = gsl_wavelet_alloc (gsl_wavelet_daubechies_centered,4); break; case 2: w = gsl_wavelet_alloc (gsl_wavelet_daubechies_centered,6); break; case 3: w = gsl_wavelet_alloc (gsl_wavelet_daubechies_centered,8); break; case 4: w = gsl_wavelet_alloc (gsl_wavelet_bspline_centered,103); break; case 5: w = gsl_wavelet_alloc (gsl_wavelet_bspline_centered,202); break; default: VError("illegal wavelet type"); } work = gsl_wavelet_workspace_alloc (dim); data = gsl_matrix_calloc(dim,dim); shiftdata = gsl_matrix_calloc(dim,dim); tmp = gsl_matrix_calloc(dim,dim); } avesig = 0; for (slice=0; slice<nslices; slice++) { /* ** read data */ sum1 = sum2 = nx = 0; for (i=0; i<nrows; i++) { for (j=0; j<ncols; j++) { u = VGetPixel(src,slice,i,j); sum1 += u; sum2 += u*u; nx++; } } mean = sum1/nx; sig = sqrt((sum2 - nx * mean * mean) / (nx - 1.0)); if (sig < 1.0e-3) { VFillImage(dest,slice,0); continue; } gsl_matrix_set_zero(data); for (i=0; i<nrows; i++) { for (j=0; j<ncols; j++) { u = VGetPixel(src,slice,i,j); u = (u-mean)/sig; gsl_matrix_set(data,i,j,u); } } gsl_matrix_memcpy(tmp,data); /* ** get sigma estimate (Donoho) */ if (gsl_wavelet2d_nstransform_matrix_forward(w,data,work) != GSL_SUCCESS) VError(" gsl_wavelet2d_nstransform_matrix_forward failed"); sigma = estimateSigma(data); /* fprintf(stderr," slice: %3d %f\n",slice,sigma); */ avesig += sigma; Filtering(data,filtertype,level,sigma); gsl_wavelet2d_nstransform_matrix_inverse(w,data,work); /* ** translation invariance, shift 4/8 algorithm */ nx = 1; for (i=-nshift; i<=nshift; i++) { for (j=-nshift; j<=nshift; j++) { if (i == 0 && j == 0) continue; Shift(tmp,shiftdata,i,j); gsl_wavelet2d_nstransform_matrix_forward(w,shiftdata,work); Filtering(shiftdata,filtertype,level,sigma); gsl_wavelet2d_nstransform_matrix_inverse(w,shiftdata,work); AddShift(data,shiftdata,i,j); nx++; } } gsl_matrix_scale(data,1.0/nx); /* ** output */ for (i=0; i<nrows; i++) { for (j=0; j<ncols; j++) { u = gsl_matrix_get(data,i,j); u = sig*u + mean; if (u < VPixelMinValue(dest)) u = VPixelMinValue(dest); if (u > VPixelMaxValue(dest)) u = VPixelMaxValue(dest); VSetPixel(dest,slice,i,j,u); } } } avesig /= (double)nslices; /* fprintf(stderr," kappa: %f\n",sqrt(avesig) * 1.75); */ /* gsl_matrix_free(shiftdata); gsl_matrix_free(tmp); gsl_wavelet_free (w); gsl_wavelet_workspace_free (work); free (data); */ return dest; } VDictEntry WDict[] = { { "haar", 0 }, { "daub4", 1 }, { "daub6", 2 }, { "daub8", 3 }, { "bspline103", 4 }, { "bspline202", 5 }, { NULL } }; int main (int argc,char *argv[]) { static VShort ftype = 0; static VShort wtype = 0; static VShort nshift = 1; static VDouble level = 0.5; static VOptionDescRec options[] = { {"wavelet",VShortRepn,1,(VPointer) &wtype,VOptionalOpt,WDict,"wavelet type"}, {"filter",VShortRepn,1,(VPointer) &ftype,VOptionalOpt,NULL,"filter type"}, {"shift",VShortRepn,1,(VPointer) &nshift,VOptionalOpt,NULL,"shift window size"}, {"level",VDoubleRepn,1,(VPointer) &level,VOptionalOpt,NULL,"level"} }; FILE *in_file,*out_file; VAttrList list=NULL; VAttrListPosn posn; VImage src=NULL,dest=NULL; int n=0,nimages=0; char *prg=GetLipsiaName("vdenoise"); fprintf (stderr, "%s\n", prg); VParseFilterCmd (VNumber (options),options,argc,argv,&in_file,&out_file); if (! (list = VReadFile (in_file, NULL))) exit (1); fclose(in_file); nimages = 0; for (VFirstAttr (list, & posn); VAttrExists (& posn); VNextAttr (& posn)) { if (VGetAttrRepn (& posn) == VImageRepn) nimages++; } n = 0; for (VFirstAttr (list, & posn); VAttrExists (& posn); VNextAttr (& posn)) { if (VGetAttrRepn (& posn) != VImageRepn) continue; VGetAttrValue (& posn, NULL,VImageRepn, & src); fprintf(stderr," image %4d of %d\r",n,nimages); dest = VWavelets(src,dest,(int)ftype,(int)wtype,(int)nshift,level); src = VCopyImage(dest,src,VAllBands); VSetAttrValue (& posn, NULL,VImageRepn,src); n++; } if (src == NULL) VError(" no input image found"); VHistory(VNumber(options),options,prg,&list,&list); if (! VWriteFile (out_file, list)) exit (1); fprintf (stderr, "%s: done.\n", argv[0]); return 0; }
{ "alphanum_fraction": 0.5890138322, "avg_line_length": 22.2815964523, "ext": "c", "hexsha": "895c682901d9eccb2f520bca1331c6952f067709", "lang": "C", "max_forks_count": 8, "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z", "max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z", "max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zrajna/lipsia", "max_forks_repo_path": "src/prep/vdenoise/vdenoise.c", "max_issues_count": 7, "max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z", "max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zrajna/lipsia", "max_issues_repo_path": "src/prep/vdenoise/vdenoise.c", "max_line_length": 84, "max_stars_count": 17, "max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zrajna/lipsia", "max_stars_repo_path": "src/prep/vdenoise/vdenoise.c", "max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z", "max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z", "num_tokens": 3477, "size": 10049 }
#ifndef OPENMC_PHOTON_H #define OPENMC_PHOTON_H #include "openmc/endf.h" #include "openmc/memory.h" // for unique_ptr #include "openmc/particle.h" #include "openmc/vector.h" #include <gsl/gsl> #include <hdf5.h> #include "xtensor/xtensor.hpp" #include <string> #include <unordered_map> #include <utility> // for pair namespace openmc { //============================================================================== //! Photon interaction data for a single element //============================================================================== class ElectronSubshell { public: // Constructors ElectronSubshell() { }; int index_subshell; //!< index in SUBSHELLS int threshold; double n_electrons; double binding_energy; xt::xtensor<double, 1> cross_section; // Transition data int n_transitions; xt::xtensor<int, 2> transition_subshells; xt::xtensor<double, 1> transition_energy; xt::xtensor<double, 1> transition_probability; }; class PhotonInteraction { public: // Constructors/destructor PhotonInteraction(hid_t group); ~PhotonInteraction(); // Methods void calculate_xs(Particle& p) const; void compton_scatter(double alpha, bool doppler, double* alpha_out, double* mu, int* i_shell, uint64_t* seed) const; double rayleigh_scatter(double alpha, uint64_t* seed) const; void pair_production(double alpha, double* E_electron, double* E_positron, double* mu_electron, double* mu_positron, uint64_t* seed) const; void atomic_relaxation(const ElectronSubshell& shell, Particle& p) const; // Data members std::string name_; //!< Name of element, e.g. "Zr" int Z_; //!< Atomic number gsl::index index_; //!< Index in global elements vector // Microscopic cross sections xt::xtensor<double, 1> energy_; xt::xtensor<double, 1> coherent_; xt::xtensor<double, 1> incoherent_; xt::xtensor<double, 1> photoelectric_total_; xt::xtensor<double, 1> pair_production_total_; xt::xtensor<double, 1> pair_production_electron_; xt::xtensor<double, 1> pair_production_nuclear_; xt::xtensor<double, 1> heating_; // Form factors Tabulated1D incoherent_form_factor_; Tabulated1D coherent_int_form_factor_; Tabulated1D coherent_anomalous_real_; Tabulated1D coherent_anomalous_imag_; // Photoionization and atomic relaxation data std::unordered_map<int, int> shell_map_; //!< Given a shell designator, e.g. 3, this //!< dictionary gives an index in shells_ vector<ElectronSubshell> shells_; // Compton profile data xt::xtensor<double, 2> profile_pdf_; xt::xtensor<double, 2> profile_cdf_; xt::xtensor<double, 1> binding_energy_; xt::xtensor<double, 1> electron_pdf_; // Stopping power data double I_; // mean excitation energy xt::xtensor<int, 1> n_electrons_; xt::xtensor<double, 1> ionization_energy_; xt::xtensor<double, 1> stopping_power_radiative_; // Bremsstrahlung scaled DCS xt::xtensor<double, 2> dcs_; private: void compton_doppler(double alpha, double mu, double* E_out, int* i_shell, uint64_t* seed) const; }; //============================================================================== // Non-member functions //============================================================================== std::pair<double, double> klein_nishina(double alpha, uint64_t* seed); void free_memory_photon(); //============================================================================== // Global variables //============================================================================== namespace data { extern xt::xtensor<double, 1> compton_profile_pz; //! Compton profile momentum grid //! Photon interaction data for each element extern std::unordered_map<std::string, int> element_map; extern vector<unique_ptr<PhotonInteraction>> elements; } // namespace data } // namespace openmc #endif // OPENMC_PHOTON_H
{ "alphanum_fraction": 0.6379222108, "avg_line_length": 29.8320610687, "ext": "h", "hexsha": "ca8f75474d0c9209cafd081e367903b346696dab", "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": "a9e85f4d5b59d133c17caccf4704a032184841d4", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "cjwyett/openmc", "max_forks_repo_path": "include/openmc/photon.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "a9e85f4d5b59d133c17caccf4704a032184841d4", "max_issues_repo_issues_event_max_datetime": "2021-05-21T17:34:35.000Z", "max_issues_repo_issues_event_min_datetime": "2020-05-22T07:57:36.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "cjwyett/openmc", "max_issues_repo_path": "include/openmc/photon.h", "max_line_length": 86, "max_stars_count": 1, "max_stars_repo_head_hexsha": "a9e85f4d5b59d133c17caccf4704a032184841d4", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "cjwyett/openmc", "max_stars_repo_path": "include/openmc/photon.h", "max_stars_repo_stars_event_max_datetime": "2020-02-07T20:23:33.000Z", "max_stars_repo_stars_event_min_datetime": "2020-02-07T20:23:33.000Z", "num_tokens": 944, "size": 3908 }
#include <stdio.h> #include <gsl/gsl_monte.h> #include <gsl/gsl_monte_vegas.h> #include <gsl/gsl_math.h> #include "timer.c" #include "timer.h" extern double g (double *t, size_t dim, void *params); double dipole_approx (double r); double gaussian (double *x, int dim); int main (void) { double res, err; size_t dim = 6; double x1[] = { 0., 0., 0., 0., 0., 0., }; double xu[] = { 1., 1., 1., 1., 1., 1., }; double distmin = 1.001; double distmax = 4.; double dist; int np = 20; double nt = (distmax - distmin) / (np - 1); double vegas[20], dipole[20], distance[20]; gsl_rng *r = gsl_rng_alloc (gsl_rng_taus2); unsigned long seed = 1UL; gsl_rng_set (r, seed); size_t calls = 1000000; dist = distmin; gsl_monte_function G = { &g, dim, &dist }; gsl_monte_vegas_state *sv = gsl_monte_vegas_alloc (dim); gsl_monte_vegas_init (sv); // Vegas Integration /*commented so does not output in order to create a proper res printf ("# Stat Dist E(r) ErrEst Dipolapprox\n"); */ timer_start (); for (int i = 0; i < np; i++) { gsl_monte_vegas_integrate (&G, x1, xu, dim, calls / 5, r, sv, &res, &err); do { gsl_monte_vegas_integrate (&G, x1, xu, dim, calls, r, sv, &res, &err); } while (fabs (gsl_monte_vegas_chisq (sv) - 1.0) > 0.2); fflush (stdout); dist += nt; vegas[i] = res; distance[i] = dist; dipole[i] = -2. / pow (dist, 3.); } timer_stop(); gsl_monte_vegas_free (sv); double sum; double x[6]; long i, j, nn; nn = 1000000; timer_start (); double home[20]; dist = distmin; for (j = 0; j < np; j++) { sum = 0.; for (i = 0; i < nn; i++) { for (int k = 0; k < (int) dim; k++) { x[k] = gsl_rng_uniform (r); } sum += g (x, dim, &dist); } res = sum/nn; dist += nt; home[j] = res; } timer_stop (); gsl_rng_free (r); double homeerr = 0.0; for (int e = 0; e < np; e++) { homeerr += fabs(home[e] - vegas[e]); } printf("# Dist Vegas Home Dipolapprox\n"); for( int l = 0; l < np; l++) { double dd = distance[l]; double vv = fabs(vegas[l]); double hh = fabs(home[l]); double di = fabs(dipole[l]); printf(" %.6f %.6f %.6f %.6f\n", dd, vv, hh, di); } return 0; }
{ "alphanum_fraction": 0.5039619651, "avg_line_length": 21.0333333333, "ext": "c", "hexsha": "8bb5abd328999908d32ad62315868ed45cd7e0a9", "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": "2e3d329923c49728e9c86f503266777f44fe0eaf", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "basantrk/fin2", "max_forks_repo_path": "main.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "2e3d329923c49728e9c86f503266777f44fe0eaf", "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": "basantrk/fin2", "max_issues_repo_path": "main.c", "max_line_length": 84, "max_stars_count": null, "max_stars_repo_head_hexsha": "2e3d329923c49728e9c86f503266777f44fe0eaf", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "basantrk/fin2", "max_stars_repo_path": "main.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 836, "size": 2524 }
#include <pthread.h> #include <stdlib.h> #include <cblas.h> #include "tasks.h" void update_task_seq(void *ptr) { struct update_task_arg *arg = (struct update_task_arg*) ptr; int nrows = arg->nrows; int ncols = arg->ncols; int nrhs = arg->nrhs; double *L = arg->L; int ldL = arg->ldL; double *X = arg->X; int ldX = arg->ldX; double *B = arg->B; int ldB = arg->ldB; // Allocate temporary storage W. int ldW = nrows; double *W = (double*) malloc(sizeof(*W) * ldW * nrhs); // Compute W := L * X. cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, nrows, nrhs, ncols, 1.0, L, ldL, X, ldX, 0.0, W, ldW); // Acquire lock. pthread_mutex_lock(arg->Block); // Update B := B - W. #define B(i,j) B[(i) + (j) * ldB] #define W(i,j) W[(i) + (j) * ldW] for (int j = 0; j < nrhs; ++j) { for (int i = 0; i < nrows; ++i) { B(i,j) -= W(i,j); } } #undef B #undef W // Release lock. pthread_mutex_unlock(arg->Block); // Free temporary storage. free(W); }
{ "alphanum_fraction": 0.5126416739, "avg_line_length": 21.641509434, "ext": "c", "hexsha": "312e83564b0bbff87318a9ed3ecb522471ea6b7b", "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": "222736152bc9448e55fc32da5ca55281a92bb4d5", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "NLAFET/pcp-runtime", "max_forks_repo_path": "src/examples/dtrsm/task-update-seq.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "222736152bc9448e55fc32da5ca55281a92bb4d5", "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": "NLAFET/pcp-runtime", "max_issues_repo_path": "src/examples/dtrsm/task-update-seq.c", "max_line_length": 64, "max_stars_count": null, "max_stars_repo_head_hexsha": "222736152bc9448e55fc32da5ca55281a92bb4d5", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "NLAFET/pcp-runtime", "max_stars_repo_path": "src/examples/dtrsm/task-update-seq.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 371, "size": 1147 }
/* integration/qagp.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 <stdlib.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_integration.h> static int qagp (const gsl_function *f, const double *pts, const size_t npts, const double epsabs, const double epsrel, const size_t limit, gsl_integration_workspace * workspace, double *result, double *abserr, gsl_integration_rule * q); #include "initialise.c" #include "qpsrt.c" #include "util.c" #include "append.c" #include "reset.c" #include "qelg.c" #include "qpsrt2.c" #include "ptsort.c" #include "positivity.c" int gsl_integration_qagp (const gsl_function *f, double * pts, size_t npts, double epsabs, double epsrel, size_t limit, gsl_integration_workspace * workspace, double * result, double * abserr) { int status = qagp (f, pts, npts, epsabs, epsrel, limit, workspace, result, abserr, &gsl_integration_qk21) ; return status ; } static int qagp (const gsl_function * f, const double *pts, const size_t npts, const double epsabs, const double epsrel, const size_t limit, gsl_integration_workspace * workspace, double *result, double *abserr, gsl_integration_rule * q) { double area, errsum; double res_ext, err_ext; double result0, abserr0, resabs0; double tolerance; double ertest = 0; double error_over_large_intervals = 0; double reseps = 0, abseps = 0, correc = 0; size_t ktmin = 0; int roundoff_type1 = 0, roundoff_type2 = 0, roundoff_type3 = 0; int error_type = 0, error_type2 = 0; size_t iteration = 0; int positive_integrand = 0; int extrapolate = 0; int disallow_extrapolation = 0; struct extrapolation_table table; const size_t nint = npts - 1; /* number of intervals */ size_t *ndin = workspace->level; /* temporarily alias ndin to level */ size_t i; /* Initialize results */ *result = 0; *abserr = 0; /* Test on validity of parameters */ if (limit > workspace->limit) { GSL_ERROR ("iteration limit exceeds available workspace", GSL_EINVAL) ; } if (npts > workspace->limit) { GSL_ERROR ("npts exceeds size of workspace", GSL_EINVAL); } if (epsabs <= 0 && (epsrel < 50 * GSL_DBL_EPSILON || epsrel < 0.5e-28)) { GSL_ERROR ("tolerance cannot be acheived with given epsabs and epsrel", GSL_EBADTOL); } /* Check that the integration range and break points are an ascending sequence */ for (i = 0; i < nint; i++) { if (pts[i + 1] < pts[i]) { GSL_ERROR ("points are not in an ascending sequence", GSL_EINVAL); } } /* Perform the first integration */ result0 = 0; abserr0 = 0; resabs0 = 0; initialise (workspace, 0.0, 0.0) ; for (i = 0; i < nint; i++) { double area1, error1, resabs1, resasc1; const double a1 = pts[i]; const double b1 = pts[i + 1]; q (f, a1, b1, &area1, &error1, &resabs1, &resasc1); result0 = result0 + area1; abserr0 = abserr0 + error1; resabs0 = resabs0 + resabs1; append_interval (workspace, a1, b1, area1, error1); if (error1 == resasc1 && error1 != 0.0) { ndin[i] = 1; } else { ndin[i] = 0; } } /* Compute the initial error estimate */ errsum = 0.0; for (i = 0; i < nint; i++) { if (ndin[i]) { workspace->elist[i] = abserr0; } errsum = errsum + workspace->elist[i]; } for (i = 0; i < nint; i++) { workspace->level[i] = 0; } /* Sort results into order of decreasing error via the indirection array order[] */ sort_results (workspace); /* Test on accuracy */ tolerance = GSL_MAX_DBL (epsabs, epsrel * fabs (result0)); if (abserr0 <= 100 * GSL_DBL_EPSILON * resabs0 && abserr0 > tolerance) { *result = result0; *abserr = abserr0; GSL_ERROR ("cannot reach tolerance because of roundoff error" "on first attempt", GSL_EROUND); } else if (abserr0 <= tolerance) { *result = result0; *abserr = abserr0; return GSL_SUCCESS; } else if (limit == 1) { *result = result0; *abserr = abserr0; GSL_ERROR ("a maximum of one iteration was insufficient", GSL_EMAXITER); } /* Initialization */ initialise_table (&table); append_table (&table, result0); area = result0; res_ext = result0; err_ext = GSL_DBL_MAX; error_over_large_intervals = errsum; ertest = tolerance; positive_integrand = test_positivity (result0, resabs0); iteration = nint - 1; do { size_t current_level; double a1, b1, a2, b2; double a_i, b_i, r_i, e_i; double area1 = 0, area2 = 0, area12 = 0; double error1 = 0, error2 = 0, error12 = 0; double resasc1, resasc2; double resabs1, resabs2; double last_e_i; /* Bisect the subinterval with the largest error estimate */ retrieve (workspace, &a_i, &b_i, &r_i, &e_i); current_level = workspace->level[workspace->i] + 1; a1 = a_i; b1 = 0.5 * (a_i + b_i); a2 = b1; b2 = b_i; iteration++; q (f, a1, b1, &area1, &error1, &resabs1, &resasc1); q (f, a2, b2, &area2, &error2, &resabs2, &resasc2); area12 = area1 + area2; error12 = error1 + error2; last_e_i = e_i; /* Improve previous approximations to the integral and test for accuracy. We write these expressions in the same way as the original QUADPACK code so that the rounding errors are the same, which makes testing easier. */ errsum = errsum + error12 - e_i; area = area + area12 - r_i; tolerance = GSL_MAX_DBL (epsabs, epsrel * fabs (area)); if (resasc1 != error1 && resasc2 != error2) { double delta = r_i - area12; if (fabs (delta) <= 1.0e-5 * fabs (area12) && error12 >= 0.99 * e_i) { if (!extrapolate) { roundoff_type1++; } else { roundoff_type2++; } } if (i > 10 && error12 > e_i) { roundoff_type3++; } } /* Test for roundoff and eventually set error flag */ if (roundoff_type1 + roundoff_type2 >= 10 || roundoff_type3 >= 20) { error_type = 2; /* round off error */ } if (roundoff_type2 >= 5) { error_type2 = 1; } /* set error flag in the case of bad integrand behaviour at a point of the integration range */ if (subinterval_too_small (a1, a2, b2)) { error_type = 4; } /* append the newly-created intervals to the list */ update (workspace, a1, b1, area1, error1, a2, b2, area2, error2); if (errsum <= tolerance) { goto compute_result; } if (error_type) { break; } if (iteration >= limit - 1) { error_type = 1; break; } if (disallow_extrapolation) { continue; } error_over_large_intervals += -last_e_i; if (current_level < workspace->maximum_level) { error_over_large_intervals += error12; } if (!extrapolate) { /* test whether the interval to be bisected next is the smallest interval. */ if (large_interval (workspace)) continue; extrapolate = 1; workspace->nrmax = 1; } /* The smallest interval has the largest error. Before bisecting decrease the sum of the errors over the larger intervals (error_over_large_intervals) and perform extrapolation. */ if (!error_type2 && error_over_large_intervals > ertest) { if (increase_nrmax (workspace)) continue; } /* Perform extrapolation */ append_table (&table, area); if (table.n < 3) { goto skip_extrapolation; } qelg (&table, &reseps, &abseps); ktmin++; if (ktmin > 5 && err_ext < 0.001 * errsum) { error_type = 5; } if (abseps < err_ext) { ktmin = 0; err_ext = abseps; res_ext = reseps; correc = error_over_large_intervals; ertest = GSL_MAX_DBL (epsabs, epsrel * fabs (reseps)); if (err_ext <= ertest) break; } /* Prepare bisection of the smallest interval. */ if (table.n == 1) { disallow_extrapolation = 1; } if (error_type == 5) { break; } skip_extrapolation: reset_nrmax (workspace); extrapolate = 0; error_over_large_intervals = errsum; } while (iteration < limit); *result = res_ext; *abserr = err_ext; if (err_ext == GSL_DBL_MAX) goto compute_result; if (error_type || error_type2) { if (error_type2) { err_ext += correc; } if (error_type == 0) error_type = 3; if (result != 0 && area != 0) { if (err_ext / fabs (res_ext) > errsum / fabs (area)) goto compute_result; } else if (err_ext > errsum) { goto compute_result; } else if (area == 0.0) { goto return_error; } } /* Test on divergence. */ { double max_area = GSL_MAX_DBL (fabs (res_ext), fabs (area)); if (!positive_integrand && max_area < 0.01 * resabs0) goto return_error; } { double ratio = res_ext / area; if (ratio < 0.01 || ratio > 100 || errsum > fabs (area)) error_type = 6; } goto return_error; compute_result: *result = sum_results (workspace); *abserr = errsum; return_error: if (error_type > 2) error_type--; if (error_type == 0) { return GSL_SUCCESS; } else if (error_type == 1) { GSL_ERROR ("number of iterations was insufficient", GSL_EMAXITER); } else if (error_type == 2) { GSL_ERROR ("cannot reach tolerance because of roundoff error", GSL_EROUND); } else if (error_type == 3) { GSL_ERROR ("bad integrand behavior found in the integration interval", GSL_ESING); } else if (error_type == 4) { GSL_ERROR ("roundoff error detected in the extrapolation table", GSL_EROUND); } else if (error_type == 5) { GSL_ERROR ("integral is divergent, or slowly convergent", GSL_EDIVERGE); } else { GSL_ERROR ("could not integrate function", GSL_EFAILED); } }
{ "alphanum_fraction": 0.5627537212, "avg_line_length": 23.1389432485, "ext": "c", "hexsha": "fc8e039ff4330491e104a10adeb19f83bffaf6d5", "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/integration/qagp.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/integration/qagp.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/integration/qagp.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": 3221, "size": 11824 }
#pragma once #include <memory> #include "halley/text/halleystring.h" #include "halley/core/graphics/texture.h" #include <gsl/gsl> namespace Halley { enum class ShaderType; class MaterialDataBlock; class Material; enum class ShaderParameterType; class Painter; class MaterialDefinition; class MaterialParameter; class MaterialTextureParameter; class VideoAPI; class MaterialConstantBuffer { public: virtual ~MaterialConstantBuffer() {} virtual void update(const MaterialDataBlock& dataBlock) = 0; }; enum class MaterialDataBlockType { // Shared blocks are not stored locally in the material (e.g. the HalleyBlock, stored by the engine) SharedLocal, // Shared, this keeps the canonical copy SharedExternal, // Shared, only a reference Local // Local data }; class MaterialDataBlock { friend class Material; public: MaterialDataBlock(); MaterialDataBlock(MaterialDataBlockType type, size_t size, int bindPoint, const String& name, const MaterialDefinition& def); MaterialDataBlock(const MaterialDataBlock& other); MaterialDataBlock(MaterialDataBlock&& other) noexcept; MaterialConstantBuffer& getConstantBuffer() const; int getAddress(int pass, ShaderType stage) const; int getBindPoint() const; gsl::span<const gsl::byte> getData() const; MaterialDataBlockType getType() const; private: std::unique_ptr<MaterialConstantBuffer> constantBuffer; Bytes data; Vector<int> addresses; MaterialDataBlockType dataBlockType; int bindPoint = 0; bool dirty = true; bool setUniform(size_t offset, ShaderParameterType type, const void* data); void upload(VideoAPI* api); }; class Material { friend class MaterialParameter; public: Material(const Material& other); explicit Material(std::shared_ptr<const MaterialDefinition> materialDefinition, bool forceLocalBlocks = false); // forceLocalBlocks is for engine use only void bind(int pass, Painter& painter); void uploadData(Painter& painter); static void resetBindCache(); bool operator==(const Material& material) const; bool operator!=(const Material& material) const; const MaterialDefinition& getDefinition() const { return *materialDefinition; } std::shared_ptr<Material> clone() const; const std::shared_ptr<const Texture>& getTexture(int textureUnit) const; const Vector<MaterialTextureParameter>& getTextureUniforms() const; const std::vector<std::shared_ptr<const Texture>>& getTextures() const; const Vector<MaterialParameter>& getUniforms() const; const Vector<MaterialDataBlock>& getDataBlocks() const; void setPassEnabled(int pass, bool enabled); bool isPassEnabled(int pass) const; Material& set(const String& name, const std::shared_ptr<const Texture>& texture); Material& set(const String& name, const std::shared_ptr<Texture>& texture); bool hasParameter(const String& name) const; template <typename T> Material& set(const String& name, const T& value) { getParameter(name) = value; return *this; } uint64_t getHash() const; private: std::shared_ptr<const MaterialDefinition> materialDefinition; Vector<MaterialParameter> uniforms; Vector<MaterialTextureParameter> textureUniforms; Vector<MaterialDataBlock> dataBlocks; std::vector<std::shared_ptr<const Texture>> textures; std::vector<char> passEnabled; mutable uint64_t hashValue = 0; mutable bool needToUpdateHash = true; bool needToUploadData = true; void initUniforms(bool forceLocalBlocks); MaterialParameter& getParameter(const String& name); void setUniform(int blockNumber, size_t offset, ShaderParameterType type, const void* data); uint64_t computeHash() const; const std::shared_ptr<const Texture>& getFallbackTexture() const; }; }
{ "alphanum_fraction": 0.7595948827, "avg_line_length": 28.8615384615, "ext": "h", "hexsha": "65801cc3f62382e63f716241b802fa07629840c4", "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": "dcd5ad2631eadd40ec952355577ac0d894d530d4", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Bearwaves/halley", "max_forks_repo_path": "src/engine/core/include/halley/core/graphics/material/material.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "dcd5ad2631eadd40ec952355577ac0d894d530d4", "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": "Bearwaves/halley", "max_issues_repo_path": "src/engine/core/include/halley/core/graphics/material/material.h", "max_line_length": 156, "max_stars_count": null, "max_stars_repo_head_hexsha": "dcd5ad2631eadd40ec952355577ac0d894d530d4", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "Bearwaves/halley", "max_stars_repo_path": "src/engine/core/include/halley/core/graphics/material/material.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 888, "size": 3752 }
/** * @file bblas_sutil.c * * @brief BBLAS testing utilities for float routines. * * BBLAS is a software package provided by Univ. of Manchester, * Univ. of Tennessee. * * @version 1.0.0 * @author Samuel D. Relton * @author Pedro V. Lara * @author Mawussi Zounon * @date 2016-02-20 * * Contains routines used in the testing to modify randomly generated matrices * and compute the average error over an entire batch etc. * **/ #ifndef DOXYGEN_SHOULD_SKIP_THIS /** * Code generation * @generated from bblas_zutil.c normal z -> s, Mon Jun 6 09:44:13 2016 **/ #endif #include "bblas_common.h" #if defined(BBLAS_WITH_MKL) #include <mkl_lapacke.h> #else #include <lapacke.h> #endif /** Include real functions since using float real precision **/ #define REAL /** Quick access to the matrix elements **/ #define A(i,j) A[i + j*lda] /** * Make a matrix symmetric/symmetric. Makes diagonal real. * Sets Aji = conj( Aij ) for j < i, that is, copy & conjugate * lower triangle to upper triangle. **/ void bblas_smake_symmetric(int lda, int N, float* A) { int i, j; for( i=0; i < N; ++i ) { A(i,i) = creal( A(i,i) ); for( j=0; j < i; ++j ) { A(j,i) = conj( A(i,j) ); } } } #ifdef COMPLEX /** * Make a matrix real-symmetric * Does NOT make diagonal real. * Sets Aji = Aij for j < i, that is, * copy lower triangle to upper triangle. **/ void bblas_smake_symmetric(int lda, int N, float* A) { int i, j; for( i=0; i < N; ++i ) { for( j=0; j < i; ++j ) { A(j,i) = A(i,j); } } } #endif /** * irandRange generates a random value (int) * in the range min_n and max_n **/ int irandRange(int min_n, int max_n) { return rand() % (max_n - min_n + 1) + min_n; } /** * bblas_srandRange generates a random value (float) * in the range [0,max_n]: TODO replace by generic */ float bblas_srandRange( int max_n ) { return ( float )rand()/( float )( RAND_MAX/max_n ); } /** * Computes statistics of the relative errors to summarise them for the user. **/ void bblas_sstatistic(bblas_stest_t *test) { enum BBLAS_ROUTINE routine = test->routine; /*Compute avg(M), avg(N), avg(K) */ if(test->batch_opts == BBLAS_VARIABLE) { if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) || (routine == BBLAS_TRMM) || (routine == BBLAS_TRSM)) { test->avgM = bblas_avgarrayI(test->M, test->batch_count); } if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYRK) || (routine == BBLAS_HERK) || (routine == BBLAS_SYR2K) || (routine == BBLAS_HER2K)) { test->avgK = bblas_avgarrayI(test->K, test->batch_count); } test->avgN = bblas_avgarrayI(test->N, test->batch_count); } else if (test->batch_opts == BBLAS_FIXED) { if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) || (routine == BBLAS_TRMM) || (routine == BBLAS_TRSM)) { test->avgM = test->M[0]; } if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYRK) || (routine == BBLAS_HERK) || (routine == BBLAS_SYR2K) || (routine == BBLAS_HER2K)) { test->avgK = test->K[0]; } test->avgN = test->N[0]; } else { bblas_error("testing_sgemm_batch.c", "wrong batch_opts value"); } /*Statistics on the error */ switch(test->target) { case BBLAS_MKL: test->mkl_min_error = bblas_sminarrayD(test->mkl_error, test->batch_count); test->mkl_avg_error = bblas_savgarrayD(test->mkl_error, test->batch_count); test->mkl_max_error = bblas_smaxarrayD(test->mkl_error, test->batch_count); test->mkl_std_error = bblas_sstdarrayD(test->mkl_error, test->batch_count); break; case BBLAS_CUBLAS: case BBLAS_MAGMA: test->device_min_error = bblas_sminarrayD(test->device_error, test->batch_count); test->device_avg_error = bblas_savgarrayD(test->device_error, test->batch_count); test->device_max_error = bblas_smaxarrayD(test->device_error, test->batch_count); test->device_std_error = bblas_sstdarrayD(test->device_error, test->batch_count); break; case BBLAS_OTHER: test->other_min_error = bblas_sminarrayD(test->other_error, test->batch_count); test->other_avg_error = bblas_savgarrayD(test->other_error, test->batch_count); test->other_max_error = bblas_smaxarrayD(test->other_error, test->batch_count); test->other_std_error = bblas_sstdarrayD(test->other_error, test->batch_count); break; default: printf("In bblas_sstatistic(): Target no defined\n"); exit(EXIT_FAILURE); } } /** * Print a matrix. **/ void bblas_sprintmatrix(float *matrix, int row, int col) { /*Local variables */ int i, j; for (i=0; i < row; i++) { printf("\n\n"); for (j=0; j < col; j++) { #ifdef COMPLEX printf("%1.2f + %1.2f\t", creal(matrix[i*col+j]), cimag(matrix[i*col+j])); #else printf("%1.2f",matrix[i*col+j]); #endif } } printf("\n"); } /** * Decide whether a batch is fixed or variable. **/ char* bblas_getoption(enum BBLAS_OPTS opts) { /*Local variable */ char funcname[] = "bblas_getoption"; switch(opts) { case BBLAS_VARIABLE: return "BATCH OPTION: VARIABLE"; break; case BBLAS_FIXED: return "BATCH OPTION: FIXED"; break; default: printf("ERROR in %s, undefined bblas routine name\n",funcname); exit(EXIT_FAILURE); } } /** * Get the name of the current test routine. **/ char* bblas_getroutine(enum BBLAS_ROUTINE routine) { /*Local variable */ char funcname[] = "bblas_getroutine"; switch(routine) { case BBLAS_GEMM: return "SGEMM"; break; case BBLAS_HEMM: return "SSYMM"; break; case BBLAS_HER2K: return "SSYR2K"; break; case BBLAS_HERK: return "SSYRK"; break; case BBLAS_SYMM: return "SSYMM"; break; case BBLAS_SYR2K: return "SSYR2K"; break; case BBLAS_SYRK: return "SSYRK"; break; case BBLAS_TRMM: return "STRMM"; break; case BBLAS_TRSM: return "STRSM"; break; default: printf("ERROR in %s, undefined bblas routine name\n",funcname); exit(EXIT_FAILURE); } } /** * Computes the maximum value of an array of real floats. **/ float bblas_smaxarrayD(float *myArray, int size) { int iter; float maxValue = myArray[0]; for (iter = 0; iter < size; ++iter) { if ( myArray[iter] > maxValue ) { maxValue = myArray[iter]; } } return maxValue; } /** * Computes the minimum value of an array of real floats. **/ float bblas_sminarrayD(float *myArray, int size) { int iter; float minValue = myArray[0]; for (iter = 0; iter < size; ++iter) { if ( myArray[iter] < minValue ) { minValue = myArray[iter]; } } return minValue; } /** * Computes the mean value of an array of real floats. **/ float bblas_savgarrayD(float *myArray, int size) { int iter; float avg = 0.; for (iter = 0; iter < size; ++iter) { avg += myArray[iter]; } return avg/size; } /** * Computes the standard deviation of an array of real floats. **/ float bblas_sstdarrayD(float *myArray, int size) { int iter; float avg, sd=0.; avg = bblas_savgarrayD(myArray, size); for (iter = 0; iter < size; ++iter) { sd += (myArray[iter] -avg)*(myArray[iter] -avg); } return sd/size; } /** * Computes the minimum value of an array of integers. **/ int bblas_minarrayI(int *myArray, int size) { int iter; int minValue = myArray[0]; for (iter = 0; iter < size; ++iter) { if ( myArray[iter] < minValue ) { minValue = myArray[iter]; } } return minValue; } /** * Computes the mean of an array of integers. **/ int bblas_avgarrayI(int *myArray, int size) { int iter; int avg = 0; for (iter = 0; iter < size; ++iter) { avg += myArray[iter]; } return avg/size; } /** * Transform BBLAS enum values for <tt>trans</tt>, <tt>uplo</tt> etc. to human-readable strings. **/ char* bblas_op2char(unsigned int op) { char *opname = (char*)malloc(30*sizeof(char)); switch(op) { case BblasNoTrans: strcpy(opname,"CblasNoTrans"); break; case BblasTrans: strcpy(opname,"CblasTrans"); break; case BblasConjTrans: strcpy(opname,"CblasConjTrans"); break; case BblasLower: strcpy(opname,"CblasLower"); break; case BblasUpper: strcpy(opname,"CblasUpper"); break; case BblasNonUnit: strcpy(opname,"CblasNonUnit"); break; case BblasUnit: strcpy(opname,"CblasUnit"); break; case BblasLeft: strcpy(opname,"CblasLeft"); break; case BblasRight: strcpy(opname,"CblasRight"); break; default: return 0; exit(EXIT_FAILURE); } return opname; } /** * Get the amount of data needed. **/ int bblas_snbdata(bblas_stest_t *test) { enum BBLAS_OPTS batch_opts = test->batch_opts; int nb_data; char function_name[NAME_LENGTH] ="bblas_getdatacount"; switch(batch_opts) { case BBLAS_VARIABLE: nb_data = test->batch_count; break; case BBLAS_FIXED: nb_data = 1; break; default: bblas_fatal_error(function_name, "wrong batch_opts value"); } return nb_data; } /** * Inject an error into the computation if this is set in the input file. **/ void bblas_sset_error(bblas_stest_t *test) { int nb_data = bblas_snbdata(test); int routine = test->routine; int error_index = irandRange(0, nb_data); if (test->global_error){ test->batch_count = -1; return; } if (test->batch_opts == BBLAS_FIXED) { error_index = 0; } if (test->set_error) { if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) || (routine == BBLAS_TRMM) || (routine == BBLAS_TRSM)) { test->M[error_index] = -1; }else if ((routine == BBLAS_SYRK) || (routine == BBLAS_HERK) || (routine == BBLAS_SYR2K)|| (routine == BBLAS_HER2K)) { test->K[error_index] = -1; } } } /** * Check whether a computation has passed or failed our accuracy test. * When new_accuracy=1 in the input file this uses an appropriate * forward/backward error bound, * otherwise this looks at the relative error. **/ void bblas_spassed_failed(bblas_stest_t *test, float error, char *result, int info) { float eps = LAPACKE_slamch_work('e'); /* Use our new accuracy test based on forward/backward error analysis*/ if (test->new_accuracy) { if( (error > 1) || (info)) { strcpy(result, "FAILED"); }else { strcpy(result, "PASSED"); } }else { /* Use old accuracy test based on the relative error */ if((error > eps*test->tolerance) || (info)) { strcpy(result, "FAILED"); }else { strcpy(result, "PASSED"); } } } /** * Set the batch_count. **/ void bblas_sset_batch_count(bblas_stest_t *test) { test->batch_count = test->minbatch_count* (test->current_iter+1); } #undef REAL
{ "alphanum_fraction": 0.6092867232, "avg_line_length": 20.3010752688, "ext": "c", "hexsha": "928f5a0f4292c85e34f474d48901370af93ff7ca", "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": "7f3bef184d4d7a9a8b5685185e16f77e5d317e6d", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "NLAFET/BBLAS-ref", "max_forks_repo_path": "testing/bblas_sutil.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "7f3bef184d4d7a9a8b5685185e16f77e5d317e6d", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "NLAFET/BBLAS-ref", "max_issues_repo_path": "testing/bblas_sutil.c", "max_line_length": 96, "max_stars_count": null, "max_stars_repo_head_hexsha": "7f3bef184d4d7a9a8b5685185e16f77e5d317e6d", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "NLAFET/BBLAS-ref", "max_stars_repo_path": "testing/bblas_sutil.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3324, "size": 11328 }
///////////////////////////////////////////////////////////////////// // = NMatrix // // A linear algebra library for scientific computation in Ruby. // NMatrix is part of SciRuby. // // NMatrix was originally inspired by and derived from NArray, by // Masahiro Tanaka: http://narray.rubyforge.org // // == Copyright Information // // SciRuby is Copyright (c) 2010 - 2014, Ruby Science Foundation // NMatrix is Copyright (c) 2012 - 2014, John Woods and the Ruby Science Foundation // // Please see LICENSE.txt for additional copyright notices. // // == Contributing // // By contributing source code to SciRuby, you agree to be bound by // our Contributor Agreement: // // * https://github.com/SciRuby/sciruby/wiki/Contributor-Agreement // // == inc.h // // Includes needed for LAPACK, CLAPACK, and CBLAS functions. // #ifndef INC_H # define INC_H extern "C" { // These need to be in an extern "C" block or you'll get all kinds of undefined symbol errors. #if defined HAVE_CBLAS_H #include <cblas.h> #elif defined HAVE_ATLAS_CBLAS_H #include <atlas/cblas.h> #endif #if defined HAVE_CLAPACK_H #include <clapack.h> #elif defined HAVE_ATLAS_CLAPACK_H #include <atlas/clapack.h> #endif } #endif // INC_H
{ "alphanum_fraction": 0.6809563067, "avg_line_length": 25.2708333333, "ext": "h", "hexsha": "11a9594693135142cde344600b2e406b55242a71", "lang": "C", "max_forks_count": 131, "max_forks_repo_forks_event_max_datetime": "2022-03-04T13:51:54.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-16T08:01:31.000Z", "max_forks_repo_head_hexsha": "2152aa690dc394ff92a5340f53b6d24268ac0668", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "VasiliCekaskin/nmatrix", "max_forks_repo_path": "ext/nmatrix_atlas/math_atlas/inc.h", "max_issues_count": 317, "max_issues_repo_head_hexsha": "2152aa690dc394ff92a5340f53b6d24268ac0668", "max_issues_repo_issues_event_max_datetime": "2022-03-12T18:09:48.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-05T22:47:39.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "VasiliCekaskin/nmatrix", "max_issues_repo_path": "ext/nmatrix_atlas/math_atlas/inc.h", "max_line_length": 107, "max_stars_count": 329, "max_stars_repo_head_hexsha": "2152aa690dc394ff92a5340f53b6d24268ac0668", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "VasiliCekaskin/nmatrix", "max_stars_repo_path": "ext/nmatrix_atlas/math_atlas/inc.h", "max_stars_repo_stars_event_max_datetime": "2022-03-20T08:57:43.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-09T16:47:40.000Z", "num_tokens": 317, "size": 1213 }